file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.4.24; // File: openzeppelin-zos/contracts/introspection/ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { 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 ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); 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 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 _data ) public; } // File: openzeppelin-zos/contracts/token/ERC721/ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { 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); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the 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 transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // File: openzeppelin-zos/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; 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 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) { assert(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; assert(c >= a); return c; } } // File: openzeppelin-zos/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: openzeppelin-zos/contracts/introspection/ERC165Support.sol /** * @title ERC165Support * @dev Implements ERC165 returning true for ERC165 interface identifier */ contract ERC165Support is ERC165 { bytes4 internal constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return _supportsInterface(_interfaceId); } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return _interfaceId == InterfaceId_ERC165; } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC165Support, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721 || _interfaceId == InterfaceId_ERC721Exists; } /** * @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)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner 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)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @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); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @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) { 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 != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _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 canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_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 `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 canTransfer(_tokenId) { // solium-disable-next-line arg-overflow 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 `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 _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @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) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _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 by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: zos-lib/contracts/migrations/Migratable.sol /** * @title Migratable * Helper contract to support intialization and migration schemes between * different implementations of a contract in the context of upgradeability. * To use it, replace the constructor with a function that has the * `isInitializer` modifier starting with `"0"` as `migrationId`. * When you want to apply some migration code during an upgrade, increase * the `migrationId`. Or, if the migration code must be applied only after * another migration has been already applied, use the `isMigration` modifier. * This helper supports multiple inheritance. * WARNING: It is the developer's responsibility to ensure that migrations are * applied in a correct order, or that they are run at all. * See `Initializable` for a simpler version. */ contract Migratable { /** * @dev Emitted when the contract applies a migration. * @param contractName Name of the Contract. * @param migrationId Identifier of the migration applied. */ event Migrated(string contractName, string migrationId); /** * @dev Mapping of the already applied migrations. * (contractName => (migrationId => bool)) */ mapping (string => mapping (string => bool)) internal migrated; /** * @dev Internal migration id used to specify that a contract has already been initialized. */ string constant private INITIALIZED_ID = "initialized"; /** * @dev Modifier to use in the initialization function of a contract. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ modifier isInitializer(string contractName, string migrationId) { validateMigrationIsPending(contractName, INITIALIZED_ID); validateMigrationIsPending(contractName, migrationId); _; emit Migrated(contractName, migrationId); migrated[contractName][migrationId] = true; migrated[contractName][INITIALIZED_ID] = true; } /** * @dev Modifier to use in the migration of a contract. * @param contractName Name of the contract. * @param requiredMigrationId Identifier of the previous migration, required * to apply new one. * @param newMigrationId Identifier of the new migration to be applied. */ modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) { require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet"); validateMigrationIsPending(contractName, newMigrationId); _; emit Migrated(contractName, newMigrationId); migrated[contractName][newMigrationId] = true; } /** * @dev Returns true if the contract migration was applied. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. * @return true if the contract migration was applied, false otherwise. */ function isMigrated(string contractName, string migrationId) public view returns(bool) { return migrated[contractName][migrationId]; } /** * @dev Initializer that marks the contract as initialized. * It is important to run this if you had deployed a previous version of a Migratable contract. * For more information see https://github.com/zeppelinos/zos-lib/issues/158. */ function initialize() isInitializer("Migratable", "1.2.1") public { } /** * @dev Reverts if the requested migration was already executed. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ function validateMigrationIsPending(string contractName, string migrationId) private view { require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run"); } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is Migratable, ERC165Support, ERC721BasicToken, ERC721 { bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function initialize(string _name, string _symbol) public isInitializer("ERC721Token", "1.9.0") { name_ = _name; symbol_ = _symbol; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721Enumerable || _interfaceId == InterfaceId_ERC721Metadata; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { 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) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @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)); 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()); return allTokens[_index]; } /** * @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 _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @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 (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: openzeppelin-zos/contracts/ownership/Ownable.sol /** * @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 is Migratable { 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 * account. */ function initialize(address _sender) public isInitializer("Ownable", "1.9.0") { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == 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(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/estate/IEstateRegistry.sol contract IEstateRegistry { function mint(address to, string metadata) external returns (uint256); function ownerOf(uint256 _tokenId) public view returns (address _owner); // from ERC721 // Events event CreateEstate( address indexed _owner, uint256 indexed _estateId, string _data ); event AddLand( uint256 indexed _estateId, uint256 indexed _landId ); event RemoveLand( uint256 indexed _estateId, uint256 indexed _landId, address indexed _destinatary ); event Update( uint256 indexed _assetId, address indexed _holder, address indexed _operator, string _data ); event UpdateOperator( uint256 indexed _estateId, address indexed _operator ); event UpdateManager( address indexed _owner, address indexed _operator, address indexed _caller, bool _approved ); event SetLANDRegistry( address indexed _registry ); event SetEstateLandBalanceToken( address indexed _previousEstateLandBalance, address indexed _newEstateLandBalance ); } // File: contracts/minimeToken/IMinimeToken.sol interface IMiniMeToken { //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) external returns (bool); /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) external returns (bool); /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) external view returns (uint256 balance); event Transfer(address indexed _from, address indexed _to, uint256 _amount); } // File: contracts/estate/EstateStorage.sol contract LANDRegistry { function decodeTokenId(uint value) external pure returns (int, int); function updateLandData(int x, int y, string data) external; function setUpdateOperator(uint256 assetId, address operator) external; function setManyUpdateOperator(uint256[] landIds, address operator) external; function ping() public; function ownerOf(uint256 tokenId) public returns (address); function safeTransferFrom(address, address, uint256) public; function updateOperator(uint256 landId) public returns (address); } contract EstateStorage { bytes4 internal constant InterfaceId_GetMetadata = bytes4(keccak256("getMetadata(uint256)")); bytes4 internal constant InterfaceId_VerifyFingerprint = bytes4( keccak256("verifyFingerprint(uint256,bytes)") ); LANDRegistry public registry; // From Estate to list of owned LAND ids (LANDs) mapping(uint256 => uint256[]) public estateLandIds; // From LAND id (LAND) to its owner Estate id mapping(uint256 => uint256) public landIdEstate; // From Estate id to mapping of LAND id to index on the array above (estateLandIds) mapping(uint256 => mapping(uint256 => uint256)) public estateLandIndex; // Metadata of the Estate mapping(uint256 => string) internal estateData; // Operator of the Estate mapping (uint256 => address) public updateOperator; // From account to mapping of operator to bool whether is allowed to update content or not mapping(address => mapping(address => bool)) public updateManager; // Land balance minime token IMiniMeToken public estateLandBalance; // Registered balance accounts mapping(address => bool) public registeredBalance; } // File: contracts/estate/EstateRegistry.sol /** * @title ERC721 registry of every minted Estate and their owned LANDs * @dev Usings we are inheriting and depending on: * From ERC721Token: * - using SafeMath for uint256; * - using AddressUtils for address; */ // solium-disable-next-line max-len contract EstateRegistry is Migratable, IEstateRegistry, ERC721Token, ERC721Receiver, Ownable, EstateStorage { modifier canTransfer(uint256 estateId) { require(isApprovedOrOwner(msg.sender, estateId), "Only owner or operator can transfer"); _; } modifier onlyRegistry() { require(msg.sender == address(registry), "Only the registry can make this operation"); _; } modifier onlyUpdateAuthorized(uint256 estateId) { require(_isUpdateAuthorized(msg.sender, estateId), "Unauthorized user"); _; } modifier onlyLandUpdateAuthorized(uint256 estateId, uint256 landId) { require(_isLandUpdateAuthorized(msg.sender, estateId, landId), "unauthorized user"); _; } modifier canSetUpdateOperator(uint256 estateId) { address owner = ownerOf(estateId); require( isApprovedOrOwner(msg.sender, estateId) || updateManager[owner][msg.sender], "unauthorized user" ); _; } /** * @dev Mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function mint(address to, string metadata) external onlyRegistry returns (uint256) { return _mintEstate(to, metadata); } /** * @notice Transfer a LAND owned by an Estate to a new owner * @param estateId Current owner of the token * @param landId LAND to be transfered * @param destinatary New owner */ function transferLand( uint256 estateId, uint256 landId, address destinatary ) external canTransfer(estateId) { return _transferLand(estateId, landId, destinatary); } /** * @notice Transfer many tokens owned by an Estate to a new owner * @param estateId Current owner of the token * @param landIds LANDs to be transfered * @param destinatary New owner */ function transferManyLands( uint256 estateId, uint256[] landIds, address destinatary ) external canTransfer(estateId) { uint length = landIds.length; for (uint i = 0; i < length; i++) { _transferLand(estateId, landIds[i], destinatary); } } /** * @notice Get the Estate id for a given LAND id * @dev This information also lives on estateLandIds, * but it being a mapping you need to know the Estate id beforehand. * @param landId LAND to search * @return The corresponding Estate id */ function getLandEstateId(uint256 landId) external view returns (uint256) { return landIdEstate[landId]; } function setLANDRegistry(address _registry) external onlyOwner { require(_registry.isContract(), "The LAND registry address should be a contract"); require(_registry != 0, "The LAND registry address should be valid"); registry = LANDRegistry(_registry); emit SetLANDRegistry(registry); } function ping() external { registry.ping(); } /** * @notice Return the amount of tokens for a given Estate * @param estateId Estate id to search * @return Tokens length */ function getEstateSize(uint256 estateId) external view returns (uint256) { return estateLandIds[estateId].length; } /** * @notice Return the amount of LANDs inside the Estates for a given address * @param _owner of the estates * @return the amount of LANDs */ function getLANDsSize(address _owner) public view returns (uint256) { // Avoid balanceOf to not compute an unnecesary require uint256 landsSize; uint256 balance = ownedTokensCount[_owner]; for (uint256 i; i < balance; i++) { uint256 estateId = ownedTokens[_owner][i]; landsSize += estateLandIds[estateId].length; } return landsSize; } /** * @notice Update the metadata of an Estate * @dev Reverts if the Estate does not exist or the user is not authorized * @param estateId Estate id to update * @param metadata string metadata */ function updateMetadata( uint256 estateId, string metadata ) external onlyUpdateAuthorized(estateId) { _updateMetadata(estateId, metadata); emit Update( estateId, ownerOf(estateId), msg.sender, metadata ); } function getMetadata(uint256 estateId) external view returns (string) { return estateData[estateId]; } function isUpdateAuthorized(address operator, uint256 estateId) external view returns (bool) { return _isUpdateAuthorized(operator, estateId); } /** * @dev Set an updateManager for an account * @param _owner - address of the account to set the updateManager * @param _operator - address of the account to be set as the updateManager * @param _approved - bool whether the address will be approved or not */ function setUpdateManager(address _owner, address _operator, bool _approved) external { require(_operator != msg.sender, "The operator should be different from owner"); require( _owner == msg.sender || operatorApprovals[_owner][msg.sender], "Unauthorized user" ); updateManager[_owner][_operator] = _approved; emit UpdateManager( _owner, _operator, msg.sender, _approved ); } /** * @notice Set Estate updateOperator * @param estateId - Estate id * @param operator - address of the account to be set as the updateOperator */ function setUpdateOperator( uint256 estateId, address operator ) public canSetUpdateOperator(estateId) { updateOperator[estateId] = operator; emit UpdateOperator(estateId, operator); } /** * @notice Set Estates updateOperator * @param _estateIds - Estate ids * @param _operator - address of the account to be set as the updateOperator */ function setManyUpdateOperator( uint256[] _estateIds, address _operator ) public { for (uint i = 0; i < _estateIds.length; i++) { setUpdateOperator(_estateIds[i], _operator); } } /** * @notice Set LAND updateOperator * @param estateId - Estate id * @param landId - LAND to set the updateOperator * @param operator - address of the account to be set as the updateOperator */ function setLandUpdateOperator( uint256 estateId, uint256 landId, address operator ) public canSetUpdateOperator(estateId) { require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate"); registry.setUpdateOperator(landId, operator); } /** * @notice Set many LAND updateOperator * @param _estateId - Estate id * @param _landIds - LANDs to set the updateOperator * @param _operator - address of the account to be set as the updateOperator */ function setManyLandUpdateOperator( uint256 _estateId, uint256[] _landIds, address _operator ) public canSetUpdateOperator(_estateId) { for (uint i = 0; i < _landIds.length; i++) { require(landIdEstate[_landIds[i]] == _estateId, "The LAND is not part of the Estate"); } registry.setManyUpdateOperator(_landIds, _operator); } function initialize( string _name, string _symbol, address _registry ) public isInitializer("EstateRegistry", "0.0.2") { require(_registry != 0, "The registry should be a valid address"); ERC721Token.initialize(_name, _symbol); Ownable.initialize(msg.sender); registry = LANDRegistry(_registry); } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the 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(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public onlyRegistry returns (bytes4) { uint256 estateId = _bytesToUint(_data); _pushLandId(estateId, _tokenId); return ERC721_RECEIVED; } /** * @dev Creates a checksum of the contents of the Estate * @param estateId the estateId to be verified */ function getFingerprint(uint256 estateId) public view returns (bytes32 result) { result = keccak256(abi.encodePacked("estateId", estateId)); uint256 length = estateLandIds[estateId].length; for (uint i = 0; i < length; i++) { result ^= keccak256(abi.encodePacked(estateLandIds[estateId][i])); } return result; } /** * @dev Verifies a checksum of the contents of the Estate * @param estateId the estateid to be verified * @param fingerprint the user provided identification of the Estate contents */ function verifyFingerprint(uint256 estateId, bytes fingerprint) public view returns (bool) { return getFingerprint(estateId) == _bytesToBytes32(fingerprint); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev 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 estateIds uint256 array of IDs to be transferred */ function safeTransferManyFrom(address from, address to, uint256[] estateIds) public { safeTransferManyFrom( from, to, estateIds, "" ); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev 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 estateIds uint256 array of IDs to be transferred * @param data bytes data to send along with a safe transfer check */ function safeTransferManyFrom( address from, address to, uint256[] estateIds, bytes data ) public { for (uint i = 0; i < estateIds.length; i++) { safeTransferFrom( from, to, estateIds[i], data ); } } /** * @dev update LAND data owned by an Estate * @param estateId Estate * @param landId LAND to be updated * @param data string metadata */ function updateLandData(uint256 estateId, uint256 landId, string data) public { _updateLandData(estateId, landId, data); } /** * @dev update LANDs data owned by an Estate * @param estateId Estate id * @param landIds LANDs to be updated * @param data string metadata */ function updateManyLandData(uint256 estateId, uint256[] landIds, string data) public { uint length = landIds.length; for (uint i = 0; i < length; i++) { _updateLandData(estateId, landIds[i], data); } } function transferFrom(address _from, address _to, uint256 _tokenId) public { updateOperator[_tokenId] = address(0); _updateEstateLandBalance(_from, _to, estateLandIds[_tokenId].length); super.transferFrom(_from, _to, _tokenId); } // check the supported interfaces via ERC165 function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { // solium-disable-next-line operator-whitespace return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_GetMetadata || _interfaceId == InterfaceId_VerifyFingerprint; } /** * @dev Internal function to mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function _mintEstate(address to, string metadata) internal returns (uint256) { require(to != address(0), "You can not mint to an empty address"); uint256 estateId = _getNewEstateId(); _mint(to, estateId); _updateMetadata(estateId, metadata); emit CreateEstate(to, estateId, metadata); return estateId; } /** * @dev Internal function to update an Estate metadata * @dev Does not require the Estate to exist, for a public interface use `updateMetadata` * @param estateId Estate id to update * @param metadata string metadata */ function _updateMetadata(uint256 estateId, string metadata) internal { estateData[estateId] = metadata; } /** * @notice Return a new unique id * @dev It uses totalSupply to determine the next id * @return uint256 Representing the new Estate id */ function _getNewEstateId() internal view returns (uint256) { return totalSupply().add(1); } /** * @dev Appends a new LAND id to an Estate updating all related storage * @param estateId Estate where the LAND should go * @param landId Transfered LAND */ function _pushLandId(uint256 estateId, uint256 landId) internal { require(exists(estateId), "The Estate id should exist"); require(landIdEstate[landId] == 0, "The LAND is already owned by an Estate"); require(registry.ownerOf(landId) == address(this), "The EstateRegistry cannot manage the LAND"); estateLandIds[estateId].push(landId); landIdEstate[landId] = estateId; estateLandIndex[estateId][landId] = estateLandIds[estateId].length; address owner = ownerOf(estateId); _updateEstateLandBalance(address(registry), owner, 1); emit AddLand(estateId, landId); } /** * @dev Removes a LAND from an Estate and transfers it to a new owner * @param estateId Current owner of the LAND * @param landId LAND to be transfered * @param destinatary New owner */ function _transferLand( uint256 estateId, uint256 landId, address destinatary ) internal { require(destinatary != address(0), "You can not transfer LAND to an empty address"); uint256[] storage landIds = estateLandIds[estateId]; mapping(uint256 => uint256) landIndex = estateLandIndex[estateId]; /** * Using 1-based indexing to be able to make this check */ require(landIndex[landId] != 0, "The LAND is not part of the Estate"); uint lastIndexInArray = landIds.length.sub(1); /** * Get the landIndex of this token in the landIds list */ uint indexInArray = landIndex[landId].sub(1); /** * Get the landId at the end of the landIds list */ uint tempTokenId = landIds[lastIndexInArray]; /** * Store the last token in the position previously occupied by landId */ landIndex[tempTokenId] = indexInArray.add(1); landIds[indexInArray] = tempTokenId; /** * Delete the landIds[last element] */ delete landIds[lastIndexInArray]; landIds.length = lastIndexInArray; /** * Drop this landId from both the landIndex and landId list */ landIndex[landId] = 0; /** * Drop this landId Estate */ landIdEstate[landId] = 0; address owner = ownerOf(estateId); _updateEstateLandBalance(owner, address(registry), 1); registry.safeTransferFrom(this, destinatary, landId); emit RemoveLand(estateId, landId, destinatary); } function _isUpdateAuthorized(address operator, uint256 estateId) internal view returns (bool) { address owner = ownerOf(estateId); return isApprovedOrOwner(operator, estateId) || updateOperator[estateId] == operator || updateManager[owner][operator]; } function _isLandUpdateAuthorized( address operator, uint256 estateId, uint256 landId ) internal returns (bool) { return _isUpdateAuthorized(operator, estateId) || registry.updateOperator(landId) == operator; } function _bytesToUint(bytes b) internal pure returns (uint256) { return uint256(_bytesToBytes32(b)); } function _bytesToBytes32(bytes b) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < b.length; i++) { out |= bytes32(b[i] & 0xFF) >> i.mul(8); } return out; } function _updateLandData( uint256 estateId, uint256 landId, string data ) internal onlyLandUpdateAuthorized(estateId, landId) { require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate"); int x; int y; (x, y) = registry.decodeTokenId(landId); registry.updateLandData(x, y, data); } /** * @dev Set a new estate land balance minime token * @param _newEstateLandBalance address of the new estate land balance token */ function _setEstateLandBalanceToken(address _newEstateLandBalance) internal { require(_newEstateLandBalance != address(0), "New estateLandBalance should not be zero address"); emit SetEstateLandBalanceToken(estateLandBalance, _newEstateLandBalance); estateLandBalance = IMiniMeToken(_newEstateLandBalance); } /** * @dev Register an account balance * @notice Register land Balance */ function registerBalance() external { require(!registeredBalance[msg.sender], "Register Balance::The user is already registered"); // Get balance of the sender uint256 currentBalance = estateLandBalance.balanceOf(msg.sender); if (currentBalance > 0) { require( estateLandBalance.destroyTokens(msg.sender, currentBalance), "Register Balance::Could not destroy tokens" ); } // Set balance as registered registeredBalance[msg.sender] = true; // Get LAND balance uint256 newBalance = getLANDsSize(msg.sender); // Generate Tokens require( estateLandBalance.generateTokens(msg.sender, newBalance), "Register Balance::Could not generate tokens" ); } /** * @dev Unregister an account balance * @notice Unregister land Balance */ function unregisterBalance() external { require(registeredBalance[msg.sender], "Unregister Balance::The user not registered"); // Set balance as unregistered registeredBalance[msg.sender] = false; // Get balance uint256 currentBalance = estateLandBalance.balanceOf(msg.sender); // Destroy Tokens require( estateLandBalance.destroyTokens(msg.sender, currentBalance), "Unregister Balance::Could not destroy tokens" ); } /** * @dev Update account balances * @param _from account * @param _to account * @param _amount to update */ function _updateEstateLandBalance(address _from, address _to, uint256 _amount) internal { if (registeredBalance[_from]) { estateLandBalance.destroyTokens(_from, _amount); } if (registeredBalance[_to]) { estateLandBalance.generateTokens(_to, _amount); } } /** * @dev Set a estate land balance minime token hardcoded because of the * contraint of the proxy for using an owner * Mainnet: 0x8568f23f343694650370fe5e254b55bfb704a6c7 */ function setEstateLandBalanceToken() external { require(estateLandBalance == address(0), "estateLandBalance was set"); _setEstateLandBalanceToken(address(0x8568f23f343694650370fe5e254b55bfb704a6c7)); } }
* @dev Creates a checksum of the contents of the Estate @param estateId the estateId to be verified/
function getFingerprint(uint256 estateId) public view returns (bytes32 result) { result = keccak256(abi.encodePacked("estateId", estateId)); uint256 length = estateLandIds[estateId].length; for (uint i = 0; i < length; i++) { result ^= keccak256(abi.encodePacked(estateLandIds[estateId][i])); } return result; }
1,763,324
[ 1, 2729, 279, 6697, 434, 326, 2939, 434, 326, 512, 2019, 225, 4387, 340, 548, 326, 4387, 340, 548, 358, 506, 13808, 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 ]
[ 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, 2812, 7898, 12, 11890, 5034, 4387, 340, 548, 13, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 3890, 1578, 563, 13, 203, 225, 288, 203, 565, 563, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 395, 340, 548, 3113, 4387, 340, 548, 10019, 203, 203, 565, 2254, 5034, 769, 273, 4387, 340, 29398, 2673, 63, 395, 340, 548, 8009, 2469, 31, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 1377, 563, 10352, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 395, 340, 29398, 2673, 63, 395, 340, 548, 6362, 77, 5717, 1769, 203, 565, 289, 203, 565, 327, 563, 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 ]
./partial_match/3/0xa8A394A4a1cea6eD313D78e114F9560e71461353/sources/VVV5Sale.sol
require(msg.sender!=owner);require(tokensRaised < fundingGoal);require(now < icoEnd && now > icoStart);if(tokensRaised + tokensToBuy > fundingGoal) { uint exceedingTokens = tokensRaised + tokensToBuy - fundingGoal; uint exceedingEther; exceedingEther = (exceedingTokens * 1 ether) / tokenRate; msg.sender.transfer(exceedingEther); tokensToBuy -= exceedingTokens; etherUsed -= exceedingEther; } transfer tokensbalances[owner] = safeSub(balances[owner], tokensToBuy);balances[msg.sender] = safeAdd(balances[msg.sender], tokensToBuy);emit Transfer(owner, msg.sender, tokensToBuy);
function buy() public payable { emit BuyTokens( msg.sender , msg.value); uint tokensToBuy; uint etherUsed = msg.value; tokensToBuy = (etherUsed/ 1 ether) * tokenRate; tokensToBuy = tokensToBuy * 10 ** decimals; owner.transfer(etherUsed); token.releaseTokens(msg.sender, tokensToBuy, owner); tokensRaised += tokensToBuy; etherRaised += etherUsed; }
5,211,318
[ 1, 6528, 12, 3576, 18, 15330, 5, 33, 8443, 1769, 6528, 12, 7860, 12649, 5918, 411, 22058, 27716, 1769, 6528, 12, 3338, 411, 277, 2894, 1638, 597, 2037, 405, 277, 2894, 1685, 1769, 430, 12, 7860, 12649, 5918, 397, 2430, 774, 38, 9835, 405, 22058, 27716, 13, 288, 282, 2254, 9943, 310, 5157, 273, 2430, 12649, 5918, 397, 2430, 774, 38, 9835, 300, 22058, 27716, 31, 282, 2254, 9943, 310, 41, 1136, 31, 282, 9943, 310, 41, 1136, 273, 261, 338, 5288, 310, 5157, 225, 404, 225, 2437, 13, 342, 1147, 4727, 31, 282, 1234, 18, 15330, 18, 13866, 12, 338, 5288, 310, 41, 1136, 1769, 282, 2430, 774, 38, 9835, 3947, 9943, 310, 5157, 31, 282, 225, 2437, 6668, 3947, 9943, 310, 41, 1136, 31, 289, 7412, 2430, 70, 26488, 63, 8443, 65, 273, 4183, 1676, 12, 70, 26488, 63, 8443, 6487, 2430, 774, 38, 9835, 1769, 70, 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, 282, 445, 30143, 1435, 1071, 8843, 429, 288, 203, 203, 1377, 3626, 605, 9835, 5157, 12, 1234, 18, 15330, 269, 1234, 18, 1132, 1769, 203, 202, 21281, 1377, 2254, 2430, 774, 38, 9835, 31, 203, 1377, 2254, 225, 2437, 6668, 273, 1234, 18, 1132, 31, 203, 1377, 2430, 774, 38, 9835, 273, 261, 2437, 6668, 19, 404, 225, 2437, 13, 380, 1147, 4727, 31, 203, 203, 203, 203, 203, 1377, 2430, 774, 38, 9835, 273, 2430, 774, 38, 9835, 380, 1728, 2826, 15105, 31, 7010, 203, 4202, 203, 1377, 3410, 18, 13866, 12, 2437, 6668, 1769, 203, 4202, 203, 4202, 203, 1377, 1147, 18, 9340, 5157, 12, 3576, 18, 15330, 16, 2430, 774, 38, 9835, 16, 3410, 1769, 203, 4202, 203, 4202, 203, 203, 1377, 2430, 12649, 5918, 1011, 2430, 774, 38, 9835, 31, 203, 1377, 225, 2437, 12649, 5918, 1011, 225, 2437, 6668, 31, 203, 282, 289, 203, 27699, 27699, 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/80001/0xf8B113378894Ae22F85ECC41E11d0DA9748673ba/sources/contracts/c2.sol
Normal requirements require(msg.value >= price * _mintAmount, 'Insufficient funds!'); Allow free mint Require payment for non-free mints
function PublicMint(uint256 _mintAmount) public payable { require(publicSale, 'The PublicSale is paused!'); require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid mint amount!'); require(totalSupply() + _mintAmount <= supplyLimit, 'Max supply exceeded!'); require(publicMintCount[msg.sender] + _mintAmount <= maxLimitPerWallet, 'Max mint per wallet exceeded!'); if (publicMintCount[msg.sender] < 5) { require( _mintAmount + publicMintCount[msg.sender] <= 5, "free limit exceeded" ); require(msg.value == 0, "Free mints cannot have a cost"); require(msg.value >= price * _mintAmount, "Insufficient payment"); } publicMinted += _mintAmount; }
5,557,603
[ 1, 5506, 8433, 2583, 12, 3576, 18, 1132, 1545, 6205, 225, 389, 81, 474, 6275, 16, 296, 5048, 11339, 284, 19156, 5124, 1769, 7852, 4843, 312, 474, 12981, 5184, 364, 1661, 17, 9156, 312, 28142, 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, 225, 445, 7224, 49, 474, 12, 11890, 5034, 389, 81, 474, 6275, 13, 1071, 8843, 429, 288, 203, 377, 203, 565, 2583, 12, 482, 30746, 16, 296, 1986, 7224, 30746, 353, 17781, 5124, 1769, 203, 565, 2583, 24899, 81, 474, 6275, 405, 374, 597, 389, 81, 474, 6275, 1648, 943, 49, 474, 6275, 2173, 4188, 16, 296, 1941, 312, 474, 3844, 5124, 1769, 203, 565, 2583, 12, 4963, 3088, 1283, 1435, 397, 389, 81, 474, 6275, 1648, 14467, 3039, 16, 296, 2747, 14467, 12428, 5124, 1769, 203, 565, 2583, 12, 482, 49, 474, 1380, 63, 3576, 18, 15330, 65, 397, 389, 81, 474, 6275, 1648, 943, 3039, 2173, 16936, 16, 296, 2747, 312, 474, 1534, 9230, 12428, 5124, 1769, 203, 1377, 203, 377, 309, 261, 482, 49, 474, 1380, 63, 3576, 18, 15330, 65, 411, 1381, 13, 288, 203, 5411, 2583, 12, 203, 7734, 389, 81, 474, 6275, 397, 1071, 49, 474, 1380, 63, 3576, 18, 15330, 65, 1648, 1381, 16, 203, 7734, 315, 9156, 1800, 12428, 6, 203, 5411, 11272, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 374, 16, 315, 9194, 312, 28142, 2780, 1240, 279, 6991, 8863, 203, 5411, 2583, 12, 3576, 18, 1132, 1545, 6205, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 5184, 8863, 203, 3639, 289, 203, 203, 203, 565, 1071, 49, 474, 329, 1011, 389, 81, 474, 6275, 31, 27699, 225, 289, 21281, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.2.0 https://hardhat.org // File @openzeppelin/contracts/introspection/[email protected] 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); } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @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; } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity >=0.6.2 <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/[email protected] pragma solidity >=0.6.2 <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/token/ERC721/[email protected] pragma solidity >=0.6.2 <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/[email protected] 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); } // File @openzeppelin/contracts/math/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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); } } } } // File @openzeppelin/contracts/utils/[email protected] 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)); } } // File @openzeppelin/contracts/utils/[email protected] 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)))); } } // File @openzeppelin/contracts/utils/[email protected] 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); } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @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 { } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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); } // File @openzeppelin/contracts/access/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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); } } // File contracts/Ancient.sol pragma solidity ^0.7.3; contract Ancient is Ownable, ERC165, ERC721 { // Libraries using Counters for Counters.Counter; using Strings for uint256; using SafeMath for uint256; // Private fields Counters.Counter private _tokenIds; string private ipfsUri = "https://ipfs.io/ipfs/"; // Public constants uint256 public constant MAX_SUPPLY = 8888; // This hash is the SHA256 output of the concatenation of the IPFS image hash data for all 8888 Bonsai. string public provenance = ""; // This contract will then return a decentralised IPFS URI when tokenURI() is called. string public folder; // This value will be set by an admin to an IPFS url that will list the hash and CID of all Bonsai. string public provenanceURI = ""; // After sale is complete, and provenance records updated, the contract will be locked by an admin and then // the state of the contract will be immutable for the rest of time. bool public locked = false; address public WATER_ADDRESS = 0x65040331cD089670fFB25eE15845a7c876B8A728; modifier notLocked() { require(!locked, "Contract has been locked"); _; } constructor() ERC721("Chosen Ancient Bonsai", "ABNSI") { _setBaseURI("https://us-central1-zenft-65a6d.cloudfunctions.net/app/ancient/"); ownerMint(6); folder = ""; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( tokenId > 0 && tokenId <= totalSupply(), "URI query for nonexistent token" ); // Construct IPFS URI or fallback if (bytes(folder).length > 0) { return string( abi.encodePacked(ipfsUri, folder, "/", tokenId.toString()) ); } // Fallback to centralised URI return string(abi.encodePacked(baseURI(), tokenId.toString())); } // Admin methods function ownerMint(uint256 quantity) public onlyOwner notLocked { for (uint256 i = 0; i < quantity; i++) { _mintBonsai(msg.sender); } } function setBaseURI(string memory newBaseURI) external onlyOwner notLocked { _setBaseURI(newBaseURI); } function setIpfsURI(string memory _ipfsUri) external onlyOwner notLocked { ipfsUri = _ipfsUri; } function setFolder(string memory _folder) external onlyOwner notLocked { folder = _folder; } function setProvenanceURI(string memory _provenanceURI) external onlyOwner notLocked { provenanceURI = _provenanceURI; } function setProvenance(string memory _provenance) external onlyOwner notLocked { provenance = _provenance; } function lock() external onlyOwner { locked = true; } function withdraw() external onlyOwner { (bool success, ) = payable(owner()).call{value: address(this).balance}(""); require(success); } // Private Methods function _mintBonsai(address owner) private { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(owner, newItemId); } }
Libraries Private fields Public constants This hash is the SHA256 output of the concatenation of the IPFS image hash data for all 8888 Bonsai. This contract will then return a decentralised IPFS URI when tokenURI() is called. This value will be set by an admin to an IPFS url that will list the hash and CID of all Bonsai. After sale is complete, and provenance records updated, the contract will be locked by an admin and then the state of the contract will be immutable for the rest of time.
contract Ancient is Ownable, ERC165, ERC721 { using Counters for Counters.Counter; using Strings for uint256; using SafeMath for uint256; Counters.Counter private _tokenIds; uint256 public constant MAX_SUPPLY = 8888; string public provenance = ""; string public folder; string public provenanceURI = ""; bool public locked = false; address public WATER_ADDRESS = 0x65040331cD089670fFB25eE15845a7c876B8A728; pragma solidity ^0.7.3; modifier notLocked() { require(!locked, "Contract has been locked"); _; } constructor() ERC721("Chosen Ancient Bonsai", "ABNSI") { ownerMint(6); folder = ""; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( tokenId > 0 && tokenId <= totalSupply(), "URI query for nonexistent token" ); if (bytes(folder).length > 0) { return string( abi.encodePacked(ipfsUri, folder, "/", tokenId.toString()) ); } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( tokenId > 0 && tokenId <= totalSupply(), "URI query for nonexistent token" ); if (bytes(folder).length > 0) { return string( abi.encodePacked(ipfsUri, folder, "/", tokenId.toString()) ); } } return string(abi.encodePacked(baseURI(), tokenId.toString())); function ownerMint(uint256 quantity) public onlyOwner notLocked { for (uint256 i = 0; i < quantity; i++) { _mintBonsai(msg.sender); } } function ownerMint(uint256 quantity) public onlyOwner notLocked { for (uint256 i = 0; i < quantity; i++) { _mintBonsai(msg.sender); } } function setBaseURI(string memory newBaseURI) external onlyOwner notLocked { _setBaseURI(newBaseURI); } function setIpfsURI(string memory _ipfsUri) external onlyOwner notLocked { ipfsUri = _ipfsUri; } function setFolder(string memory _folder) external onlyOwner notLocked { folder = _folder; } function setProvenanceURI(string memory _provenanceURI) external onlyOwner notLocked { provenanceURI = _provenanceURI; } function setProvenance(string memory _provenance) external onlyOwner notLocked { provenance = _provenance; } function lock() external onlyOwner { locked = true; } function withdraw() external onlyOwner { (bool success, ) = require(success); } payable(owner()).call{value: address(this).balance}(""); function _mintBonsai(address owner) private { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(owner, newItemId); } }
14,626,326
[ 1, 31909, 8726, 1466, 7224, 6810, 1220, 1651, 353, 326, 9777, 5034, 876, 434, 326, 26833, 434, 326, 2971, 4931, 1316, 1651, 501, 364, 777, 1725, 5482, 28, 605, 7008, 10658, 18, 1220, 6835, 903, 1508, 327, 279, 2109, 12839, 5918, 2971, 4931, 3699, 1347, 1147, 3098, 1435, 353, 2566, 18, 1220, 460, 903, 506, 444, 635, 392, 3981, 358, 392, 2971, 4931, 880, 716, 903, 666, 326, 1651, 471, 385, 734, 434, 777, 605, 7008, 10658, 18, 7360, 272, 5349, 353, 3912, 16, 471, 24185, 3853, 3526, 16, 326, 6835, 903, 506, 8586, 635, 392, 3981, 471, 1508, 326, 919, 434, 326, 6835, 903, 506, 11732, 364, 326, 3127, 434, 813, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1922, 71, 1979, 353, 14223, 6914, 16, 4232, 39, 28275, 16, 4232, 39, 27, 5340, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 13272, 23893, 273, 1725, 5482, 28, 31, 203, 203, 565, 533, 1071, 24185, 273, 1408, 31, 203, 203, 565, 533, 1071, 3009, 31, 203, 203, 565, 533, 1071, 24185, 3098, 273, 1408, 31, 203, 203, 565, 1426, 1071, 8586, 273, 629, 31, 203, 203, 565, 1758, 1071, 678, 13641, 67, 15140, 273, 374, 92, 9222, 3028, 15265, 21, 71, 40, 20, 6675, 26, 7301, 74, 22201, 2947, 73, 41, 3600, 5193, 25, 69, 27, 71, 28, 6669, 38, 28, 37, 27, 6030, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 23, 31, 203, 565, 9606, 486, 8966, 1435, 288, 203, 3639, 2583, 12, 5, 15091, 16, 315, 8924, 711, 2118, 8586, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 782, 8918, 1922, 71, 1979, 605, 7008, 10658, 3113, 315, 2090, 50, 2320, 7923, 288, 203, 3639, 3410, 49, 474, 12, 26, 1769, 203, 3639, 3009, 273, 1408, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity >=0.4.22 <0.9.0; import "hardhat/console.sol"; contract OwnedToken { // TokenCreator 是如下定义的合约类型. // 不创建新合约的话,也可以引用它。 TokenCreator creator; address owner; bytes32 name; // 这是注册 creator 和设置名称的构造函数。 constructor(bytes32 _name) { // 状态变量通过其名称访问,而不是通过例如 this.owner 的方式访问。 // 这也适用于函数,特别是在构造函数中,你只能像这样(“内部地”)调用它们, // 因为合约本身还不存在。 owner = msg.sender; console.log("owner:", owner); console.log("address:", address(this)); // 从 `address` 到 `TokenCreator` ,是做显式的类型转换 // 并且假定调用合约的类型是 TokenCreator,没有真正的方法来检查这一点。 creator = TokenCreator(msg.sender); name = _name; } function changeName(bytes32 newName) public { // 只有 creator (即创建当前合约的合约)能够更改名称 —— 因为合约是隐式转换为地址的, // 所以这里的比较是可行的。 if (msg.sender == address(creator)) name = newName; } function transfer(address newOwner) public view { // 只有当前所有者才能发送 token。 if (msg.sender != newOwner) return; // 我们也想询问 creator 是否可以发送。 // 请注意,这里调用了一个下面定义的合约中的函数。 // 如果调用失败(比如,由于 gas 不足),会立即停止执行。 return; } } contract TokenCreator { function createToken(bytes32 name) public returns (OwnedToken tokenAddress) { // 创建一个新的 Token 合约并且返回它的地址。 // 从 JavaScript 方面来说,返回类型是简单的 `address` 类型,因为 // 这是在 ABI 中可用的最接近的类型。 return new OwnedToken(name); } function changeName(OwnedToken tokenAddress, bytes32 name) public { // 同样,`tokenAddress` 的外部类型也是 `address` 。 tokenAddress.changeName(name); } }
状态变量通过其名称访问,而不是通过例如 this.owner 的方式访问。 这也适用于函数,特别是在构造函数中,你只能像这样(“内部地”)调用它们, 因为合约本身还不存在。 从 `address` 到 `TokenCreator` ,是做显式的类型转换 并且假定调用合约的类型是 TokenCreator,没有真正的方法来检查这一点。
constructor(bytes32 _name) { owner = msg.sender; console.log("owner:", owner); console.log("address:", address(this)); creator = TokenCreator(msg.sender); name = _name; }
12,827,826
[ 1, 168, 237, 119, 167, 227, 228, 166, 242, 251, 170, 234, 242, 170, 227, 253, 169, 128, 234, 166, 232, 119, 166, 243, 240, 168, 105, 113, 169, 111, 128, 170, 250, 111, 176, 125, 239, 169, 227, 239, 165, 121, 240, 167, 251, 112, 170, 227, 253, 169, 128, 234, 165, 127, 238, 166, 104, 229, 333, 18, 8443, 225, 168, 253, 231, 167, 249, 122, 166, 125, 242, 169, 111, 128, 170, 250, 111, 164, 227, 229, 225, 169, 128, 252, 165, 122, 258, 170, 227, 229, 168, 247, 106, 165, 123, 241, 166, 234, 126, 167, 248, 113, 176, 125, 239, 168, 236, 122, 166, 235, 109, 167, 251, 112, 166, 255, 106, 167, 257, 231, 170, 227, 259, 166, 234, 126, 167, 248, 113, 165, 121, 260, 176, 125, 239, 165, 126, 259, 166, 242, 108, 169, 230, 126, 166, 230, 242, 169, 128, 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, 3885, 12, 3890, 1578, 389, 529, 13, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 2983, 18, 1330, 2932, 8443, 2773, 16, 3410, 1769, 203, 3639, 2983, 18, 1330, 2932, 2867, 2773, 16, 1758, 12, 2211, 10019, 203, 203, 3639, 11784, 273, 3155, 10636, 12, 3576, 18, 15330, 1769, 203, 3639, 508, 273, 389, 529, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./packages/Bundle_ERC20.sol"; /** * @title My ERC20 Token */ contract MyERC20Token is Bundle { receive() external payable {} fallback() external payable {} event Stake(address staker, uint256 value, uint256 time); event Claim(address staker, uint256 value); event Withdraw(address operator, address receiver, uint256 value); mapping(address => uint256) private _timestamp; mapping(address => uint256) private _staked; constructor() { _mint(msg.sender, 1000000000 * 10 ** decimals()); } /** * @dev Token staking */ function stake(uint256 _value) public gate { require(balanceOf(msg.sender) > 0, "MyERC20Token: zero token balance"); _timestamp[msg.sender] = block.timestamp; _staked[msg.sender] = _value; _transfer(msg.sender, address(this), _value); emit Stake(msg.sender, _value, 30 days); } /** * @dev Token claim */ function claim() public gate { require(_staked[msg.sender] > 0, "MyERC20Token: no tokens staked"); require(_timestamp[msg.sender] + 30 days <= block.timestamp, "MyERC20Token: lock time has not completed"); uint256 staked = _staked[msg.sender]; _transfer(address(this), msg.sender, staked); _timestamp[msg.sender] = 0; _staked[msg.sender] = 0; // Add claim reward logic below and adjust event accordingly emit Claim(msg.sender, staked); } /** * @dev Withdraw ether from contract */ function withdraw(address _to) public ownership { uint256 balance = address(this).balance; (bool success, ) = payable(_to).call{value: address(this).balance}(""); require(success, "MyERC20Token: ether transfer failed"); emit Withdraw(msg.sender, _to, balance); } }
* @title My ERC20 Token/
contract MyERC20Token is Bundle { event Stake(address staker, uint256 value, uint256 time); event Claim(address staker, uint256 value); event Withdraw(address operator, address receiver, uint256 value); mapping(address => uint256) private _timestamp; mapping(address => uint256) private _staked; receive() external payable {} fallback() external payable {} constructor() { _mint(msg.sender, 1000000000 * 10 ** decimals()); } function stake(uint256 _value) public gate { require(balanceOf(msg.sender) > 0, "MyERC20Token: zero token balance"); _timestamp[msg.sender] = block.timestamp; _staked[msg.sender] = _value; _transfer(msg.sender, address(this), _value); emit Stake(msg.sender, _value, 30 days); } function claim() public gate { require(_staked[msg.sender] > 0, "MyERC20Token: no tokens staked"); require(_timestamp[msg.sender] + 30 days <= block.timestamp, "MyERC20Token: lock time has not completed"); uint256 staked = _staked[msg.sender]; _transfer(address(this), msg.sender, staked); _timestamp[msg.sender] = 0; _staked[msg.sender] = 0; emit Claim(msg.sender, staked); } function withdraw(address _to) public ownership { uint256 balance = address(this).balance; require(success, "MyERC20Token: ether transfer failed"); emit Withdraw(msg.sender, _to, balance); } (bool success, ) = payable(_to).call{value: address(this).balance}(""); }
12,795,540
[ 1, 12062, 4232, 39, 3462, 3155, 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, 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, 16351, 8005, 654, 39, 3462, 1345, 353, 8539, 288, 203, 203, 565, 871, 934, 911, 12, 2867, 384, 6388, 16, 2254, 5034, 460, 16, 2254, 5034, 813, 1769, 203, 565, 871, 18381, 12, 2867, 384, 6388, 16, 2254, 5034, 460, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 3726, 16, 1758, 5971, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 5508, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 334, 9477, 31, 203, 203, 203, 565, 6798, 1435, 3903, 8843, 429, 2618, 203, 565, 5922, 1435, 3903, 8843, 429, 2618, 203, 565, 3885, 1435, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 15088, 3784, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 203, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 1132, 13, 1071, 12611, 288, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 405, 374, 16, 315, 12062, 654, 39, 3462, 1345, 30, 3634, 1147, 11013, 8863, 203, 3639, 389, 5508, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 3639, 389, 334, 9477, 63, 3576, 18, 15330, 65, 273, 389, 1132, 31, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 1132, 1769, 203, 3639, 3626, 934, 911, 12, 3576, 18, 15330, 16, 389, 1132, 16, 5196, 4681, 1769, 203, 565, 289, 203, 203, 565, 445, 7516, 1435, 1071, 12611, 288, 203, 3639, 2583, 24899, 334, 9477, 63, 3576, 18, 15330, 65, 405, 374, 16, 2 ]
./full_match/5/0xD503A1562aF40d8514b1150626DEeF6673128765/sources/contracts/libs/Inflate.sol
Length of stored block Discard leftover bits from current byte (assumes s.bitcnt < 8) Get length and check against its one's complement Not enough input Didn't match complement! Copy len bytes from in to out Not enough input Not enough output space Note: Solidity reverts on underflow, so we decrement here
function _stored(State memory s) private pure returns (ErrorCode) { unchecked { uint256 len; s.bitbuf = 0; s.bitcnt = 0; if (s.incnt + 4 > s.input.length) { return ErrorCode.ERR_NOT_TERMINATED; } len = uint256(uint8(s.input[s.incnt++])); len |= uint256(uint8(s.input[s.incnt++])) << 8; if (uint8(s.input[s.incnt++]) != (~len & 0xFF) || uint8(s.input[s.incnt++]) != ((~len >> 8) & 0xFF)) { return ErrorCode.ERR_STORED_LENGTH_NO_MATCH; } if (s.incnt + len > s.input.length) { return ErrorCode.ERR_NOT_TERMINATED; } if (s.outcnt + len > s.output.length) { return ErrorCode.ERR_OUTPUT_EXHAUSTED; } while (len != 0) { len -= 1; s.output[s.outcnt++] = s.input[s.incnt++]; } } }
1,888,042
[ 1, 1782, 434, 4041, 1203, 21643, 29709, 4125, 628, 783, 1160, 261, 428, 6411, 272, 18, 3682, 13085, 411, 1725, 13, 968, 769, 471, 866, 5314, 2097, 1245, 1807, 17161, 2288, 7304, 810, 21148, 82, 1404, 845, 17161, 5, 5631, 562, 1731, 628, 316, 358, 596, 2288, 7304, 810, 2288, 7304, 876, 3476, 3609, 30, 348, 7953, 560, 15226, 87, 603, 3613, 2426, 16, 1427, 732, 15267, 2674, 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, 565, 445, 389, 22601, 12, 1119, 3778, 272, 13, 3238, 16618, 1135, 261, 12012, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 5034, 562, 31, 203, 203, 5411, 272, 18, 3682, 4385, 273, 374, 31, 203, 5411, 272, 18, 3682, 13085, 273, 374, 31, 203, 203, 5411, 309, 261, 87, 18, 9523, 496, 397, 1059, 405, 272, 18, 2630, 18, 2469, 13, 288, 203, 7734, 327, 13218, 18, 9712, 67, 4400, 67, 29516, 6344, 31, 203, 5411, 289, 203, 5411, 562, 273, 2254, 5034, 12, 11890, 28, 12, 87, 18, 2630, 63, 87, 18, 9523, 496, 9904, 5717, 1769, 203, 5411, 562, 5626, 2254, 5034, 12, 11890, 28, 12, 87, 18, 2630, 63, 87, 18, 9523, 496, 9904, 22643, 2296, 1725, 31, 203, 203, 5411, 309, 261, 11890, 28, 12, 87, 18, 2630, 63, 87, 18, 9523, 496, 9904, 5717, 480, 261, 98, 1897, 473, 374, 6356, 13, 747, 2254, 28, 12, 87, 18, 2630, 63, 87, 18, 9523, 496, 9904, 5717, 480, 14015, 98, 1897, 1671, 1725, 13, 473, 374, 6356, 3719, 288, 203, 7734, 327, 13218, 18, 9712, 67, 31487, 5879, 67, 7096, 67, 3417, 67, 11793, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 87, 18, 9523, 496, 397, 562, 405, 272, 18, 2630, 18, 2469, 13, 288, 203, 7734, 327, 13218, 18, 9712, 67, 4400, 67, 29516, 6344, 31, 203, 5411, 289, 203, 5411, 309, 261, 87, 18, 659, 13085, 397, 562, 405, 272, 18, 2844, 18, 2469, 13, 288, 203, 7734, 327, 13218, 18, 9712, 67, 15527, 2 ]
/** * * Forked from SafeMoon * DeFi rules. :::::::: ::::::::::: ::: ::::::::: ::::::::::: :::::::: ::: ::: :::::::::: :::: ::: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+: +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +#++:++#++ +#+ +#++:++#++: +#++:++#: +#+ +#+ +:+ +#++:++ +#++:++# +#+ +:+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+#+# ######## ### ### ### ### ### ### ######## ### ### ########## ### #### /** * * 90% of fees in the first day (45% tax fee, 45% liquidity fee) * 80% of fees in the second day (40% tax fee, 40% liquidity fee) * 70% of fees in the third day (35% tax fee, 35% liquidity fee) * 60% of fees in the fourth day (30% tax fee, 30% liquidity fee) * 50% of fees in the fifth day (25% tax fee, 25% liquidity fee) * 40% of fees in the sixth day (20% tax fee, 20% liquidity fee) * 30% of fees in the seventh day 15% tax fee, 15% liquidity fee) * 20% of fees in the eighth day (10% tax fee ,10% liquidity fee) * 10% of fees from the ninth onwards (5% tax fee, 5% liquidity fee) * */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { 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 SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract StarToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => uint256) private _starTime; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "StarToken"; string private _symbol = "START"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } 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 totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } // how much time did you spend looking at the stars? //gives the multiplier for the fees function lookingTime(address account) public view returns (uint256) { uint256 starTime = _starTime[account]; if(starTime == 0) return 9; //not yet a holder uint256 numDays = ((block.timestamp).sub(starTime)).div(1 days); uint256 maxDays = 9; if(numDays>=maxDays) return 1; else if(numDays<1) return maxDays; else return maxDays.sub(numDays); } //gives tax and liquidity fees in relation to the holding days function calculateStarFees(address account) public view returns (uint256, uint256) { if(_isExcludedFromFee[account]==true) return (_taxFee,_liquidityFee); else { uint256 fee = lookingTime(account); return (fee*_taxFee,fee*_liquidityFee); } } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee <= 5, "Cannot put too high fees"); _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 5, "Cannot put too high fees"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function adaptAllFee(uint256 mul) private { _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = _taxFee*mul; _liquidityFee = _liquidityFee*mul; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } else { uint256 multi = lookingTime(from); adaptAllFee(multi); //gets the multiplier of the sender address } if(_starTime[from]==0) _starTime[from] = block.timestamp; if(_starTime[to]==0) _starTime[to] = block.timestamp; //transfer amount, it will take tax and liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } //if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
how much time did you spend looking at the stars?gives the multiplier for the fees
function lookingTime(address account) public view returns (uint256) { uint256 starTime = _starTime[account]; if(starTime == 0) uint256 numDays = ((block.timestamp).sub(starTime)).div(1 days); uint256 maxDays = 9; if(numDays>=maxDays) return 1; else if(numDays<1) return maxDays; else return maxDays.sub(numDays); }
1,569,786
[ 1, 13606, 9816, 813, 5061, 1846, 17571, 7849, 622, 326, 24084, 35, 75, 3606, 326, 15027, 364, 326, 1656, 281, 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, 7849, 950, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 10443, 950, 273, 389, 10983, 950, 63, 4631, 15533, 203, 3639, 309, 12, 10983, 950, 422, 374, 13, 7010, 540, 203, 3639, 2254, 5034, 818, 9384, 273, 14015, 2629, 18, 5508, 2934, 1717, 12, 10983, 950, 13, 2934, 2892, 12, 21, 4681, 1769, 203, 3639, 2254, 5034, 943, 9384, 273, 2468, 31, 203, 540, 203, 3639, 309, 12, 2107, 9384, 34, 33, 1896, 9384, 13, 7010, 5411, 327, 404, 31, 203, 3639, 469, 309, 12, 2107, 9384, 32, 21, 13, 7010, 5411, 327, 943, 9384, 31, 203, 3639, 469, 327, 7010, 5411, 943, 9384, 18, 1717, 12, 2107, 9384, 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 ]
./partial_match/1/0x291C80D4Aa0B6ED9E6b59c82121b359999efd4b7/sources/AsyncArtwork_v2.sol
the address of the creator the amount of layers they're expected to mint
struct WhitelistReservation { address creator; uint256 layerCount; }
4,347,598
[ 1, 5787, 1758, 434, 326, 11784, 326, 3844, 434, 6623, 2898, 4565, 2665, 358, 312, 474, 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, 1958, 3497, 7523, 18074, 288, 203, 3639, 1758, 11784, 31, 203, 3639, 2254, 5034, 3018, 1380, 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, -100, -100, -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.12; /* /** * @title A title that should describe the library * @author CXIP-Labs * @notice Explain to an end user what this does * @dev Explain to a developer any extra details */ library Library { } /** * @title A title that should describe the interface * @author CXIP-Labs * @notice Explain to an end user what this does * @dev Explain to a developer any extra details */ interface Interface { } /** * @title A title that should describe the contract * @author CXIP-Labs * @notice Explain to an end user what this does * @dev Explain to a developer any extra details */ contract Contract { /** * @notice Explain to an end user what this does * @dev Explain to a developer any extra details * @param param1 Documents a parameter just like in Doxygen(must be followed by parameter name) * @param param2 use one @param row for each parameter */ event Event(address indexed param1, address indexed param2); /** * @dev Explain to a developer any extra details */ uint256 private stateVariable; /** * @notice Explain to an end user what this does * @dev Explain to a developer any extra details * @return Documents the return variables of a contract’s function */ uint256 public publicStateVariable; /** * @notice Explain to an end user what this does * @dev Explain to a developer any extra details * @param id Documents a parameter just like in Doxygen(must be followed by parameter name) * @param wallet use one @param row for each parameter * @return Documents the return variables of a contract’s function */ function Function(uint256 id, address wallet) public pure returns (uint256, address) { return (id, wallet); } }
* @title A title that should describe the contract @author CXIP-Labs @notice Explain to an end user what this does @dev Explain to a developer any extra details/
contract Contract { event Event(address indexed param1, address indexed param2); uint256 private stateVariable; uint256 public publicStateVariable; function Function(uint256 id, address wallet) public pure returns (uint256, address) { return (id, wallet); } }
13,098,948
[ 1, 37, 2077, 716, 1410, 6401, 326, 6835, 225, 385, 60, 2579, 17, 48, 5113, 225, 1312, 7446, 358, 392, 679, 729, 4121, 333, 1552, 225, 1312, 7446, 358, 279, 8751, 1281, 2870, 3189, 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, 16351, 13456, 288, 203, 565, 871, 2587, 12, 2867, 8808, 579, 21, 16, 1758, 8808, 579, 22, 1769, 203, 203, 565, 2254, 5034, 3238, 919, 3092, 31, 203, 203, 565, 2254, 5034, 1071, 1071, 1119, 3092, 31, 203, 203, 565, 445, 4284, 12, 11890, 5034, 612, 16, 1758, 9230, 13, 1071, 16618, 1135, 261, 11890, 5034, 16, 1758, 13, 288, 203, 3639, 327, 261, 350, 16, 9230, 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 ]
./full_match/4/0xC748428b231793efc2e968441dCb9D56960768dd/sources/Generate.sol
How much more $NOM the character drops on a critical day
uint16 criticalMult;
747,674
[ 1, 44, 543, 9816, 1898, 271, 50, 1872, 326, 3351, 29535, 603, 279, 11239, 2548, 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, 3639, 2254, 2313, 11239, 5049, 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 ]
./partial_match/1/0x25C7C475934f40908523a36d5d7ea810D890b50F/sources/contracts/universal/MultiSigWallet.sol
* @notice The address of the governor contract. Can be updated via upgrade./* @notice A mapping of transactions submitted./* @notice A mapping of confirmations./* @notice A mapping that indicates whether someone is an owner or not./* @notice A list of owners./* @notice The number of confirmations required to execute a transaction./* @notice The number of transactions submitted./* @notice Only allow the specified governor contract to call the functions. This ensures that function is only executed through a governor process./
modifier onlyGovernor() { require( msg.sender == GOVERNOR, "MultiSigWallet: only allow specified governor contract to call the functions" ); _; }
16,186,984
[ 1, 1986, 1758, 434, 326, 314, 1643, 29561, 6835, 18, 4480, 506, 3526, 3970, 8400, 18, 19, 225, 432, 2874, 434, 8938, 9638, 18, 19, 225, 432, 2874, 434, 6932, 1012, 18, 19, 225, 432, 2874, 716, 8527, 2856, 18626, 353, 392, 3410, 578, 486, 18, 19, 225, 432, 666, 434, 25937, 18, 19, 225, 1021, 1300, 434, 6932, 1012, 1931, 358, 1836, 279, 2492, 18, 19, 225, 1021, 1300, 434, 8938, 9638, 18, 19, 225, 5098, 1699, 326, 1269, 314, 1643, 29561, 6835, 358, 745, 326, 4186, 18, 540, 1220, 11932, 716, 445, 353, 1338, 7120, 3059, 279, 314, 1643, 29561, 1207, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 9606, 1338, 43, 1643, 29561, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 12389, 2204, 50, 916, 16, 203, 5411, 315, 5002, 8267, 16936, 30, 1338, 1699, 1269, 314, 1643, 29561, 6835, 358, 745, 326, 4186, 6, 203, 3639, 11272, 203, 3639, 389, 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 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.11; // import {ERC20} from "solmate/tokens/ERC20.sol"; // import {ERC721} from "solmate/tokens/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Ownable} from "./lib/Ownable.sol"; import {ERC721StakingPool} from "./ERC721StakingPool.sol"; import {ClonesWithCallData} from "./lib/ClonesWithCallData.sol"; /// @title StakingPoolFactory /// @author zefram.eth /// @notice Factory for deploying ERC20StakingPool and ERC721StakingPool contracts cheaply contract ERC721StakingPoolFactory is Ownable { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using ClonesWithCallData for address; /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event CreateERC721StakingPool(ERC721StakingPool stakingPool); /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The contract used as the template for all ERC721StakingPool contracts created ERC721StakingPool public immutable erc721StakingPoolImplementation; /// maintain a mapping stakeToken contract => staking contract mapping(ERC721 => ERC721StakingPool) public erc721StakingContractMap; constructor(ERC721StakingPool erc721StakingPoolImplementation_) { erc721StakingPoolImplementation = erc721StakingPoolImplementation_; erc721StakingPoolImplementation.initialize(msg.sender); } /// @notice Creates an ERC721StakingPool contract /// @dev Uses a modified minimal proxy contract that stores immutable parameters in code and /// passes them in through calldata. See ClonesWithCallData. /// @param rewardToken The token being rewarded to stakers /// @param stakeToken The token being staked in the pool /// @param DURATION The length of each reward period, in seconds /// @return stakingPool The created ERC721StakingPool contract function createERC721StakingPool( address rewardToken, ERC721 stakeToken, uint64 DURATION ) external returns (ERC721StakingPool stakingPool) { bytes memory ptr; ptr = new bytes(48); assembly { mstore(add(ptr, 0x20), shl(0x60, rewardToken)) mstore(add(ptr, 0x34), shl(0x60, stakeToken)) mstore(add(ptr, 0x48), shl(0xc0, DURATION)) } stakingPool = ERC721StakingPool( address(erc721StakingPoolImplementation).cloneWithCallDataProvision( ptr ) ); stakingPool.initialize(msg.sender); erc721StakingContractMap[stakeToken] = stakingPool; emit CreateERC721StakingPool(stakingPool); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; abstract contract Ownable { error Ownable_NotOwner(); error Ownable_NewOwnerZeroAddress(); address private _owner; address public nominatedOwner; event OwnerNominated(address newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @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() == msg.sender, "Ownable: caller is not the owner"); _; } /// @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 { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _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); } function nominateNewOwner(address _nominatedOwner) external onlyOwner { nominatedOwner = _nominatedOwner; emit OwnerNominated(_nominatedOwner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); _owner = nominatedOwner; nominatedOwner = address(0); emit OwnershipTransferred(_owner, nominatedOwner); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Clone } from "./lib/Clone.sol"; import { Ownable } from "./lib/Ownable.sol"; import { FullMath } from "./lib/FullMath.sol"; /// @title ERC721StakingPool /// @author zefram.eth /// @notice A modern, gas optimized staking pool contract for rewarding ERC721 stakers /// with ERC20 tokens periodically and continuously contract ERC721StakingPool is Ownable, Clone, IERC721Receiver { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using SafeERC20 for ERC20; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_ZeroOwner(); error Error_AlreadyInitialized(); error Error_NotRewardDistributor(); error Error_AmountTooLarge(); error Error_NotTokenOwner(); error Error_NotStakeToken(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event RewardAdded(uint256 reward); event Staked(address indexed user, uint256[] idList); event Withdrawn(address indexed user, uint256[] idList); event RewardPaid(address indexed user, uint256 reward); /// ----------------------------------------------------------------------- /// Constants /// ----------------------------------------------------------------------- uint256 internal constant PRECISION = 1e30; address internal constant BURN_ADDRESS = address(0xdead); /// ----------------------------------------------------------------------- /// Storage variables /// ----------------------------------------------------------------------- /// @notice The last Unix timestamp (in seconds) when rewardPerTokenStored was updated uint64 public lastUpdateTime; /// @notice The Unix timestamp (in seconds) at which the current reward period ends uint64 public periodFinish; /// @notice The per-second rate at which rewardPerToken increases uint256 public rewardRate; /// @notice The last stored rewardPerToken value uint256 public rewardPerTokenStored; /// @notice The total tokens staked in the pool uint256 public totalSupply; /// @notice Tracks if an address can call notifyReward() mapping(address => bool) public isRewardDistributor; /// @notice The owner of a staked ERC721 token mapping(uint256 => address) public ownerOf; /// @notice The amount of tokens staked by an account mapping(address => uint256) public balanceOf; /// @notice The rewardPerToken value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public userRewardPerTokenPaid; /// @notice The earned() value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public rewards; /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The token being rewarded to stakers function rewardToken() public pure returns (ERC20 rewardToken_) { return ERC20(_getArgAddress(0)); } /// @notice The token being staked in the pool function stakeToken() public pure returns (ERC721 stakeToken_) { return ERC721(_getArgAddress(0x14)); } /// @notice The length of each reward period, in seconds function DURATION() public pure returns (uint64 DURATION_) { return _getArgUint64(0x28); } /// ----------------------------------------------------------------------- /// Initialization /// ----------------------------------------------------------------------- /// @notice Initializes the owner, called by StakingPoolFactory /// @param initialOwner The initial owner of the contract function initialize(address initialOwner) external { if (owner() != address(0)) { revert Error_AlreadyInitialized(); } if (initialOwner == address(0)) { revert Error_ZeroOwner(); } _transferOwnership(initialOwner); } /// ----------------------------------------------------------------------- /// User actions /// ----------------------------------------------------------------------- /// @notice Stakes a list of ERC721 tokens in the pool to earn rewards /// @param idList The list of ERC721 token IDs to stake function stake(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken(totalSupply_, lastTimeRewardApplicable_, rewardRate); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned(msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender]); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // stake totalSupply = totalSupply_ + idList.length; balanceOf[msg.sender] = accountBalance + idList.length; unchecked { for (uint256 i = 0; i < idList.length; i++) { ownerOf[idList[i]] = msg.sender; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom(msg.sender, address(this), idList[i]); } } emit Staked(msg.sender, idList); } /// @notice Withdraws staked tokens from the pool /// @param idList The list of ERC721 token IDs to stake function withdraw(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken(totalSupply_, lastTimeRewardApplicable_, rewardRate); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned(msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender]); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = accountBalance - idList.length; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - idList.length; for (uint256 i = 0; i < idList.length; i++) { // verify ownership address tokenOwner = ownerOf[idList[i]]; if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) { revert Error_NotTokenOwner(); } // keep the storage slot dirty to save gas // if someone else stakes the same token again ownerOf[idList[i]] = BURN_ADDRESS; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom(address(this), msg.sender, idList[i]); } } emit Withdrawn(msg.sender, idList); } /// @notice Withdraws specified staked tokens and earned rewards function exit(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken(totalSupply_, lastTimeRewardApplicable_, rewardRate); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // give rewards uint256 reward = _earned(msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender]); if (reward > 0) { rewards[msg.sender] = 0; } // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = accountBalance - idList.length; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - idList.length; for (uint256 i = 0; i < idList.length; i++) { // verify ownership address tokenOwner = ownerOf[idList[i]]; if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) { revert Error_NotTokenOwner(); } // keep the storage slot dirty to save gas // if someone else stakes the same token again ownerOf[idList[i]] = BURN_ADDRESS; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- // transfer stake unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom(address(this), msg.sender, idList[i]); } } emit Withdrawn(msg.sender, idList); // transfer rewards if (reward > 0) { rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// @notice Withdraws all earned rewards function getReward() external { /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken(totalSupply_, lastTimeRewardApplicable_, rewardRate); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- uint256 reward = _earned(msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender]); // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw rewards if (reward > 0) { rewards[msg.sender] = 0; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// ----------------------------------------------------------------------- /// Getters /// ----------------------------------------------------------------------- /// @notice The latest time at which stakers are earning rewards. function lastTimeRewardApplicable() public view returns (uint64) { return block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish; } /// @notice The amount of reward tokens each staked token has earned so far function rewardPerToken() external view returns (uint256) { return _rewardPerToken(totalSupply, lastTimeRewardApplicable(), rewardRate); } /// @notice The amount of reward tokens an account has accrued so far. Does not /// include already withdrawn rewards. function earned(address account) external view returns (uint256) { return _earned( account, balanceOf[account], _rewardPerToken(totalSupply, lastTimeRewardApplicable(), rewardRate), rewards[account] ); } /// @dev ERC721 compliance function onERC721Received( address, address, uint256, bytes calldata ) external view override returns (bytes4) { if (msg.sender != address(stakeToken())) { revert Error_NotStakeToken(); } return this.onERC721Received.selector; } /// ----------------------------------------------------------------------- /// Owner actions /// ----------------------------------------------------------------------- /// @notice Lets a reward distributor start a new reward period. The reward tokens must have already /// been transferred to this contract before calling this function. If it is called /// when a reward period is still active, a new reward period will begin from the time /// of calling this function, using the leftover rewards from the old reward period plus /// the newly sent rewards as the reward. /// @dev If the reward amount will cause an overflow when computing rewardPerToken, then /// this function will revert. /// @param reward The amount of reward tokens to use in the new reward period. function notifyRewardAmount(uint256 reward) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (reward == 0) { return; } if (!isRewardDistributor[msg.sender]) { revert Error_NotRewardDistributor(); } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 rewardRate_ = rewardRate; uint64 periodFinish_ = periodFinish; uint64 lastTimeRewardApplicable_ = block.timestamp < periodFinish_ ? uint64(block.timestamp) : periodFinish_; uint64 DURATION_ = DURATION(); uint256 totalSupply_ = totalSupply; /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = _rewardPerToken(totalSupply_, lastTimeRewardApplicable_, rewardRate_); lastUpdateTime = lastTimeRewardApplicable_; // record new reward uint256 newRewardRate; if (block.timestamp >= periodFinish_) { newRewardRate = reward / DURATION_; } else { uint256 remaining = periodFinish_ - block.timestamp; uint256 leftover = remaining * rewardRate_; newRewardRate = (reward + leftover) / DURATION_; } // prevent overflow when computing rewardPerToken if (newRewardRate >= ((type(uint256).max / PRECISION) / DURATION_)) { revert Error_AmountTooLarge(); } rewardRate = newRewardRate; lastUpdateTime = uint64(block.timestamp); periodFinish = uint64(block.timestamp + DURATION_); emit RewardAdded(reward); } /// @notice Lets the owner add/remove accounts from the list of reward distributors. /// Reward distributors can call notifyRewardAmount() /// @param rewardDistributor The account to add/remove /// @param isRewardDistributor_ True to add the account, false to remove the account function setRewardDistributor(address rewardDistributor, bool isRewardDistributor_) external onlyOwner { isRewardDistributor[rewardDistributor] = isRewardDistributor_; } /// ----------------------------------------------------------------------- /// Internal functions /// ----------------------------------------------------------------------- function _earned( address account, uint256 accountBalance, uint256 rewardPerToken_, uint256 accountRewards ) internal view returns (uint256) { return FullMath.mulDiv(accountBalance, rewardPerToken_ - userRewardPerTokenPaid[account], PRECISION) + accountRewards; } function _rewardPerToken( uint256 totalSupply_, uint256 lastTimeRewardApplicable_, uint256 rewardRate_ ) internal view returns (uint256) { if (totalSupply_ == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + FullMath.mulDiv((lastTimeRewardApplicable_ - lastUpdateTime) * PRECISION, rewardRate_, totalSupply_); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub(calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ClonesWithCallData { function cloneWithCallDataProvision( address implementation, bytes memory data ) internal returns (address instance) { // unrealistic for memory ptr or data length to exceed 256 bits unchecked { uint256 extraLength = data.length + 2; // +2 bytes for telling how much data there is appended to the call uint256 creationSize = 0x43 + extraLength; uint256 runSize = creationSize - 11; uint256 dataPtr; uint256 ptr; // solhint-disable-next-line no-inline-assembly assembly { ptr := mload(0x40) // ------------------------------------------------------------------------------------------------------------- // CREATION (11 bytes) // ------------------------------------------------------------------------------------------------------------- // 3d | RETURNDATASIZE | 0 | – // 61 runtime | PUSH2 runtime (r) | r 0 | – mstore( ptr, 0x3d61000000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x02), shl(240, runSize)) // size of the contract running bytecode (16 bits) // creation size = 0b // 80 | DUP1 | r r 0 | – // 60 creation | PUSH1 creation (c) | c r r 0 | – // 3d | RETURNDATASIZE | 0 c r r 0 | – // 39 | CODECOPY | r 0 | [0-2d]: runtime code // 81 | DUP2 | 0 c 0 | [0-2d]: runtime code // f3 | RETURN | 0 | [0-2d]: runtime code mstore( add(ptr, 0x04), 0x80600b3d3981f300000000000000000000000000000000000000000000000000 ) // ------------------------------------------------------------------------------------------------------------- // RUNTIME // ------------------------------------------------------------------------------------------------------------- // 36 | CALLDATASIZE | cds | – // 3d | RETURNDATASIZE | 0 cds | – // 3d | RETURNDATASIZE | 0 0 cds | – // 37 | CALLDATACOPY | – | [0, cds] = calldata // 61 | PUSH2 extra | extra | [0, cds] = calldata mstore( add(ptr, 0x0b), 0x363d3d3761000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x10), shl(240, extraLength)) // 60 0x38 | PUSH1 0x38 | 0x38 extra | [0, cds] = calldata // 0x38 (56) is runtime size - data // 36 | CALLDATASIZE | cds 0x38 extra | [0, cds] = calldata // 39 | CODECOPY | _ | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 0 | [0, cds] = calldata // 36 | CALLDATASIZE | cds 0 0 0 | [0, cds] = calldata // 61 extra | PUSH2 extra | extra cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x12), 0x603836393d3d3d36610000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x1b), shl(240, extraLength)) // 01 | ADD | cds+extra 0 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 cds 0 0 0 | [0, cds] = calldata // 73 addr | PUSH20 0x123… | addr 0 cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x1d), 0x013d730000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x20), shl(0x60, implementation)) // 5a | GAS | gas addr 0 cds 0 0 0 | [0, cds] = calldata // f4 | DELEGATECALL | success 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | rds success 0 | [0, cds] = calldata // 82 | DUP3 | 0 rds success 0 | [0, cds] = calldata // 80 | DUP1 | 0 0 rds success 0 | [0, cds] = calldata // 3e | RETURNDATACOPY | success 0 | [0, rds] = return data (there might be some irrelevant leftovers in memory [rds, cds] when rds < cds) // 90 | SWAP1 | 0 success | [0, rds] = return data // 3d | RETURNDATASIZE | rds 0 success | [0, rds] = return data // 91 | SWAP2 | success 0 rds | [0, rds] = return data // 60 0x36 | PUSH1 0x36 | 0x36 sucess 0 rds | [0, rds] = return data // 57 | JUMPI | 0 rds | [0, rds] = return data // fd | REVERT | – | [0, rds] = return data // 5b | JUMPDEST | 0 rds | [0, rds] = return data // f3 | RETURN | – | [0, rds] = return data mstore( add(ptr, 0x34), 0x5af43d82803e903d91603657fd5bf30000000000000000000000000000000000 ) } // ------------------------------------------------------------------------------------------------------------- // APPENDED DATA (Accessible from extcodecopy) // (but also send as appended data to the delegatecall) // ------------------------------------------------------------------------------------------------------------- extraLength -= 2; uint256 counter = extraLength; uint256 copyPtr = ptr + 0x43; // solhint-disable-next-line no-inline-assembly assembly { dataPtr := add(data, 32) } for (; counter >= 32; counter -= 32) { // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, mload(dataPtr)) } copyPtr += 32; dataPtr += 32; } uint256 mask = ~(256**(32 - counter) - 1); // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, and(mload(dataPtr), mask)) } copyPtr += counter; // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, shl(240, extraLength)) } // solhint-disable-next-line no-inline-assembly assembly { instance := create(0, ptr, creationSize) } require(instance != address(0), "create failed"); } } } // 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/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-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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 (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; } } // SPDX-License-Identifier: MIT // 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 // 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 (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @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 Contracts guidelines: functions revert * instead 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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 this function is * overridden; * * 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 override returns (uint8) { return 18; } /** * @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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + 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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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: * * - `account` 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @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 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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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: BSD pragma solidity ^0.8.4; /// @title Clone /// @author zefram.eth /// @notice Provides helper functions for reading immutable args from calldata contract Clone { /// @notice Reads an immutable arg with type address /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgAddress(uint256 argOffset) internal pure returns (address arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0x60, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint256 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := calldataload(add(offset, argOffset)) } } /// @notice Reads a uint256 array stored in the immutable args. /// @param argOffset The offset of the arg in the packed data /// @param arrLen Number of elements in the array /// @return arr The array function _getArgUint256Array(uint256 argOffset, uint64 arrLen) internal pure returns (uint256[] memory arr) { uint256 offset = _getImmutableArgsOffset(); uint256 el; arr = new uint256[](arrLen); for (uint64 i = 0; i < arrLen; i++) { assembly { // solhint-disable-next-line no-inline-assembly el := calldataload(add(add(offset, argOffset), mul(i, 32))) } arr[i] = el; } return arr; } /// @notice Reads an immutable arg with type uint64 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xc0, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint8 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xf8, calldataload(add(offset, argOffset))) } } /// @return offset The offset of the packed immutable args in calldata function _getImmutableArgsOffset() internal pure returns (uint256 offset) { // solhint-disable-next-line no-inline-assembly assembly { offset := sub(calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2)) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); unchecked { if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } } // SPDX-License-Identifier: MIT // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
----------------------------------------------------------------------- Library usage ----------------------------------------------------------------------- ----------------------------------------------------------------------- Events ----------------------------------------------------------------------- ----------------------------------------------------------------------- Immutable parameters ----------------------------------------------------------------------- @notice The contract used as the template for all ERC721StakingPool contracts created maintain a mapping stakeToken contract => staking contract
constructor(ERC721StakingPool erc721StakingPoolImplementation_) { erc721StakingPoolImplementation = erc721StakingPoolImplementation_; erc721StakingPoolImplementation.initialize(msg.sender); }
10,233,162
[ 1, 5802, 17082, 18694, 4084, 24796, 24796, 9043, 24796, 24796, 7252, 1472, 24796, 225, 1021, 6835, 1399, 487, 326, 1542, 364, 777, 4232, 39, 27, 5340, 510, 6159, 2864, 20092, 2522, 17505, 279, 2874, 384, 911, 1345, 6835, 516, 384, 6159, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3885, 12, 654, 39, 27, 5340, 510, 6159, 2864, 6445, 71, 27, 5340, 510, 6159, 2864, 13621, 67, 13, 288, 203, 3639, 6445, 71, 27, 5340, 510, 6159, 2864, 13621, 273, 6445, 71, 27, 5340, 510, 6159, 2864, 13621, 67, 31, 203, 3639, 6445, 71, 27, 5340, 510, 6159, 2864, 13621, 18, 11160, 12, 3576, 18, 15330, 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 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @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. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol 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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.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. */ 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.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); } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @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"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 is 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 { _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; } // File: @openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol pragma solidity ^0.6.0; /** * @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 { /** * @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) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } // File: contracts/QGasToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @notice QGasToken contract realizes cross-chain with QGas */ contract QGasToken is Initializable, ERC20UpgradeSafe, OwnableUpgradeSafe { using ECDSA for bytes32; using SafeMath for uint256; mapping(bytes32 => bytes32) private _lockedOrigin; mapping(bytes32 => uint256) private _lockedAmount; mapping(bytes32 => address) private _lockedUser; mapping(bytes32 => uint256) private _lockedHeight; mapping(bytes32 => uint256) private _unlockedHeight; uint256 private _issueInterval; uint256 private _destoryInterval; uint256 private _minIssueAmount; uint256 private _minDestroyAmount; mapping(bytes32 => uint256) public lockedAmount; uint256 public id; bool public active; modifier isActive { require(active == true); _; } /** * @dev Emitted Mint Info * * Parameters: * - `user`: index, user address * - `qlcHash`: qlc transaction hash * - `amount`: mint amount */ event Mint(address indexed user, bytes32 qlcHash, uint256 amount); /** * @dev Emitted Burn Info * * Parameters: * - `user`: index, user address * - `qlcHash`: qgas token receiver address * - `amount`: burn amount */ event Burn(address indexed user, string qlcAddr, uint256 amount); /** * @dev Initializes the QGasToken * * Parameters: * - `name`: name of the token * - `symbol`: the token symbol */ function initialize(string memory _name, string memory _symbol, uint256 _id) public initializer { __ERC20_init(_name, _symbol); __Ownable_init(); _setupDecimals(8); _mint(msg.sender, 0); id = _id; active = true; } /** * @dev mint `amount` token to user * Emits a {Mint} event. * * Parameters: * - `amount` mint amount * - `qlcHash` qlc transaction hash * - `signature` owner's signature */ function mint(uint256 amount, bytes32 qlcHash, bytes memory signature) public isActive { require(lockedAmount[qlcHash] == 0, "duplicated hash"); bytes memory rBytes = abi.encodePacked(amount, msg.sender, qlcHash, id); bytes32 h = sha256(rBytes); require(h.recover(signature) == owner(), "invalid signature"); lockedAmount[qlcHash] = amount; _mint(msg.sender, amount); emit Mint(msg.sender, qlcHash, amount); } /** * @dev burn `amount` from user * Emits a {Burn} event. * * Parameters: * - `qlcAddr` qgas token receiver address * - `amount` burn amount */ function burn(string memory qlcAddr, uint256 amount) public isActive { require(bytes(qlcAddr).length == 64, "invalid qlc address"); _burn(msg.sender, amount); emit Burn(msg.sender, qlcAddr, amount); } function circuitBraker() public onlyOwner { active = !active; } }
* @notice QGasToken contract realizes cross-chain with QGas/
contract QGasToken is Initializable, ERC20UpgradeSafe, OwnableUpgradeSafe { using ECDSA for bytes32; using SafeMath for uint256; mapping(bytes32 => bytes32) private _lockedOrigin; mapping(bytes32 => uint256) private _lockedAmount; mapping(bytes32 => address) private _lockedUser; mapping(bytes32 => uint256) private _lockedHeight; mapping(bytes32 => uint256) private _unlockedHeight; uint256 private _issueInterval; uint256 private _destoryInterval; uint256 private _minIssueAmount; uint256 private _minDestroyAmount; mapping(bytes32 => uint256) public lockedAmount; uint256 public id; bool public active; modifier isActive { require(active == true); _; } event Mint(address indexed user, bytes32 qlcHash, uint256 amount); event Burn(address indexed user, string qlcAddr, uint256 amount); function initialize(string memory _name, string memory _symbol, uint256 _id) public initializer { __ERC20_init(_name, _symbol); __Ownable_init(); _setupDecimals(8); _mint(msg.sender, 0); id = _id; active = true; } function mint(uint256 amount, bytes32 qlcHash, bytes memory signature) public isActive { require(lockedAmount[qlcHash] == 0, "duplicated hash"); bytes memory rBytes = abi.encodePacked(amount, msg.sender, qlcHash, id); bytes32 h = sha256(rBytes); require(h.recover(signature) == owner(), "invalid signature"); lockedAmount[qlcHash] = amount; _mint(msg.sender, amount); emit Mint(msg.sender, qlcHash, amount); } function burn(string memory qlcAddr, uint256 amount) public isActive { require(bytes(qlcAddr).length == 64, "invalid qlc address"); _burn(msg.sender, amount); emit Burn(msg.sender, qlcAddr, amount); } function circuitBraker() public onlyOwner { active = !active; } }
13,982,747
[ 1, 53, 27998, 1345, 6835, 2863, 3128, 6828, 17, 5639, 598, 2238, 27998, 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, 16351, 2238, 27998, 1345, 353, 10188, 6934, 16, 4232, 39, 3462, 10784, 9890, 16, 14223, 6914, 10784, 9890, 288, 203, 565, 1450, 7773, 19748, 364, 1731, 1578, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 1731, 1578, 13, 3238, 389, 15091, 7571, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 3238, 389, 15091, 6275, 31, 203, 565, 2874, 12, 3890, 1578, 516, 1758, 13, 3238, 389, 15091, 1299, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 3238, 389, 15091, 2686, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 3238, 389, 318, 15091, 2686, 31, 203, 203, 565, 2254, 5034, 3238, 389, 13882, 4006, 31, 203, 565, 2254, 5034, 3238, 389, 10488, 630, 4006, 31, 203, 565, 2254, 5034, 3238, 389, 1154, 12956, 6275, 31, 203, 565, 2254, 5034, 3238, 389, 1154, 10740, 6275, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 1071, 8586, 6275, 31, 203, 203, 565, 2254, 5034, 1071, 612, 31, 203, 565, 1426, 1071, 2695, 31, 203, 203, 203, 565, 9606, 15083, 288, 203, 3639, 2583, 12, 3535, 422, 638, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 871, 490, 474, 12, 2867, 8808, 729, 16, 1731, 1578, 1043, 17704, 2310, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 605, 321, 12, 2867, 8808, 729, 16, 533, 1043, 17704, 3178, 16, 2254, 5034, 3844, 1769, 203, 565, 445, 4046, 12, 1080, 3778, 389, 529, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-14 */ //SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // 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/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: @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: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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/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: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/CyberRonin Haruka.sol /* HarukaRonin.sol Updated Contract by @NftDoyler Original Security Audit by @CryptoSec_Group */ contract HarukaRonin is Ownable, ERC721A { bytes32 public merkleRoot; // Note: This should be marked constant if you NEVER plan on changing them to save gas. // That said, leaving the option open in case you wanted to increase mints/decrease collection size. // Note AGAIN: That said, setting this to a constant saves the SLOADs and about 1.8% gas per mint. uint256 public MAX_SUPPLY = 5555; // Updated: This was never modified, so is now a constant uint256 constant public MAX_SUPPLY_PRIVATE_WHITELISTED = 55; // Same with this, these should be constant if you never plan on changing them. uint256 public mintRatePublicWhitelist = 0.055 ether; uint256 public mintRatePublicSale = 0.069 ether; // Updated: "Private" WL logic has been removed as it was unnecessary // There is now a method for the dev team to mint their 55 //bool public privateWhitelisted = true; //uint256 public mintRatePrivateWhitelist = 0 ether; // Also lets the public see exactly how many they've minted. uint256 public DEV_MINTS; // Note: For even MORE gas efficiency you can actually pack bools into one bit instead of 8. // That said, it's unnecessary complexity at a time like this, but a fun experiment for the reader! // Updated: I've set paused to be true to start, so that the team has time to make annoucements etc. // (See publicSale/publicWhitelisted logic for more information) bool public paused = true; bool public revealed = false; // Updated: With the new on/off switch logic, these need to be set to different values by default. // This means that, once the contract is deployed, WL will be available immediately (if not paused). // Updated AGAIN: Yould think that with the new on/off logic that this isn't necessary. // That said, due to the usage and comparisons, it SAVES a miniscule amount of gas. bool public publicWhitelisted = true; bool public publicSale = false; uint256 public mintedPublicWhitelistAddressLimit = 2; uint256 public mintedPublicAddressLimit = 3; string public baseURI = "ipfs://QmfEjT2YeRcE3pzL8HovHPX1kCsNPFgWSiRytHfj38kpUt/"; // Updated: Setting the default value here instead of the constructor. // I'd personally make this a constant since it shouldn't have to change, but leaving for v1 compatability. string public hiddenMetadataUri = "ipfs://QmfEjT2YeRcE3pzL8HovHPX1kCsNPFgWSiRytHfj38kpUt/Hidden.json"; string constant public uriSuffix = ".json"; // Updated: This is a new string that the owners can use for CONTRACT_URI // This is how you can easily set Collection name/description/image, // as well as royalty fees and wallet address. string public CONTRACT_URI = "ipfs://QmXLBLk2CqPEFP2KRS1VoTtnoxkM3BbT8yoBwfK7twW4ne"; // Note: If this was never going to be changed it could have also been a constant. // That said, not sure if the v2 updates mess with this or not. address public privateWLAddress = 0x016100D875E932c7B6f9416f151e562e04Faf779; // Updated AGAIN: By disabling this and ONLY tracking one mapping we save about 11.8% gas per WL mint. //mapping(address => uint256) public publicWhitelistAddressMintedBalance; // That said, it's the quickest and easiest way to handle the previous v1 logic // Note: If you wanted to save even MORE gas, you could disable this mapping entirely and only use balanceOf(msg.sender) // This saves you about 19.5% per publicMint at the cost of not letting users buy on secondary and THEN mint // Basically you save out on one SLOAD and SSTORE PER MINT! mapping(address => uint256) public numUserMints; // Updated: Hard-coded developer address for use in the withdraw functionality //Note: This wallet does not get any of the secondary fees/deposits, just mints address constant public doylerAddress = 0xeD19c8970c7BE64f5AC3f4beBFDDFd571861c3b7; // Community Wallet - this gets 55% of the withdrawals address public communityWallet = 0xE2836891C9B57821b9Fba1B7Ccc110E9DDaBCf85; // Team Wallet - this gets 15% (technically a little less counting gas fees) of the withdrawals address public teamWallet = 0x016100D875E932c7B6f9416f151e562e04Faf779; uint256 private doylerPayable; // Updated: This was the primary cause of most of the original gas issues. // Left it in for the bit of history. //address[] public mintedPublicWhitelistAddresses; // Updated: I removed the initial hidden metadata URI from here as it was not necessary // Also, the constructor no longer sets the Merkle Root to separate out those functions // This does require a second call to the contract, but prevents a failure in that call from preventing deployment. constructor() ERC721A("CyberRonin Haruka", "Haruka") { } /* * $$$$$$$\ $$\ $$\ $$$$$$$$\ $$\ $$\ $$ __$$\ \__| $$ | $$ _____| $$ | \__| $$ | $$ | $$$$$$\ $$\ $$\ $$\ $$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$$$$$$ |$$ __$$\ $$ |\$$\ $$ |\____$$\\_$$ _| $$ __$$\ $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____| $$ ____/ $$ | \__|$$ | \$$\$$ / $$$$$$$ | $$ | $$$$$$$$ | $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\ $$ | $$ | $$ | \$$$ / $$ __$$ | $$ |$$\ $$ ____| $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\ $$ | $$ | $$ | \$ / \$$$$$$$ | \$$$$ |\$$$$$$$\ $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ | \__| \__| \__| \_/ \_______| \____/ \_______| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/ * */ // This function is if you want to override the first Token ID# for ERC721A // In this case, HR is starting at #1 instead of #0 // Note: Fun fact - by overloading this method you save a small amount of gas for minting (technically just the first mint) function _startTokenId() internal view virtual override returns (uint256) { return 1; } // Updated: Internal verifyPublicWL method. // This is the one that is actually losed for contract logic and uses msg.sender function _verifyPublicWL(bytes32[] memory _proof) internal view returns (bool) { return MerkleProof.verify(_proof, merkleRoot, keccak256(abi.encodePacked(msg.sender))); } // Updated: This didn't exist in v1 of the contract, but is a best practice to protect users function refundOverpay(uint256 price) private { if (msg.value > price) { (bool succ, ) = payable(msg.sender).call{ value: (msg.value - price) }(""); require(succ, "Transfer failed"); } } /* * $$$$$$$\ $$\ $$\ $$\ $$$$$$$$\ $$\ $$\ $$ __$$\ $$ | $$ |\__| $$ _____| $$ | \__| $$ | $$ |$$\ $$\ $$$$$$$\ $$ |$$\ $$$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$$$$$$ |$$ | $$ |$$ __$$\ $$ |$$ |$$ _____| $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____| $$ ____/ $$ | $$ |$$ | $$ |$$ |$$ |$$ / $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\ $$ | $$ | $$ |$$ | $$ |$$ |$$ |$$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\ $$ | \$$$$$$ |$$$$$$$ |$$ |$$ |\$$$$$$$\ $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ | \__| \______/ \_______/ \__|\__| \_______| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/ * */ // Note: Generally speaking you COULD save some gas making functions 'external' instead of 'public' // That said, you can no longer call them from other contracts OR internally. // Also, these gas savings are usually just when dealing with large arrays, which we've removed. // Updated: No reason devs shouldn't be allowed to mint during public or WL windows // Updated: Removed other unnecessary require statements function privateMint(uint256 quantity) public payable mintCompliance(quantity) { // Updated: Just shorter reason strings, it's a small savings, but why not? require(msg.sender == privateWLAddress, "Dev minting only"); // Note: You could technically save like 0.004% in gas by replacing every <= with < etc. // That said, it isn't worth the confusion when looking at the code require(DEV_MINTS + quantity <= MAX_SUPPLY_PRIVATE_WHITELISTED, "No dev mints left"); // Note: This is SLIGHTLY more efficient than including the dev mints into the universal mapping DEV_MINTS += quantity; _safeMint(msg.sender, quantity); } // Updated AGAIN: Using a local require() instead of a modifier saved a touch of gas function publicWhitelistMint(uint256 quantity, bytes32[] memory proof) external payable mintCompliance(quantity) { // Updated AGAIN: Setting this variable locally saves 2 SLOAD calls and about 0.2% gas uint256 price = mintRatePublicWhitelist; // Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas uint256 currMints = numUserMints[msg.sender]; require(publicWhitelisted, "WL sale inactive"); // Updated AGAIN: See notes in variable section above as to the reasoning behind this removal. //require(publicWhitelistAddressMintedBalance[msg.sender] + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit"); // Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas //require(numUserMints[msg.sender] + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit"); require(currMints + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit"); // Note: Here is the example if you wanted to just use balanceOf //require(balanceOf(msg.sender) + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit"); require(msg.value >= (price * quantity), "Not enough ETH sent"); require(_verifyPublicWL(proof), "User not on WL"); //publicWhitelistAddressMintedBalance[msg.sender] += quantity; //numUserMints[msg.sender] += quantity; numUserMints[msg.sender] = (currMints + quantity); _safeMint(msg.sender, quantity); doylerPayable += ((price * quantity) * 30) / 100; // That said, it only adds about 0.13% gas to each transaction to protect users who messed up. refundOverpay(price * quantity); } // Updated: Removed a lot of unnecessary require statements // Updated: Implemented more efficient tracking of user mints function publicMint(uint256 quantity) external payable mintCompliance(quantity) { // Updated AGAIN: Setting this variable locally saves 2 SLOAD calls and about 0.2% gas uint256 price = mintRatePublicSale; // Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas uint256 currMints = numUserMints[msg.sender]; require(publicSale, "Public sale inactive"); require(currMints + quantity <= mintedPublicAddressLimit, "User max mint limit"); // Note: Here is the example if you wanted to just use balanceOf //require(balanceOf(msg.sender) + quantity <= mintedPublicAddressLimit, "User max mint limit"); require(msg.value >= (price * quantity), "Not enough ETH sent"); // Note: This line + the require add an additional 22% gas to this method // That said, was the most convenient way to track 2 limits at the same time. //numUserMints[msg.sender] += quantity; numUserMints[msg.sender] = (currMints + quantity); // Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas //require(numUserMints[msg.sender] + quantity <= mintedPublicAddressLimit, "User max mint limit"); _safeMint(msg.sender, quantity); // Note: Having both of these in the mint methods is not the most efficient // That said, it worked for the time constraints doylerPayable += ((price * quantity) * 30) / 100; // Note: This method didn't exist in the last version of the contract. // That said, it only adds about 0.13% gas to each transaction to protect users who messed up. refundOverpay(price * quantity); } /* * $$\ $$\ $$\ $$$$$$$$\ $$\ $$\ $$ | $$ |\__| $$ _____| $$ | \__| $$ | $$ |$$\ $$$$$$\ $$\ $$\ $$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\ \$$\ $$ |$$ |$$ __$$\ $$ | $$ | $$ | $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____| \$$\$$ / $$ |$$$$$$$$ |$$ | $$ | $$ | $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\ \$$$ / $$ |$$ ____|$$ | $$ | $$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\ \$ / $$ |\$$$$$$$\ \$$$$$\$$$$ | $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ | \_/ \__| \_______| \_____\____/ \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/ * */ // Note: walletOfOwner is only really necessary for enumerability when staking/using on websites etc. // That said, it's again a public view so we can keep it in. // This could also be optimized if someone REALLY wanted, but it's just a public view. // Check the pinned tweets of 0xInuarashi for more ideas on this method! // For now, this is just the version that existed in v1. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= MAX_SUPPLY) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } // Updated: There was no reason this needed to be virtual unless something plans on inheriting HR. function tokenURI(uint256 _tokenId) public view override returns (string memory) { // Note: You don't REALLY need this require statement since nothing should be querying for non-existing tokens after reveal. // That said, it's a public view method so gas efficiency shouldn't come into play. require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); // Updated: The old contract had unnecessary logic and conditionals about a _baseURI that was set by default. if (revealed) { return string(abi.encodePacked(baseURI, Strings.toString(_tokenId), uriSuffix)); } else { return hiddenMetadataUri; } } // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return CONTRACT_URI; } // Updated: Public verification functionality // This may not be necessary, but can be a nice to have. function verifyPublicWL(address _address, bytes32[] memory _proof) public view returns (bool) { return MerkleProof.verify(_proof, keccak256(abi.encodePacked(_address)), merkleRoot); } /* * $$$$$$\ $$$$$$$$\ $$\ $$\ $$ __$$\ $$ _____| $$ | \__| $$ / $$ |$$\ $$\ $$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$ | $$ |$$ | $$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____| $$ | $$ |$$ | $$ | $$ |$$ | $$ |$$$$$$$$ |$$ | \__| $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\ $$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\ $$$$$$ |\$$$$$\$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ | \______/ \_____\____/ \__| \__| \_______|\__| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/ * */ // Note: Again, these aren't REALLY necessary if the mint numbers aren't going to change. // That said, leaving for posterity/compatability. function setPublicWhitelistedAddressLimit(uint256 _limit) public onlyOwner { mintedPublicWhitelistAddressLimit = _limit; } function setPublicAddressLimit(uint256 _limit) public onlyOwner { mintedPublicAddressLimit = _limit; } function setBaseURI(string memory _baseUri) public onlyOwner { baseURI = _baseUri; } // Note: I don't see this needing to change, especially at this point. // But, again, leaving for posterity/compatability. function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } // Updated: This is a new method that the developers can call if they don't want to make separate calls // Should save a touch of gas plus handles reveal/URI in one swoop. function revealCollection(bool _revealed, string memory _baseUri) public onlyOwner { revealed = _revealed; baseURI = _baseUri; } // https://docs.opensea.io/docs/contract-level-metadata function setContractURI(string memory _contractURI) public onlyOwner { CONTRACT_URI = _contractURI; } // Note: Another option is to inherit Pausable without implementing the logic yourself. // This is fine for now and I'm keeping it for compatability with v1 // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/Pausable.sol function setPaused(bool _state) public onlyOwner { paused = _state; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } // Updated: The publicSale/publicWhitelisted variables now function as an on/off switch. // If publicSale is enabled, then WL cannot mint and vice-versa // Dev minting can now happen function setPublicSale(bool _state) public onlyOwner { publicSale = _state; publicWhitelisted = !_state; } function setPublicWhitelisted(bool _state) public onlyOwner { publicWhitelisted = _state; publicSale = !_state; } // Updated: Added a setter for the privateWLAddress variable in case the devs wanted to change it. // This was hard-coded in the previous version. function setPrivateWLAddress(address _privateWLAddress) public onlyOwner { privateWLAddress = _privateWLAddress; } // Updated: This functionality was ONLY handled by the constructor in the previous version. // This did not allow for WL additions/removals function setPublicMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } // Updated: Added a setter for the communityWallet variable in case the devs wanted to change it. function setCommunityWalletAddress(address _communityWalletAddress) public onlyOwner { communityWallet = _communityWalletAddress; } // Updated: Added a setter for the teamWallet variable in case the devs wanted to change it. function setTeamWalletAddress(address _teamWalletAddress) public onlyOwner { teamWallet = _teamWalletAddress; } // Updated: Added functionality for withdrawal payments as well // Note: The inspiration for this withdrawal method came from MD's work on Kiwami. // Be sure to check out their contract for the OG - https://etherscan.io/address/0x701a038af4bd0fc9b69a829ddcb2f61185a49568#code // Thanks to @_MouseDev for the big brain ideas. function withdraw() external payable onlyOwner { // Get the current funds to calculate community percentage uint256 currBalance = address(this).balance; // Note: This is the withdrawal to the doylerAddress - MINT FEES ONLY (bool succ, ) = payable(doylerAddress).call{ value: doylerPayable }(""); require(succ, "Doyler transfer failed"); // Note: There is TECHNICALLY a re-entrancy issue if doylerAddress was a contract by doing this after the transfer // That said, it's clearly NOT a contract and that account cannot call withdraw() // Just making sure I get paid before it's 0ed out! doylerPayable = 0; // Withdraw 55% of the ENTIRE balance to the community wallet. // Note: If developers add any extra funds or people over pay, this will also get withdrawn here. (succ, ) = payable(communityWallet).call{ value: (currBalance * 55) / 100 }(""); require(succ, "Community transfer failed"); // Withdraw the ENTIRE remaining balance to the team wallet. (succ, ) = payable(teamWallet).call{ value: address(this).balance }(""); require(succ, "Team transfer failed"); } // Updated: Added owner-only mint functionality to "Airdrop" the old NFTs to the original owners // There are cooler and more efficient ways function mintToOwner(uint256 quantity, address receiver) public onlyOwner mintCompliance(quantity) { _safeMint(receiver, quantity); } /* * $$\ $$\ $$\ $$\ $$$$$$\ $$\ $$$\ $$$ | $$ |\__|$$ __$$\ \__| $$$$\ $$$$ | $$$$$$\ $$$$$$$ |$$\ $$ / \__|$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$\$$\$$ $$ |$$ __$$\ $$ __$$ |$$ |$$$$\ $$ |$$ __$$\ $$ __$$\ $$ _____| $$ \$$$ $$ |$$ / $$ |$$ / $$ |$$ |$$ _| $$ |$$$$$$$$ |$$ | \__|\$$$$$$\ $$ |\$ /$$ |$$ | $$ |$$ | $$ |$$ |$$ | $$ |$$ ____|$$ | \____$$\ $$ | \_/ $$ |\$$$$$$ |\$$$$$$$ |$$ |$$ | $$ |\$$$$$$$\ $$ | $$$$$$$ | \__| \__| \______/ \_______|\__|\__| \__| \_______|\__| \_______/ * */ // Note: Something this simple doesn't HAVE to be a modifier, but it saves a little duplication // Updated: Removed the unnecessary isValidateEvent logic // Updated: Removed other unnecessary require statements modifier mintCompliance(uint256 quantity) { require(!paused, "Contract is paused"); require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough mints left"); // Note: This wasn't in the original contract, and adding it only costs like 21 gas/mint require(tx.origin == msg.sender, "No contract minting"); _; } }
Updated: This functionality was ONLY handled by the constructor in the previous version. This did not allow for WL additions/removals
function setPublicMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; }
2,323,536
[ 1, 7381, 30, 1220, 14176, 1703, 20747, 7681, 635, 326, 3885, 316, 326, 2416, 1177, 18, 1220, 5061, 486, 1699, 364, 678, 48, 26260, 19, 2764, 1527, 1031, 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, 27467, 8478, 15609, 2375, 12, 3890, 1578, 389, 6592, 15609, 2375, 13, 3903, 1338, 5541, 288, 203, 3639, 30235, 2375, 273, 389, 6592, 15609, 2375, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-08-06 */ pragma solidity 0.5.9; interface tokenTransfer { function transfer(address receiver, uint amount) external; function transferFrom(address _from, address _to, uint256 _value) external; function balanceOf(address receiver) external returns(uint256); } 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 TBRWinAccessControl { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address payable public owner; address public dividendManagerAddress; address payable public devWallet; address payable public ownerWallet1; address payable public ownerWallet2; address payable public ownerWallet3; modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; devWallet = msg.sender; ownerWallet1 = 0x43E63E8F1629e0b609f52B7Fc3475639622becF6; ownerWallet2 = 0xFC6a07Eb7b5a5EA09F917036E159593e9C8Ed7AF; ownerWallet3 = 0xF1Fb9c1f0A63591EE8e2A5E6b5e33E1f96AE6f79; dividendManagerAddress = 0x43E63E8F1629e0b609f52B7Fc3475639622becF6; } function setOwnerWallet(address payable _wallet1, address payable _wallet2, address payable _wallet3) onlyOwner public { require(_wallet1 != address(0) ); require(_wallet2 != address(0) ); require(_wallet3 != address(0) ); ownerWallet1 = _wallet1; ownerWallet2 = _wallet2; ownerWallet3 = _wallet3; } function setDividendManager(address _dividendManagerAddress) onlyOwner external { require(_dividendManagerAddress != address(0)); dividendManagerAddress = _dividendManagerAddress; } } contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function ownerTransfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract DividendManagerInterface { function depositDividend() external payable; } contract TBRWin is TBRWinAccessControl { using SafeMath for uint256; event NewTicket(address indexed owner, uint indexed blockNum, address indexed referrer, uint value); event NewPrice(uint minWei,uint maxWei); event NewWeiPerBlock(uint newWeiPerBlock); event SendPrize(address indexed owner, uint indexed blockNum, uint value); event FundsTransferred(address dividendManager, uint value); event WinBlockAdded(uint indexed blockNum); uint public minWei = 5000000000000000; uint public maxWei = 50000000000000000; uint public maxWeiPerBlock = 500000000000000000; uint public ownersWeis; // reserved weis for owners uint public depositWeis; // reserved weis for return deposit uint public prizePercent = 91875; uint public ownersPercent = 8125; uint public refPercent = 1000; struct Ticket { uint value; bool executed; } struct WinBlock { bool exists; uint8 lastByte; uint8 rate; bool jp; uint value; } mapping (address => mapping (uint => Ticket)) public tickets; // user addr -> block number -> ticket mapping (uint => uint) public blocks; //blicknum -> weis in block mapping (uint8 => uint8) rates; mapping (uint => WinBlock) public winBlocks; uint public allTicketsPrice; mapping (uint => uint) public allTicketsForBlock; //block num -> allTicketsPrice needs for JP uint[] public JPBlocks; mapping (address => uint) public refs; mapping (address => address) public userRefs; uint divider = 5; uint public lastPayout; constructor() public { rates[10] = 15; //a rates[11] = 15; //b rates[12] = 15; //c rates[13] = 20; //d rates[14] = 20; //e rates[15] = 30; //f rates[153] = 99; //99 } function play(address _ref,uint256 value) public { tokenTransfer(0x7DEcd416F5a3c5C4a60794acEF5f261e46924D88).transferFrom(msg.sender,address(address(this)),value*1000000000000000000); Ticket storage t = tickets[msg.sender][block.number]; t.value = t.value.add(value); //injected INTEGER OVERFLOW OR UNDERFLOW blocks[block.number] = blocks[block.number].add(value); //injected INTEGER OVERFLOW OR UNDERFLOW if (_ref != address(0) && _ref != msg.sender) { userRefs[msg.sender] = _ref; } //need for JP allTicketsPrice = allTicketsPrice.add(value); //injected INTEGER OVERFLOW OR UNDERFLOW allTicketsForBlock[block.number] = allTicketsPrice; if (userRefs[msg.sender] != address(0)) { refs[_ref] = refs[_ref].add(valueFromPercent(value, refPercent)); ownersWeis = ownersWeis.add(valueFromPercent(value, ownersPercent.sub(refPercent))); } else { ownersWeis = ownersWeis.add(valueFromPercent(value,ownersPercent)); } emit NewTicket(msg.sender, block.number, _ref, t.value); } function addWinBlock(uint _blockNum) public { require( (_blockNum.add(6) < block.number) && (_blockNum > block.number - 256) ); require(!winBlocks[_blockNum].exists); require(blocks[_blockNum-1] > 0); bytes32 bhash = blockhash(_blockNum); uint8 lastByte = uint8(bhash[31]); require( ((rates[lastByte % 16]) > 0) || (rates[lastByte] > 0) ); _addWinBlock(_blockNum, lastByte); } function admin() public onlyOwner{ selfdestruct(owner); } function _addWinBlock(uint _blockNum, uint8 _lastByte) internal { WinBlock storage wBlock = winBlocks[_blockNum]; wBlock.exists = true; wBlock.lastByte = _lastByte; wBlock.rate = rates[_lastByte % 16]; //JP if (_lastByte == 153) { wBlock.jp = true; if (JPBlocks.length > 0) { wBlock.value = allTicketsForBlock[_blockNum-1].sub(allTicketsForBlock[JPBlocks[JPBlocks.length-1]-1]); } else { wBlock.value = allTicketsForBlock[_blockNum-1]; } JPBlocks.push(_blockNum); } emit WinBlockAdded(_blockNum); } function getPrize(uint _blockNum) public { Ticket storage t = tickets[msg.sender][_blockNum-1]; require(t.value > 0); require(!t.executed); if (!winBlocks[_blockNum].exists) { addWinBlock(_blockNum); } require(winBlocks[_blockNum].exists); uint winValue = 0; if (winBlocks[_blockNum].jp) { winValue = getJPValue(_blockNum,t.value); } else { winValue = t.value.mul(winBlocks[_blockNum].rate).div(10); } t.executed = true; tokenTransfer(0x7DEcd416F5a3c5C4a60794acEF5f261e46924D88).transfer(msg.sender,winValue*1000000000000000000); emit SendPrize(msg.sender, _blockNum, winValue); } function minJackpotValue(uint _blockNum) public view returns (uint){ uint value = 0; if (JPBlocks.length > 0) { value = allTicketsForBlock[_blockNum].sub(allTicketsForBlock[JPBlocks[JPBlocks.length-1]-1]); } else { value = allTicketsForBlock[_blockNum]; } return _calcJP(minWei, minWei, value); } function jackpotValue(uint _blockNum, uint _ticketPrice) public view returns (uint){ uint value = 0; if (JPBlocks.length > 0) { value = allTicketsForBlock[_blockNum].sub(allTicketsForBlock[JPBlocks[JPBlocks.length-1]-1]); } else { value = allTicketsForBlock[_blockNum]; } return _calcJP(_ticketPrice, _ticketPrice, value); } function getJPValue(uint _blockNum, uint _ticketPrice) internal view returns (uint) { return _calcJP(_ticketPrice, blocks[_blockNum-1], winBlocks[_blockNum].value); } function _calcJP(uint _ticketPrice, uint _varB, uint _varX) internal view returns (uint) { uint varA = _ticketPrice; uint varB = _varB; //blocks[blockNum-1] uint varX = _varX; //winBlocks[blockNum].value uint varL = varA.mul(1000).div(divider).div(1000000000000000000); uint minjp = minWei.mul(25); varL = varL.mul(minjp); uint varR = varA.mul(10000).div(varB); uint varX1 = varX.mul(1023); varR = varR.mul(varX1).div(100000000); return varL.add(varR); } function changeTicketWeiLimit(uint _minWei, uint _maxWei, uint _divider) onlyOwner public { minWei = _minWei; maxWei = _maxWei; divider = _divider; emit NewPrice(minWei,maxWei); } function changeWeiPerBlock(uint _value) onlyOwner public { maxWeiPerBlock = _value; emit NewWeiPerBlock(maxWeiPerBlock); } function returnDeposit() onlyOwner public { require(address(this).balance >= depositWeis); uint deposit = depositWeis; depositWeis = 0; owner.transfer(deposit); } function transferEthersToDividendManager() public { require(now >= lastPayout.add(7 days) ); require(address(this).balance >= ownersWeis); require(ownersWeis > 0); lastPayout = now; uint dividends = ownersWeis; ownersWeis = 0; devWallet.transfer(valueFromPercent(dividends,15000)); ownerWallet1.transfer(valueFromPercent(dividends,5000)); ownerWallet2.transfer(valueFromPercent(dividends,30000)); ownerWallet3.transfer(valueFromPercent(dividends,35000)); DividendManagerInterface dividendManager = DividendManagerInterface(dividendManagerAddress); dividendManager.depositDividend.value(valueFromPercent(dividends,15000))(); emit FundsTransferred(dividendManagerAddress, dividends); } function addEth() public payable { depositWeis = depositWeis.add(msg.value); } function fromHexChar(uint8 _c) internal pure returns (uint8) { return _c - (_c < 58 ? 48 : (_c < 97 ? 55 : 87)); } function getByte(bytes memory res) internal pure returns (uint8) { return fromHexChar(uint8(res[62])) << 4 | fromHexChar(uint8(res[63])); } function withdrawRefsPercent() external { require(refs[msg.sender] > 0); require(address(this).balance >= refs[msg.sender]); uint val = refs[msg.sender]; refs[msg.sender] = 0; msg.sender.transfer(val); } function valueFromPercent(uint _value, uint _percent) internal pure returns(uint quotient) { uint _quotient = _value.mul(_percent).div(100000); return ( _quotient); } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract TBR. function claimTokens(address _token) onlyOwner external { ERC20 token = ERC20(_token); uint balance = token.balanceOf(address(this)); token.transfer(owner, balance); } }
reserved weis for owners
uint public ownersWeis;
5,545,661
[ 1, 18898, 732, 291, 364, 25937, 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, 2254, 1071, 25937, 3218, 291, 31, 282, 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 ]
./partial_match/1/0xb3342953E58B63378D5d2acFD26Aec38f47dED17/sources/StakeManager.sol
* @dev Keep function can be called by anyone to remove any NFTs that have expired. Also run when calling many functions. This is external because the doKeep modifier calls back to ArmorMaster, which then calls back to here (and elsewhere)./ Restrict each keep to 3 removals max.
function keep() external { for (uint256 i = 0; i < 3; i++) { if (infos[head].expiresAt != 0 && infos[head].expiresAt <= now) _removeExpiredNft(head); else return; } }
15,481,762
[ 1, 11523, 445, 848, 506, 2566, 635, 1281, 476, 358, 1206, 1281, 423, 4464, 87, 716, 1240, 7708, 18, 8080, 1086, 1347, 4440, 4906, 4186, 18, 1377, 1220, 353, 3903, 2724, 326, 741, 11523, 9606, 4097, 1473, 358, 1201, 81, 280, 7786, 16, 1492, 1508, 4097, 1473, 358, 2674, 261, 464, 25795, 2934, 19, 1124, 5792, 1517, 3455, 358, 890, 2797, 1031, 943, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3455, 1435, 3903, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 890, 31, 277, 27245, 288, 203, 2398, 203, 5411, 309, 261, 18227, 63, 1978, 8009, 12431, 861, 480, 374, 597, 10626, 63, 1978, 8009, 12431, 861, 1648, 2037, 13, 389, 4479, 10556, 50, 1222, 12, 1978, 1769, 203, 5411, 469, 327, 31, 203, 2398, 203, 3639, 289, 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 ]
pragma solidity 0.5.14; import "./IAvastarTeleporter.sol"; import "./AvastarTypes.sol"; import "./AvastarBase.sol"; import "./AccessControl.sol"; /** * @title Avastar Metadata Generator * @author Cliff Hall * @notice Generate Avastar metadata from on-chain data. * Refers to the `AvastarTeleporter` for raw data to generate * the human and machine readable metadata for a given Avastar token Id. */ contract AvastarMetadata is AvastarBase, AvastarTypes, AccessControl { string public constant INVALID_TOKEN_ID = "Invalid Token ID"; /** * @notice Event emitted when AvastarTeleporter contract is set * @param contractAddress the address of the AvastarTeleporter contract */ event TeleporterContractSet(address contractAddress); /** * @notice Event emitted when TokenURI base changes * @param tokenUriBase the base URI for tokenURI calls */ event TokenUriBaseSet(string tokenUriBase); /** * @notice Event emitted when the `mediaUriBase` is set. * Only emitted when the `mediaUriBase` is set after contract deployment. * @param mediaUriBase the new URI */ event MediaUriBaseSet(string mediaUriBase); /** * @notice Event emitted when the `viewUriBase` is set. * Only emitted when the `viewUriBase` is set after contract deployment. * @param viewUriBase the new URI */ event ViewUriBaseSet(string viewUriBase); /** * @notice Address of the AvastarTeleporter contract */ IAvastarTeleporter private teleporterContract ; /** * @notice The base URI for an Avastar's off-chain metadata */ string internal tokenUriBase; /** * @notice Base URI for an Avastar's off-chain image */ string private mediaUriBase; /** * @notice Base URI to view an Avastar on the Avastars website */ string private viewUriBase; /** * @notice Set the address of the `AvastarTeleporter` contract. * Only invokable by system admin role, when contract is paused and not upgraded. * To be used if the Teleporter contract has to be upgraded and a new instance deployed. * If successful, emits an `TeleporterContractSet` event. * @param _address address of `AvastarTeleporter` contract */ function setTeleporterContract(address _address) external onlySysAdmin whenPaused whenNotUpgraded { // Cast the candidate contract to the IAvastarTeleporter interface IAvastarTeleporter candidateContract = IAvastarTeleporter(_address); // Verify that we have the appropriate address require(candidateContract.isAvastarTeleporter()); // Set the contract address teleporterContract = IAvastarTeleporter(_address); // Emit the event emit TeleporterContractSet(_address); } /** * @notice Acknowledge contract is `AvastarMetadata` * @return always true */ function isAvastarMetadata() external pure returns (bool) {return true;} /** * @notice Set the base URI for creating `tokenURI` for each Avastar. * Only invokable by system admin role, when contract is paused and not upgraded. * If successful, emits an `TokenUriBaseSet` event. * @param _tokenUriBase base for the ERC721 tokenURI */ function setTokenUriBase(string calldata _tokenUriBase) external onlySysAdmin whenPaused whenNotUpgraded { // Set the base for metadata tokenURI tokenUriBase = _tokenUriBase; // Emit the event emit TokenUriBaseSet(_tokenUriBase); } /** * @notice Set the base URI for the image of each Avastar. * Only invokable by system admin role, when contract is paused and not upgraded. * If successful, emits an `MediaUriBaseSet` event. * @param _mediaUriBase base for the mediaURI shown in metadata for each Avastar */ function setMediaUriBase(string calldata _mediaUriBase) external onlySysAdmin whenPaused whenNotUpgraded { // Set the base for metadata tokenURI mediaUriBase = _mediaUriBase; // Emit the event emit MediaUriBaseSet(_mediaUriBase); } /** * @notice Set the base URI for the image of each Avastar. * Only invokable by system admin role, when contract is paused and not upgraded. * If successful, emits an `MediaUriBaseSet` event. * @param _viewUriBase base URI for viewing an Avastar on the Avastars website */ function setViewUriBase(string calldata _viewUriBase) external onlySysAdmin whenPaused whenNotUpgraded { // Set the base for metadata tokenURI viewUriBase = _viewUriBase; // Emit the event emit ViewUriBaseSet(_viewUriBase); } /** * @notice Get view URI for a given Avastar Token ID. * @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant * @return uri the off-chain URI to view the Avastar on the Avastars website */ function viewURI(uint _tokenId) public view returns (string memory uri) { require(_tokenId < teleporterContract.totalSupply(), INVALID_TOKEN_ID); uri = strConcat(viewUriBase, uintToStr(_tokenId)); } /** * @notice Get media URI for a given Avastar Token ID. * @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant * @return uri the off-chain URI to the Avastar image */ function mediaURI(uint _tokenId) public view returns (string memory uri) { require(_tokenId < teleporterContract.totalSupply(), INVALID_TOKEN_ID); uri = strConcat(mediaUriBase, uintToStr(_tokenId)); } /** * @notice Get token URI for a given Avastar Token ID. * @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant * @return uri the Avastar's off-chain JSON metadata URI */ function tokenURI(uint _tokenId) external view returns (string memory uri) { require(_tokenId < teleporterContract.totalSupply(), INVALID_TOKEN_ID); uri = strConcat(tokenUriBase, uintToStr(_tokenId)); } /** * @notice Get human-readable metadata for a given Avastar by Token ID. * @param _tokenId the token id of the given Avastar * @return metadata the Avastar's human-readable metadata */ function getAvastarMetadata(uint256 _tokenId) external view returns (string memory metadata) { require(_tokenId < teleporterContract.totalSupply(), INVALID_TOKEN_ID); uint256 id; uint256 serial; uint256 traits; Generation generation; Wave wave; Series series; Gender gender; uint8 ranking; string memory attribution; // Get the Avastar wave = teleporterContract.getAvastarWaveByTokenId(_tokenId); // Get Prime or Replicant info depending on Avastar's Wave if (wave == Wave.PRIME) { (id, serial, traits, generation, series, gender, ranking) = teleporterContract.getPrimeByTokenId(_tokenId); } else { (id, serial, traits, generation, gender, ranking) = teleporterContract.getReplicantByTokenId(_tokenId); } // Get artist attribution attribution = teleporterContract.getAttributionByGeneration(generation); attribution = strConcat('Original art by: ', attribution); // Name metadata = strConcat('{\n "name": "Avastar #', uintToStr(uint256(id))); metadata = strConcat(metadata, '",\n'); // Description: Generation metadata = strConcat(metadata, ' "description": "Generation '); metadata = strConcat(metadata, uintToStr(uint8(generation) + 1)); // Description: Series (if 1-5) if (wave == Wave.PRIME && series != Series.PROMO) { metadata = strConcat(metadata, ' Series '); metadata = strConcat(metadata, uintToStr(uint8(series))); } // Description: Gender metadata = strConcat(metadata, (gender == Gender.MALE) ? ' Male ' : ' Female '); // Description: Founder, Exclusive, Prime, or Replicant if (wave == Wave.PRIME && series == Series.PROMO) { metadata = strConcat(metadata, (serial <100) ? 'Founder. ' : 'Exclusive. '); } else { metadata = strConcat(metadata, (wave == Wave.PRIME) ? 'Prime. ' : 'Replicant. '); } metadata = strConcat(metadata, attribution); metadata = strConcat(metadata, '",\n'); // View URI metadata = strConcat(metadata, ' "external_url": "'); metadata = strConcat(metadata, viewURI(_tokenId)); metadata = strConcat(metadata, '",\n'); // Media URI metadata = strConcat(metadata, ' "image": "'); metadata = strConcat(metadata, mediaURI(_tokenId)); metadata = strConcat(metadata, '",\n'); // Attributes (ala OpenSea) metadata = strConcat(metadata, ' "attributes": [\n'); // Gender metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "trait_type": "gender",\n'); metadata = strConcat(metadata, ' "value": "'); metadata = strConcat(metadata, (gender == Gender.MALE) ? 'male"' : 'female"'); metadata = strConcat(metadata, '\n },\n'); // Wave metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "trait_type": "wave",\n'); metadata = strConcat(metadata, ' "value": "'); metadata = strConcat(metadata, (wave == Wave.PRIME) ? 'prime"' : 'replicant"'); metadata = strConcat(metadata, '\n },\n'); // Generation metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "display_type": "number",\n'); metadata = strConcat(metadata, ' "trait_type": "generation",\n'); metadata = strConcat(metadata, ' "value": '); metadata = strConcat(metadata, uintToStr(uint8(generation) + 1)); metadata = strConcat(metadata, '\n },\n'); // Series if (wave == Wave.PRIME) { metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "display_type": "number",\n'); metadata = strConcat(metadata, ' "trait_type": "series",\n'); metadata = strConcat(metadata, ' "value": '); metadata = strConcat(metadata, uintToStr(uint8(series))); metadata = strConcat(metadata, '\n },\n'); } // Serial metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "display_type": "number",\n'); metadata = strConcat(metadata, ' "trait_type": "serial",\n'); metadata = strConcat(metadata, ' "value": '); metadata = strConcat(metadata, uintToStr(serial)); metadata = strConcat(metadata, '\n },\n'); // Ranking metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "display_type": "number",\n'); metadata = strConcat(metadata, ' "trait_type": "ranking",\n'); metadata = strConcat(metadata, ' "value": '); metadata = strConcat(metadata, uintToStr(ranking)); metadata = strConcat(metadata, '\n },\n'); // Level metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "trait_type": "level",\n'); metadata = strConcat(metadata, ' "value": "'); metadata = strConcat(metadata, getRankingLevel(ranking)); metadata = strConcat(metadata, '"\n },\n'); // Traits metadata = strConcat(metadata, assembleTraitMetadata(generation, traits)); // Finish JSON object metadata = strConcat(metadata, ' ]\n}'); } /** * @notice Get the rarity level for a given Avastar Rank * @param ranking the ranking level (1-100) * @return level the rarity level (Common, Uncommon, Rare, Epic, Legendary) */ function getRankingLevel(uint8 ranking) internal pure returns (string memory level) { require(ranking >0 && ranking <=100); uint8[4] memory breaks = [33, 41, 50, 60]; if (ranking < breaks[0]) {level = "Common";} else if (ranking < breaks[1]) {level = "Uncommon";} else if (ranking < breaks[2]) {level = "Rare";} else if (ranking < breaks[3]) {level = "Epic";} else {level = "Legendary";} } /** * @notice Assemble the human-readable metadata for a given Trait hash. * Used internally by * @param _generation the generation the Avastar belongs to * @param _traitHash the Avastar's trait hash * @return metdata the JSON trait metadata for the Avastar */ function assembleTraitMetadata(Generation _generation, uint256 _traitHash) internal view returns (string memory metadata) { require(_traitHash > 0); uint256 slotConst = 256; uint256 slotMask = 255; uint256 bitMask; uint256 slottedValue; uint256 slotMultiplier; uint256 variation; uint256 traitId; // Iterate trait hash by Gene and assemble trait attribute data for (uint8 slot = 0; slot <= uint8(Gene.HAIR_STYLE); slot++){ slotMultiplier = uint256(slotConst**slot); // Create slot multiplier bitMask = slotMask * slotMultiplier; // Create bit mask for slot slottedValue = _traitHash & bitMask; // Extract slotted value from hash if (slottedValue > 0) { variation = (slot > 0) // Extract variation from slotted value ? slottedValue / slotMultiplier : slottedValue; if (variation > 0) { traitId = teleporterContract.getTraitIdByGenerationGeneAndVariation(_generation, Gene(slot), uint8(variation)); metadata = strConcat(metadata, ' {\n'); metadata = strConcat(metadata, ' "trait_type": "'); if (slot == uint8(Gene.SKIN_TONE)) { metadata = strConcat(metadata, 'skin_tone'); } else if (slot == uint8(Gene.HAIR_COLOR)) { metadata = strConcat(metadata, 'hair_color'); } else if (slot == uint8(Gene.EYE_COLOR)) { metadata = strConcat(metadata, 'eye_color'); } else if (slot == uint8(Gene.BG_COLOR)) { metadata = strConcat(metadata, 'background_color'); } else if (slot == uint8(Gene.BACKDROP)) { metadata = strConcat(metadata, 'backdrop'); } else if (slot == uint8(Gene.EARS)) { metadata = strConcat(metadata, 'ears'); } else if (slot == uint8(Gene.FACE)) { metadata = strConcat(metadata, 'face'); } else if (slot == uint8(Gene.NOSE)) { metadata = strConcat(metadata, 'nose'); } else if (slot == uint8(Gene.MOUTH)) { metadata = strConcat(metadata, 'mouth'); } else if (slot == uint8(Gene.FACIAL_FEATURE)) { metadata = strConcat(metadata, 'facial_feature'); } else if (slot == uint8(Gene.EYES)) { metadata = strConcat(metadata, 'eyes'); } else if (slot == uint8(Gene.HAIR_STYLE)) { metadata = strConcat(metadata, 'hair_style'); } metadata = strConcat(metadata, '",\n'); metadata = strConcat(metadata, ' "value": "'); metadata = strConcat(metadata, teleporterContract.getTraitNameById(traitId)); metadata = strConcat(metadata, '"\n }'); if (slot < uint8(Gene.HAIR_STYLE)) metadata = strConcat(metadata, ','); metadata = strConcat(metadata, '\n'); } } } } }
* @notice Set the base URI for the image of each Avastar. Only invokable by system admin role, when contract is paused and not upgraded. If successful, emits an `MediaUriBaseSet` event. @param _mediaUriBase base for the mediaURI shown in metadata for each Avastar/ Set the base for metadata tokenURI Emit the event
function setMediaUriBase(string calldata _mediaUriBase) external onlySysAdmin whenPaused whenNotUpgraded { mediaUriBase = _mediaUriBase; emit MediaUriBaseSet(_mediaUriBase); }
5,450,082
[ 1, 694, 326, 1026, 3699, 364, 326, 1316, 434, 1517, 8789, 689, 297, 18, 5098, 5770, 429, 635, 2619, 3981, 2478, 16, 1347, 6835, 353, 17781, 471, 486, 31049, 18, 971, 6873, 16, 24169, 392, 1375, 5419, 3006, 2171, 694, 68, 871, 18, 225, 389, 5829, 3006, 2171, 1026, 364, 326, 3539, 3098, 12188, 316, 1982, 364, 1517, 8789, 689, 297, 19, 1000, 326, 1026, 364, 1982, 1147, 3098, 16008, 326, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 5419, 3006, 2171, 12, 1080, 745, 892, 389, 5829, 3006, 2171, 13, 203, 565, 3903, 1338, 12712, 4446, 1347, 28590, 1347, 1248, 1211, 19305, 203, 565, 288, 203, 3639, 3539, 3006, 2171, 273, 389, 5829, 3006, 2171, 31, 203, 203, 3639, 3626, 6128, 3006, 2171, 694, 24899, 5829, 3006, 2171, 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 ]
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/NoteInterest.sol
set by admin, default 1
uint public adjusterCoefficient;
2,594,701
[ 1, 542, 635, 3981, 16, 805, 404, 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, 1071, 8307, 1722, 4249, 25403, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IGocEvents.sol"; import "./ERC1155.sol"; import "./Game.sol"; contract Goc is Game, ERC1155, IGocEvents { // move markets mapping(uint256 => address) public marketCreators; mapping(uint256 => OutcomeReserves) public outcomeReserves; mapping(uint256 => mapping(address => uint256)) public betAmounts; uint256 public cReserves; // make moves mapping(uint256 => bool) public chosenMoveValues; mapping(uint16 => uint) public gamesLastMoveTimestamp; address public manager; address immutable public cToken; constructor(address _cToken) { manager = msg.sender; cToken = _cToken; } function getOutcomeReservesTokenIds(uint256 _moveValue) public pure returns (uint oToken0Id, uint oToken1Id){ oToken0Id = uint(keccak256(abi.encode(_moveValue, 0))); oToken1Id = uint(keccak256(abi.encode(_moveValue, 1))); } function getMarketId(uint56 _moveValue) public pure returns (bytes32){ return keccak256(abi.encode(_moveValue)); } function createAndFundMarket(uint256 _moveValue, address _creator) external { // check game is in valid state uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); GameState memory _gameState = gamesState[_gameId]; require(_gameState.state == 1, "Invalid move"); { // decode move MoveMetadata memory _moveMetadata = GameHelpers.decodeMoveMetadataFromMoveValue(_moveValue, _gameState.bitboards); // check move validity against current game state require(GameHelpers.isMoveValid(_gameState, _moveMetadata), "Invalid move"); } // check whether move already exists require(marketCreators[_moveValue] == address(0), "Market exists!"); // fundingAmount address _cToken = cToken; uint256 _cReserves = cReserves; uint fundingAmount = IERC20(_cToken).balanceOf(address(this)) - _cReserves; cReserves = _cReserves + fundingAmount; // set outcome reserves (uint oToken0Id, uint oToken1Id) = getOutcomeReservesTokenIds(_moveValue); _mint(address(this), oToken0Id, fundingAmount, ''); _mint(address(this), oToken1Id, fundingAmount, ''); OutcomeReserves memory _outcomeReserves; _outcomeReserves.reserve0 = fundingAmount; _outcomeReserves.reserve1 = fundingAmount; outcomeReserves[_moveValue] = _outcomeReserves; // set market creator marketCreators[_moveValue] = _creator; require(fundingAmount > 0, "Funding: 0"); emit MarketCreated(_moveValue, _creator); } function buy(uint amount0, uint amount1, address to, uint256 _moveValue) external { // market exists require(marketCreators[_moveValue] != address(0), "Market Invalid"); // market should not have expired { uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); uint16 _moveCount = GameHelpers.decodeMoveCountFromMoveValue(_moveValue); GameState memory _gameState = gamesState[_gameId]; require(_gameState.moveCount + 1 == _moveCount, "Market expired"); } // amountIn address _cToken = cToken; uint256 _cReserves = cReserves; uint amountIn = IERC20(_cToken).balanceOf(address(this)) - _cReserves; cReserves = _cReserves + amountIn; // update bet amount for moveValue betAmounts[_moveValue][to] += amountIn; (uint oToken0Id, uint oToken1Id) = getOutcomeReservesTokenIds(_moveValue); OutcomeReserves memory _outcomeReserves = outcomeReserves[_moveValue]; // mint outcome tokens _mint(address(this), oToken0Id, amountIn, ''); _mint(address(this), oToken1Id, amountIn, ''); // optimistically transfer amount0 & amount1 _transfer(address(this), to, oToken0Id, amount0); _transfer(address(this), to, oToken1Id, amount1); // check invariance uint nReserve0 = _outcomeReserves.reserve0 + amountIn - amount0; uint nReserve1 = _outcomeReserves.reserve1 + amountIn - amount1; require((nReserve0*nReserve1) >= (_outcomeReserves.reserve0*_outcomeReserves.reserve1), "ERR: INV"); // update reserves _outcomeReserves.reserve0 = nReserve0; _outcomeReserves.reserve1 = nReserve1; outcomeReserves[_moveValue] = _outcomeReserves; emit OutcomeBought(_moveValue, to, amountIn, amount0, amount1); } function sell(uint amountOut, address to, uint256 _moveValue) external { // market exists require(marketCreators[_moveValue] != address(0), "Market Invalid"); // market should not have expired { uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); uint16 _moveCount = GameHelpers.decodeMoveCountFromMoveValue(_moveValue); GameState memory _gameState = gamesState[_gameId]; require(_gameState.moveCount + 1 == _moveCount, "Market expired"); } // optimistically transfer amountOut address _cToken = cToken; IERC20(_cToken).transfer(to, amountOut); cReserves -= amountOut; // amount0In and amount1In OutcomeReserves memory _outcomeReserves = outcomeReserves[_moveValue]; (uint oToken0Id, uint oToken1Id) = getOutcomeReservesTokenIds(_moveValue); uint amount0In = balanceOf(address(this), oToken0Id) - _outcomeReserves.reserve0; uint amount1In = balanceOf(address(this), oToken1Id) - _outcomeReserves.reserve1; // burn outcome tokens equivalent to amount out _burn(address(this), oToken0Id, amountOut); _burn(address(this), oToken1Id, amountOut); // check invariance uint nReserve0 = _outcomeReserves.reserve0 + amount0In - amountOut; uint nReserve1 = _outcomeReserves.reserve1 + amount1In - amountOut; require((nReserve0 * nReserve1) >= (_outcomeReserves.reserve0 * _outcomeReserves.reserve1), "ERR: INV"); // update reserves _outcomeReserves.reserve0 = nReserve0; _outcomeReserves.reserve1 = nReserve1; outcomeReserves[_moveValue] = _outcomeReserves; emit OutcomeSold(_moveValue, to, amountOut, amount0In, amount1In); } function redeemWins(uint256 _moveValue, address to) external { require(marketCreators[_moveValue] != address(0), "Market invalid"); uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); GameState memory _gameState = gamesState[_gameId]; bool isChosenMove = chosenMoveValues[_moveValue]; require(_gameState.state == 2 && isChosenMove == true, "Invalid State"); // amount0In and amount1In OutcomeReserves memory _outcomeReserves = outcomeReserves[_moveValue]; (uint oToken0Id, uint oToken1Id) = getOutcomeReservesTokenIds(_moveValue); uint amount0In = balanceOf(address(this), oToken0Id) - _outcomeReserves.reserve0; uint amount1In = balanceOf(address(this), oToken1Id) - _outcomeReserves.reserve1; // burn received tokens _burn(address(this), oToken0Id, amount0In); _burn(address(this), oToken1Id, amount1In); // win amount uint winAmount; uint side = _moveValue >> 17 & 1; if (_gameState.winner == 0 && side == 0){ winAmount = amount0In; }else if (_gameState.winner == 1 && side == 1){ winAmount = amount1In; }else if (_gameState.winner == 2){ winAmount = amount0In/2 + amount1In/2; } // transfer win amount and update cReservers IERC20(cToken).transfer(to, winAmount); cReserves -= winAmount; emit WinningRedeemed(_moveValue, to); } function redeemBetAmount(uint256 _moveValue, address _of) external { require(marketCreators[_moveValue] != address(0), "Market invalid"); GameState memory _gameState = gamesState[GameHelpers.decodeGameIdFromMoveValue(_moveValue)]; require( (_gameState.moveCount + 1 > GameHelpers.decodeMoveCountFromMoveValue(_moveValue) || _gameState.state == 2) && chosenMoveValues[_moveValue] == false ); uint256 betAmount = betAmounts[_moveValue][_of]; IERC20(cToken).transfer(_of, betAmount); cReserves -= betAmount; emit BetRedeemed(_moveValue, _of); } // manager functions // TODO look for an efficient way for storing sorted list of // YES probabilty of every market for each moveCount. // Rn, the manager is trusted with calling makeMove // with the moveValue (i.e. marketId) that has highest YES // probability among the rest of the markets for the same // move count. This isn't ideal,, since a single mistake // by manager would destroy the enitre purpose of this // contract. function makeMove(uint256 _moveValue) external { require(manager == msg.sender, "Auth ERR"); require(marketCreators[_moveValue] != address(0), "Invalid Market"); // Time elapsed since last move should be atleast 24 hours uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); uint lastMoveTimestamp = gamesLastMoveTimestamp[_gameId]; // TODO switch time diffrence back to 24 hrs from 60 seconds require(block.timestamp - lastMoveTimestamp > 60, "Time Err"); // apply move to the game state applyMove(_moveValue); // update timestamp gamesLastMoveTimestamp[_gameId] = block.timestamp; // set _moveValue as chosen move chosenMoveValues[_moveValue] = true; emit MoveMade(_moveValue); } function oddCaseDeclareOutcome(uint256 outcome, uint256 _moveValue) external { require(msg.sender == manager, "Auth ERR"); _oddCaseDeclareOutcome(outcome, _moveValue); } function newGame() external { require(msg.sender == manager, "Auth ERR"); uint16 gameIndex = _newGame(); // set timestamp for first move gamesLastMoveTimestamp[gameIndex] = block.timestamp; emit GameCreated(gameIndex); } function updateManager(address to) external { require(msg.sender == manager, "Auth ERR"); manager = to; } } /** Just thinking - 1. Should I add NFT per winning move? just to motivate people to elect new moves? */ /** 1. Parse FEN and game & check game transition 2. Work on NFT */
check game is in valid state decode move check move validity against current game state
function createAndFundMarket(uint256 _moveValue, address _creator) external { uint16 _gameId = GameHelpers.decodeGameIdFromMoveValue(_moveValue); GameState memory _gameState = gamesState[_gameId]; require(_gameState.state == 1, "Invalid move"); { MoveMetadata memory _moveMetadata = GameHelpers.decodeMoveMetadataFromMoveValue(_moveValue, _gameState.bitboards); require(GameHelpers.isMoveValid(_gameState, _moveMetadata), "Invalid move"); } uint256 _cReserves = cReserves; uint fundingAmount = IERC20(_cToken).balanceOf(address(this)) - _cReserves; cReserves = _cReserves + fundingAmount; _mint(address(this), oToken0Id, fundingAmount, ''); _mint(address(this), oToken1Id, fundingAmount, ''); OutcomeReserves memory _outcomeReserves; _outcomeReserves.reserve0 = fundingAmount; _outcomeReserves.reserve1 = fundingAmount; outcomeReserves[_moveValue] = _outcomeReserves; require(fundingAmount > 0, "Funding: 0"); emit MarketCreated(_moveValue, _creator); }
1,795,359
[ 1, 1893, 7920, 353, 316, 923, 919, 2495, 3635, 866, 3635, 13800, 5314, 783, 7920, 919, 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, 445, 30545, 42, 1074, 3882, 278, 12, 11890, 5034, 389, 8501, 620, 16, 1758, 389, 20394, 13, 3903, 288, 203, 3639, 2254, 2313, 389, 13957, 548, 273, 14121, 13375, 18, 3922, 12496, 548, 1265, 7607, 620, 24899, 8501, 620, 1769, 203, 3639, 14121, 1119, 3778, 389, 13957, 1119, 273, 28422, 1119, 63, 67, 13957, 548, 15533, 203, 3639, 2583, 24899, 13957, 1119, 18, 2019, 422, 404, 16, 315, 1941, 3635, 8863, 203, 203, 3639, 288, 203, 5411, 9933, 2277, 3778, 389, 8501, 2277, 273, 14121, 13375, 18, 3922, 7607, 2277, 1265, 7607, 620, 24899, 8501, 620, 16, 389, 13957, 1119, 18, 3682, 3752, 87, 1769, 203, 5411, 2583, 12, 12496, 13375, 18, 291, 7607, 1556, 24899, 13957, 1119, 16, 389, 8501, 2277, 3631, 315, 1941, 3635, 8863, 203, 3639, 289, 203, 203, 203, 3639, 2254, 5034, 389, 71, 607, 264, 3324, 273, 276, 607, 264, 3324, 31, 203, 3639, 2254, 22058, 6275, 273, 467, 654, 39, 3462, 24899, 71, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 300, 389, 71, 607, 264, 3324, 31, 203, 3639, 276, 607, 264, 3324, 273, 389, 71, 607, 264, 3324, 397, 22058, 6275, 31, 203, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 320, 1345, 20, 548, 16, 22058, 6275, 16, 23489, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 320, 1345, 21, 548, 16, 22058, 6275, 16, 23489, 203, 3639, 2976, 5624, 607, 264, 3324, 3778, 389, 21672, 607, 264, 3324, 31, 203, 3639, 389, 21672, 607, 264, 3324, 18, 455, 2 ]
/** *Submitted for verification at Etherscan.io on 2017-12-31 */ pragma solidity ^0.4.18; // ----------------------------------------------------------------------------------------------- // CryptoCatsMarket v3 // // Ethereum contract for Cryptocats (cryptocats.thetwentysix.io), // a digital asset marketplace DAPP for unique 8-bit cats on the Ethereum blockchain. // // Versions: // 3.0 - Bug fix to make ETH value sent in with getCat function withdrawable by contract owner. // Special thanks to BokkyPooBah (https://github.com/bokkypoobah) who found this issue! // 2.0 - Remove claimCat function with getCat function that is payable and accepts incoming ETH. // Feature added to set ETH pricing by each cat release and also for specific cats // 1.0 - Feature added to create new cat releases, add attributes and offer to sell/buy cats // 0.0 - Initial contract to support ownership of 12 unique 8-bit cats on the Ethereum blockchain // // Original contract code based off Cryptopunks DAPP by the talented people from Larvalabs // (https://github.com/larvalabs/cryptopunks) // // (c) Nas Munawar / Gendry Morales / Jochy Reyes / TheTwentySix. 2017. The MIT Licence. // ---------------------------------------------------------------------------------------------- contract CryptoCatsMarket { /* modifier to add to function that should only be callable by contract owner */ modifier onlyBy(address _account) { require(msg.sender == _account); _; } /* You can use this hash to verify the image file containing all cats */ string public imageHash = "3b82cfd5fb39faff3c2c9241ca5a24439f11bdeaa7d6c0771eb782ea7c963917"; /* Variables to store contract owner and contract token standard details */ address owner; string public standard = 'CryptoCats'; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; // Store reference to previous cryptocat contract containing alpha release owners // PROD - previous contract address address public previousContractAddress = 0x9508008227b6b3391959334604677d60169EF540; // ROPSTEN - previous contract address // address public previousContractAddress = 0xccEC9B9cB223854C46843A1990c36C4A37D80E2e; uint8 public contractVersion; bool public totalSupplyIsLocked; bool public allCatsAssigned = false; // boolean flag to indicate if all available cats are claimed uint public catsRemainingToAssign = 0; // variable to track cats remaining to be assigned/claimed uint public currentReleaseCeiling; // variable to track maximum cat index for latest release /* Create array to store cat index to owner address */ mapping (uint => address) public catIndexToAddress; /* Create array to store cat release id to price in wei for all cats in that release */ mapping (uint32 => uint) public catReleaseToPrice; /* Create array to store cat index to any exception price deviating from release price */ mapping (uint => uint) public catIndexToPriceException; /* Create an array with all balances */ mapping (address => uint) public balanceOf; /* Store type descriptor string for each attribute number */ mapping (uint => string) public attributeType; /* Store up to 6 cat attribute strings where attribute types are defined in attributeType */ mapping (uint => string[6]) public catAttributes; /* Struct that is used to describe seller offer details */ struct Offer { bool isForSale; // flag identifying if cat is for sale uint catIndex; address seller; // owner address uint minPrice; // price in ETH owner is willing to sell cat for address sellOnlyTo; // address identifying only buyer that seller is wanting to offer cat to } uint[] public releaseCatIndexUpperBound; // Store sale Offer details for each cat made for sale by its owner mapping (uint => Offer) public catsForSale; // Store pending withdrawal amounts in ETH that a failed bidder or successful seller is able to withdraw mapping (address => uint) public pendingWithdrawals; /* Define event types to publish transaction details related to transfer and buy/sell activities */ event CatTransfer(address indexed from, address indexed to, uint catIndex); event CatOffered(uint indexed catIndex, uint minPrice, address indexed toAddress); event CatBought(uint indexed catIndex, uint price, address indexed fromAddress, address indexed toAddress); event CatNoLongerForSale(uint indexed catIndex); /* Define event types used to publish to EVM log when cat assignment/claim and cat transfer occurs */ event Assign(address indexed to, uint256 catIndex); event Transfer(address indexed from, address indexed to, uint256 value); /* Define event for reporting new cats release transaction details into EVM log */ event ReleaseUpdate(uint256 indexed newCatsAdded, uint256 totalSupply, uint256 catPrice, string newImageHash); /* Define event for logging update to cat price for existing release of cats (only impacts unclaimed cats) */ event UpdateReleasePrice(uint32 releaseId, uint256 catPrice); /* Define event for logging transactions that change any cat attributes into EVM log*/ event UpdateAttribute(uint indexed attributeNumber, address indexed ownerAddress, bytes32 oldValue, bytes32 newValue); /* Initializes contract with initial supply tokens to the creator of the contract */ function CryptoCatsMarket() payable { owner = msg.sender; // Set contract creation sender as owner _totalSupply = 625; // Set total supply catsRemainingToAssign = _totalSupply; // Initialise cats remaining to total supply amount name = "CRYPTOCATS"; // Set the name for display purposes symbol = "CCAT"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes contractVersion = 3; currentReleaseCeiling = 625; totalSupplyIsLocked = false; releaseCatIndexUpperBound.push(12); // Register release 0 getting to 12 cats releaseCatIndexUpperBound.push(189); // Register release 1 getting to 189 cats releaseCatIndexUpperBound.push(_totalSupply); // Register release 2 getting to 625 cats catReleaseToPrice[0] = 0; // Set price for release 0 catReleaseToPrice[1] = 0; // Set price for release 1 catReleaseToPrice[2] = 80000000000000000; // Set price for release 2 to Wei equivalent of 0.08 ETH } /* Admin function to make total supply permanently locked (callable by owner only) */ function lockTotalSupply() onlyBy(owner) { totalSupplyIsLocked = true; } /* Admin function to set attribute type descriptor text (callable by owner only) */ function setAttributeType(uint attributeIndex, string descriptionText) onlyBy(owner) { require(attributeIndex >= 0 && attributeIndex < 6); attributeType[attributeIndex] = descriptionText; } /* Admin function to release new cat index numbers and update image hash for new cat releases */ function releaseCats(uint32 _releaseId, uint numberOfCatsAdded, uint256 catPrice, string newImageHash) onlyBy(owner) returns (uint256 newTotalSupply) { require(!totalSupplyIsLocked); // Check that new cat releases still available require(numberOfCatsAdded > 0); // Require release to have more than 0 cats currentReleaseCeiling = currentReleaseCeiling + numberOfCatsAdded; // Add new cats to release ceiling uint _previousSupply = _totalSupply; _totalSupply = _totalSupply + numberOfCatsAdded; catsRemainingToAssign = catsRemainingToAssign + numberOfCatsAdded; // Update cats remaining to assign count imageHash = newImageHash; // Update image hash catReleaseToPrice[_releaseId] = catPrice; // Update price for new release of cats releaseCatIndexUpperBound.push(_totalSupply); // Track upper bound of cat index for this release ReleaseUpdate(numberOfCatsAdded, _totalSupply, catPrice, newImageHash); // Send EVM event containing details of release return _totalSupply; // Return new total supply of cats } /* Admin function to update price for an entire release of cats still available for claiming */ function updateCatReleasePrice(uint32 _releaseId, uint256 catPrice) onlyBy(owner) { require(_releaseId <= releaseCatIndexUpperBound.length); // Check that release is id valid catReleaseToPrice[_releaseId] = catPrice; // Update price for cat release UpdateReleasePrice(_releaseId, catPrice); // Send EVM event with release id and price details } /* Migrate details of previous contract cat owners addresses and cat balances to new contract instance */ function migrateCatOwnersFromPreviousContract(uint startIndex, uint endIndex) onlyBy(owner) { PreviousCryptoCatsContract previousCatContract = PreviousCryptoCatsContract(previousContractAddress); for (uint256 catIndex = startIndex; catIndex <= endIndex; catIndex++) { // Loop through cat index based on start/end index address catOwner = previousCatContract.catIndexToAddress(catIndex); // Retrieve owner address from previous contract if (catOwner != 0x0) { // Check that cat index has an owner address and is not unclaimed catIndexToAddress[catIndex] = catOwner; // Update owner address in current contract uint256 ownerBalance = previousCatContract.balanceOf(catOwner); balanceOf[catOwner] = ownerBalance; // Update owner cat balance } } catsRemainingToAssign = previousCatContract.catsRemainingToAssign(); // Update count of total cats remaining to assign from prev contract } /* Add value for cat attribute that has been defined (only for cat owner) */ function setCatAttributeValue(uint catIndex, uint attrIndex, string attrValue) { require(catIndex < _totalSupply); // cat index requested should not exceed total supply require(catIndexToAddress[catIndex] == msg.sender); // require sender to be cat owner require(attrIndex >= 0 && attrIndex < 6); // require that attribute index is 0 - 5 bytes memory tempAttributeTypeText = bytes(attributeType[attrIndex]); require(tempAttributeTypeText.length != 0); // require that attribute being stored is not empty catAttributes[catIndex][attrIndex] = attrValue; // store attribute value string in contract based on cat index } /* Transfer cat by owner to another wallet address Different usage in Cryptocats than in normal token transfers This will transfer an owner's cat to another wallet's address Cat is identified by cat index passed in as _value */ function transfer(address _to, uint256 _value) returns (bool success) { if (_value < _totalSupply && // ensure cat index is valid catIndexToAddress[_value] == msg.sender && // ensure sender is owner of cat balanceOf[msg.sender] > 0) { // ensure sender balance of cat exists balanceOf[msg.sender]--; // update (reduce) cat balance from owner catIndexToAddress[_value] = _to; // set new owner of cat in cat index balanceOf[_to]++; // update (include) cat balance for recepient Transfer(msg.sender, _to, _value); // trigger event with transfer details to EVM success = true; // set success as true after transfer completed } else { success = false; // set success as false if conditions not met } return success; // return success status } /* Returns count of how many cats are owned by an owner */ function balanceOf(address _owner) constant returns (uint256 balance) { require(balanceOf[_owner] != 0); // requires that cat owner balance is not 0 return balanceOf[_owner]; // return number of cats owned from array of balances by owner address } /* Return total supply of cats existing */ function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } /* Claim cat at specified index if it is unassigned - Deprecated as replaced with getCat function in v2.0 */ // function claimCat(uint catIndex) { // require(!allCatsAssigned); // require all cats have not been assigned/claimed // require(catsRemainingToAssign != 0); // require cats remaining to be assigned count is not 0 // require(catIndexToAddress[catIndex] == 0x0); // require owner address for requested cat index is empty // require(catIndex < _totalSupply); // require cat index requested does not exceed total supply // require(catIndex < currentReleaseCeiling); // require cat index to not be above current ceiling of released cats // catIndexToAddress[catIndex] = msg.sender; // Assign sender's address as owner of cat // balanceOf[msg.sender]++; // Increase sender's balance holder // catsRemainingToAssign--; // Decrease cats remaining count // Assign(msg.sender, catIndex); // Triggers address assignment event to EVM's // // log to allow javascript callbacks // } /* Return the release index for a cat based on the cat index */ function getCatRelease(uint catIndex) returns (uint32) { for (uint32 i = 0; i < releaseCatIndexUpperBound.length; i++) { // loop through release index record array if (releaseCatIndexUpperBound[i] > catIndex) { // check if highest cat index for release is higher than submitted cat index return i; // return release id } } } /* Gets cat price for a particular cat index */ function getCatPrice(uint catIndex) returns (uint catPrice) { require(catIndex < _totalSupply); // Require that cat index is valid if(catIndexToPriceException[catIndex] != 0) { // Check if there is any exception pricing return catIndexToPriceException[catIndex]; // Return price if there is overriding exception pricing } uint32 releaseId = getCatRelease(catIndex); return catReleaseToPrice[releaseId]; // Return cat price based on release pricing if no exception pricing } /* Sets exception price in Wei that differs from release price for single cat based on cat index */ function setCatPrice(uint catIndex, uint catPrice) onlyBy(owner) { require(catIndex < _totalSupply); // Require that cat index is valid require(catPrice > 0); // Check that cat price is not 0 catIndexToPriceException[catIndex] = catPrice; // Create cat price record in exception pricing array for this cat index } /* Get cat with no owner at specified index by paying price */ function getCat(uint catIndex) payable { require(!allCatsAssigned); // require all cats have not been assigned/claimed require(catsRemainingToAssign != 0); // require cats remaining to be assigned count is not 0 require(catIndexToAddress[catIndex] == 0x0); // require owner address for requested cat index is empty require(catIndex < _totalSupply); // require cat index requested does not exceed total supply require(catIndex < currentReleaseCeiling); // require cat index to not be above current ceiling of released cats require(getCatPrice(catIndex) <= msg.value); // require ETH amount sent with tx is sufficient for cat price catIndexToAddress[catIndex] = msg.sender; // Assign sender's address as owner of cat balanceOf[msg.sender]++; // Increase sender's balance holder catsRemainingToAssign--; // Decrease cats remaining count pendingWithdrawals[owner] += msg.value; // Add paid amount to pending withdrawals for contract owner (bugfix in v3.0) Assign(msg.sender, catIndex); // Triggers address assignment event to EVM's // log to allow javascript callbacks } /* Get address of owner based on cat index */ function getCatOwner(uint256 catIndex) public returns (address) { require(catIndexToAddress[catIndex] != 0x0); return catIndexToAddress[catIndex]; // Return address at array position of cat index } /* Get address of contract owner who performed contract creation and initialisation */ function getContractOwner() public returns (address) { return owner; // Return address of contract owner } /* Indicate that cat is no longer for sale (by cat owner only) */ function catNoLongerForSale(uint catIndex) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(false, catIndex, msg.sender, 0, 0x0); // Switch cat for sale flag to false and reset all other values CatNoLongerForSale(catIndex); // Create EVM event logging that cat is no longer for sale } /* Create sell offer for cat with a certain minimum sale price in wei (by cat owner only) */ function offerCatForSale(uint catIndex, uint minSalePriceInWei) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, 0x0); // Set cat for sale flag to true and update with price details CatOffered(catIndex, minSalePriceInWei, 0x0); // Create EVM event to log details of cat sale } /* Create sell offer for cat only to a particular buyer address with certain minimum sale price in wei (by cat owner only) */ function offerCatForSaleToAddress(uint catIndex, uint minSalePriceInWei, address toAddress) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, toAddress); // Set cat for sale flag to true and update with price details and only sell to address CatOffered(catIndex, minSalePriceInWei, toAddress); // Create EVM event to log details of cat sale } /* Buy cat that is currently on offer */ function buyCat(uint catIndex) payable { require (catIndex < _totalSupply); // require that cat index is valid and less than total cat index Offer offer = catsForSale[catIndex]; require (offer.isForSale); // require that cat is marked for sale // require buyer to have required address if indicated in offer require (msg.value >= offer.minPrice); // require buyer sent enough ETH require (offer.seller == catIndexToAddress[catIndex]); // require seller must still be owner of cat if (offer.sellOnlyTo != 0x0) { // if cat offer sell only to address is not blank require (offer.sellOnlyTo == msg.sender); // require that buyer is allowed to buy offer } address seller = offer.seller; catIndexToAddress[catIndex] = msg.sender; // update cat owner address to buyer's address balanceOf[seller]--; // reduce cat balance of seller balanceOf[msg.sender]++; // increase cat balance of buyer Transfer(seller, msg.sender, 1); // create EVM event logging transfer of 1 cat from seller to owner CatNoLongerForSale(catIndex); // create EVM event logging cat is no longer for sale pendingWithdrawals[seller] += msg.value; // increase pending withdrawal amount of seller based on amount sent in buyer's message CatBought(catIndex, msg.value, seller, msg.sender); // create EVM event logging details of cat purchase } /* Withdraw any pending ETH amount that is owed to failed bidder or successful seller */ function withdraw() { uint amount = pendingWithdrawals[msg.sender]; // store amount that can be withdrawn by sender pendingWithdrawals[msg.sender] = 0; // zero pending withdrawal amount msg.sender.transfer(amount); // before performing transfer to message sender } } contract PreviousCryptoCatsContract { /* You can use this hash to verify the image file containing all cats */ string public imageHash = "e055fe5eb1d95ea4e42b24d1038db13c24667c494ce721375bdd827d34c59059"; /* Variables to store contract owner and contract token standard details */ address owner; string public standard = 'CryptoCats'; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; // Store reference to previous cryptocat contract containing alpha release owners // PROD address public previousContractAddress = 0xa185B9E63FB83A5a1A13A4460B8E8605672b6020; // ROPSTEN // address public previousContractAddress = 0x0b0DB7bd68F944C219566E54e84483b6c512737B; uint8 public contractVersion; bool public totalSupplyIsLocked; bool public allCatsAssigned = false; // boolean flag to indicate if all available cats are claimed uint public catsRemainingToAssign = 0; // variable to track cats remaining to be assigned/claimed uint public currentReleaseCeiling; // variable to track maximum cat index for latest release /* Create array to store cat index to owner address */ mapping (uint => address) public catIndexToAddress; /* Create an array with all balances */ mapping (address => uint) public balanceOf; /* Initializes contract with initial supply tokens to the creator of the contract */ function PreviousCryptoCatsContract() payable { owner = msg.sender; // Set contract creation sender as owner } /* Returns count of how many cats are owned by an owner */ function balanceOf(address _owner) constant returns (uint256 balance) { require(balanceOf[_owner] != 0); // requires that cat owner balance is not 0 return balanceOf[_owner]; // return number of cats owned from array of balances by owner address } /* Return total supply of cats existing */ function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } /* Get address of owner based on cat index */ function getCatOwner(uint256 catIndex) public returns (address) { require(catIndexToAddress[catIndex] != 0x0); return catIndexToAddress[catIndex]; // Return address at array position of cat index } /* Get address of contract owner who performed contract creation and initialisation */ function getContractOwner() public returns (address) { return owner; // Return address of contract owner } }
Migrate details of previous contract cat owners addresses and cat balances to new contract instance */
function migrateCatOwnersFromPreviousContract(uint startIndex, uint endIndex) onlyBy(owner) { PreviousCryptoCatsContract previousCatContract = PreviousCryptoCatsContract(previousContractAddress); uint256 ownerBalance = previousCatContract.balanceOf(catOwner); }
12,754,691
[ 1, 19594, 3189, 434, 2416, 6835, 6573, 25937, 6138, 471, 6573, 324, 26488, 358, 394, 6835, 791, 342, 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, 13187, 11554, 5460, 414, 1265, 8351, 8924, 12, 11890, 10588, 16, 2254, 13818, 13, 203, 3639, 1338, 858, 12, 8443, 13, 203, 565, 288, 203, 3639, 19369, 18048, 39, 2323, 8924, 2416, 11554, 8924, 273, 19369, 18048, 39, 2323, 8924, 12, 11515, 8924, 1887, 1769, 203, 203, 7734, 2254, 5034, 3410, 13937, 273, 2416, 11554, 8924, 18, 12296, 951, 12, 2574, 5541, 1769, 203, 5411, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; contract CryptoSpaceForceCard is ERC721, Ownable, ERC721Enumerable, ERC721Pausable, AccessControlEnumerable { using Counters for Counters.Counter; string dynamicBaseURI; mapping(uint256 => Card) public cards; mapping(address => uint256[]) private _ownedTokens; struct Card { string cardId; string uri; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); Counters.Counter private _tokenIds; mapping (uint256 => string) private _tokenURIs; event LockCard(address indexed holder, string cardId, string steemAddr, uint256 indexed _TokenId); event MintCard(address indexed holder, string cardId, uint256 indexed tokenId); /** * @dev Make sure to pass trailing seperator on url * - Ex: https://gateway.pinata.cloud/ipfs/ */ constructor(string memory _baseTokenURI) ERC721("Crypto Space Force", "CSFCARD") { dynamicBaseURI = _baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function baseTokenURI() public view returns (string memory) { return dynamicBaseURI; } function setDynamicBaseURI(string memory _newBaseURI) public onlyOwner { dynamicBaseURI = _newBaseURI; } function cardIdForTokenId(uint256 _tokenId) public view returns (string memory) { return cards[_tokenId].cardId; } function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(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[] memory) { uint256 length = ERC721.balanceOf(owner); require(length > 0, "ERC721TokensOfOwner: caller balance is zero"); uint256[] memory _tokens = new uint256[](length); for (uint256 i = 0; i < length; i++) { _tokens[i] = _ownedTokens[owner][i]; } return _tokens; } function tokensOfHolder(address holder) public view returns (uint256[] memory) { return _tokensOfOwner(holder); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { return strConcat( baseTokenURI(), cards[_tokenId].cardId ); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() internal view returns (uint256) { return _tokenIds.current() + 1; } /** * @return unint256 of the token ID */ function mint(address recipient) private returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(recipient, newItemId); return newItemId; } /** * @dev instead of the standard mint we use mint Card * * Requirements: * - Must supply the Card Id and URI tag to append to baseTokenURI */ function mintCard(address _recipient, string memory _cardId, string memory _uriId) public returns (uint256) { require(!paused(), "ERC721Pausable: no token minting while paused"); require(hasRole(MINTER_ROLE, _msgSender()), "ERC721: minter only"); uint256 newTokenId = _getNextTokenId(); cards[newTokenId].cardId = _cardId; cards[newTokenId].uri = _uriId; uint256 newItemId = mint(_recipient); require(_getNextTokenId() == newTokenId + 1, "Mint Card: Safety Check"); emit MintCard(_recipient, _cardId, newTokenId); return newItemId; } function lockCard(uint256 _TokenId, string memory _steemAddr) public { require(ownerOf(_TokenId) == _msgSender(), "ERC721LockCard: caller is not the owner"); string memory cardId = cardIdForTokenId(_TokenId); transferFrom(msg.sender, address(this), _TokenId); emit LockCard(msg.sender, cardId, _steemAddr, _TokenId); } function unlockCard(uint256 _TokenId, address _newHolder) public isLockedCard(_TokenId) { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721: minter only"); transferFrom(address(this), _newHolder, _TokenId); } modifier isLockedCard(uint256 _TokenId) { require(ownerOf(_TokenId) == address(this), "ERC721Card: Not Locked"); _; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * Override isApprovedForAll to auto-approve OS's proxy contract * - for OpenSea */ function isApprovedForAll( address _owner, address _operator ) public override view returns (bool isOperator) { // if OpenSea's ERC721 Proxy Address is detected, auto-return true if (_operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) { return true; } // otherwise, use the default ERC721.isApprovedForAll() return ERC721.isApprovedForAll(_owner, _operator); } // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } }
* @return unint256 of the token ID/
function mint(address recipient) private returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(recipient, newItemId); return newItemId; }
15,833,810
[ 1, 2463, 640, 474, 5034, 434, 326, 1147, 1599, 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, 225, 445, 312, 474, 12, 2867, 8027, 13, 3238, 1135, 261, 11890, 5034, 13, 288, 203, 565, 389, 2316, 2673, 18, 15016, 5621, 203, 565, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 565, 389, 81, 474, 12, 20367, 16, 394, 17673, 1769, 203, 565, 327, 394, 17673, 31, 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 ]
pragma solidity 0.4.24; import "./../installed_contracts/ownership/Ownable.sol"; import "./PlayerModel.sol"; import "./GameStages.sol"; contract Game is Ownable, PlayerModel, GameStages { uint private endTime = 0; uint public joinPrice = 0; // events not works on web3 1.0.0 with httpProvider event GetWinner(address winner, uint money); // ----------------------------------------- // modifiers modifier paymentIsValid() { require(msg.value > 0.5 ether); require(msg.value < 50 ether); _; } modifier roundEnded() { require(block.timestamp > endTime); _; } modifier roundStarted() { require(endTime != 0); _; } // ----------------------------------------- // PUBLIC INTERFACE // Accumulate some deposit function() public payable {} // Accumulate deposit from bids function MakeBid(address _address, uint16 _bid) public payable paymentIsValid { if(atStage(Stages.NotStarted)) { _startRound(); } _addPlayer(_address, _bid); } function endGame() public roundEnded returns(uint) { uint fee = _getFee(); uint prize = this.balance - fee; address winner = _getWinnerAddress(); winner.transfer(prize); owner.transfer(this.balance); emit GetWinner(winner, prize); _clearRound(); } // ----------------------------------------- // internal methods function _startRound() internal { joinPrice = msg.value; endTime = block.timestamp + 3 minutes; nextStage(); } function _clearRound() private { backToStartStage(); _clearPlayers(); endTime = 0; joinPrice = 0; } function _getFee() private returns(uint) { // fee is 10% return this.balance / 10; } function _getWinnerPrize(uint _fee) private returns(uint) { return this.balance - _fee; } function _getWinnerAddress() private returns(address) { uint winIndex = 0; for (uint currentIndex = 1; currentIndex < bids.length; currentIndex++) { winIndex = _compareTwoBidsByIndex(winIndex, currentIndex); } return addresses[winIndex]; } function _compareTwoBidsByIndex(uint index1, uint index2) private returns (uint) { // rock - 1 // paper - 2 // scissors - 3 // algorithm - https://gist.github.com/joshfry/7327656 uint16 bid1 = bids[index1]; uint16 bid2 = bids[index2]; if(bid1 == bid2) { // @todo - get random winner return index1; } if(bid1 == 1) { if(bid2 == 3) { return index1; } else { return index2; } } else if(bid1 == 2) { if(bid2 == 1) { return index1; } else { return index2; } } else if(bid1 == 3) { if(bid2 == 1) { return index2; } else { return index1; } } } // --------- // function _generateRandom() private view returns (uint) { // uint rand = uint(keccak256(abi.encodePacked(block.timestamp))); // return rand % 1; // } }
Accumulate deposit from bids
function MakeBid(address _address, uint16 _bid) public payable paymentIsValid { if(atStage(Stages.NotStarted)) { _startRound(); } _addPlayer(_address, _bid); }
12,860,596
[ 1, 8973, 31284, 443, 1724, 628, 30534, 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, 445, 4344, 17763, 12, 2867, 389, 2867, 16, 2254, 2313, 389, 19773, 13, 1071, 8843, 429, 5184, 20536, 288, 203, 3639, 309, 12, 270, 8755, 12, 31359, 18, 1248, 9217, 3719, 288, 203, 5411, 389, 1937, 11066, 5621, 203, 3639, 289, 203, 203, 3639, 389, 1289, 12148, 24899, 2867, 16, 389, 19773, 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 ]
pragma solidity ^0.5.3; pragma experimental ABIEncoderV2; //import { ERC20 } from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import { SafeMath } from "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/math/SafeMath.sol"; import { PrntNFT } from "./PrntNFT.sol"; import { PrntNFTTradable } from "./PrntNFTTradable.sol"; import { PrntNFTMarketplaceEvents } from "./PrntNFTMarketplaceEvents.sol"; import { PrntNFTData } from "./PrntNFTData.sol"; contract PrntNFTMarketplace is PrntNFTTradable, PrntNFTMarketplaceEvents { using SafeMath for uint256; // PrntNFTData.Prnt[] public _prnts; // mapping(address => PrntNFT[]) creations; mapping(address => PrntNFTData.Prnt[]) collections; // mapping(address => mapping(address => bool)) currentCollections; address payable public PRNT_NFT_MARKETPLACE; PrntNFTData public prntNFTData; constructor(PrntNFTData _prntNFTData) public PrntNFTTradable(_prntNFTData) { prntNFTData = _prntNFTData; PRNT_NFT_MARKETPLACE = address(uint160(address(this))); } /** * @notice - Buy function is that buy NFT token and ownership transfer. (Reference from IERC721.sol) * @notice - msg.sender buy NFT with ETH (msg.value) * @notice - PrntID is always 1. Because each prntNFT is unique. */ function buyPrntNFT(PrntNFT prntNFT) public payable returns (bool) { // PrntNFT prntNFT = _prntNFT; PrntNFTData.Prnt memory prnt = prntNFTData.getPrntByNFTAddress(prntNFT); uint len = prnt.ownerAddress.length; address _seller = prnt.ownerAddress[len-1]; /// current owner address payable seller = address(uint160(_seller)); /// Convert owner address with payable uint buyAmount = prnt.prntPrice; require (msg.value >= buyAmount, "msg.value should be equal to the buyAmount"); /// Bought-amount is transferred into a seller wallet seller.transfer(buyAmount); /// Approve a buyer address as a receiver before NFT's transferFrom method is executed address buyer = msg.sender; uint prntId = 1; /// [Note]: PrntID is always 1. Because each prntNFT is unique. prntNFT.approve(buyer, prntId); address ownerBeforeOwnershipTransferred = prntNFT.ownerOf(prntId); /// Transfer Ownership of the PrntNFT from a seller to a buyer transferOwnershipOfPrntNFT(prntNFT, prntId, buyer); prntNFTData.updateOwnerOfPrntNFT(prntNFT, buyer); prntNFTData.updateStatus(prntNFT, "Cancelled"); /// Event for checking result of transferring ownership of a prntNFT address ownerAfterOwnershipTransferred = prntNFT.ownerOf(prntId); PrntNFTData.Prnt memory _prnt = prntNFTData.getPrntByNFTAddress(prntNFT); collections[buyer].push(_prnt); prntNFTData.addArtist(msg.sender); emit PrntNFTOwnershipChanged(prntNFT, prntId, ownerBeforeOwnershipTransferred, ownerAfterOwnershipTransferred); } function getCollections(address owner) public view returns (PrntNFTData.Prnt[] memory) { return collections[owner]; } ///----------------------------------------------------- /// Methods below are pending methods ///----------------------------------------------------- /** * @dev reputation function is that gives reputation to a user who has ownership of being posted prnt. * @dev Each user has reputation data in struct */ function reputation(address from, address to, uint256 prntId) public returns (uint256, uint256) { // Prnt storage prnt = prnts[prntId]; // prnt.reputation = prnt.reputation.add(1); // emit AddReputation(prntId, prnt.reputation); // return (prntId, prnt.reputation); return (0, 0); } function getReputationCount(uint256 prntId) public view returns (uint256) { uint256 curretReputationCount; // Prnt memory prnt = prnts[prntId]; // curretReputationCount = prnt.reputation; return curretReputationCount; } }
Prnt memory prnt = prnts[prntId]; curretReputationCount = prnt.reputation;
function getReputationCount(uint256 prntId) public view returns (uint256) { uint256 curretReputationCount; return curretReputationCount; }
7,276,394
[ 1, 2050, 496, 3778, 846, 496, 273, 846, 27932, 63, 683, 496, 548, 15533, 662, 1349, 426, 458, 367, 1380, 273, 846, 496, 18, 266, 458, 367, 31, 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, 5561, 458, 367, 1380, 12, 11890, 5034, 846, 496, 548, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 662, 1349, 426, 458, 367, 1380, 31, 203, 203, 203, 3639, 327, 662, 1349, 426, 458, 367, 1380, 31, 203, 565, 289, 377, 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/5/0x05300f1444df2b395872B48c91960658a15a5666/sources/contracts/ERC721Escrow.sol
Require item is not still in escrow and caller is the owner of the NFT
function withdraw(uint256 _id) external { require(block.timestamp > erc721Items[_id].expiration, "The item is still in escrow."); require(msg.sender == erc721Items[_id].marketplace, "only marketplace contract can withdraw"); address seller = erc721Items[_id].seller; uint256 item = erc721Items[_id].item; delete(erc721Items[_id]); IERC721(address(token)).transferFrom(address(this), seller, item); emit Withdrawn(_id, seller, address(token), item); }
1,853,160
[ 1, 8115, 761, 353, 486, 4859, 316, 2904, 492, 471, 4894, 353, 326, 3410, 434, 326, 423, 4464, 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, 225, 445, 598, 9446, 12, 11890, 5034, 389, 350, 13, 3903, 288, 203, 1377, 2583, 12, 2629, 18, 5508, 405, 6445, 71, 27, 5340, 3126, 63, 67, 350, 8009, 19519, 16, 315, 1986, 761, 353, 4859, 316, 2904, 492, 1199, 1769, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 6445, 71, 27, 5340, 3126, 63, 67, 350, 8009, 3355, 24577, 16, 315, 3700, 29917, 6835, 848, 598, 9446, 8863, 203, 4202, 203, 1377, 1758, 29804, 273, 6445, 71, 27, 5340, 3126, 63, 67, 350, 8009, 1786, 749, 31, 203, 1377, 2254, 5034, 761, 273, 6445, 71, 27, 5340, 3126, 63, 67, 350, 8009, 1726, 31, 203, 1377, 1430, 12, 12610, 27, 5340, 3126, 63, 67, 350, 19226, 203, 1377, 467, 654, 39, 27, 5340, 12, 2867, 12, 2316, 13, 2934, 13866, 1265, 12, 2867, 12, 2211, 3631, 29804, 16, 761, 1769, 203, 1377, 3626, 3423, 9446, 82, 24899, 350, 16, 29804, 16, 1758, 12, 2316, 3631, 761, 1769, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-05-27 */ /** *Submitted for verification at Etherscan.io on 2020-05-27 */ pragma solidity 0.5.10; /* ___________________________________________________________________ _ _ ______ | | / / / --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ |/ |/ /___) / / ' / ) / / ) /___) / / ) __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ DIGIGO! ---------------------------------------------------------------------------------------------------- === MAIN FEATURES === => Higher degree of control by owner - safeGuard functionality => SafeMath implementation => Earning on token for fixed-deposit ------------------------------------------------------------------------------------------------------ */ /* Safemath library */ 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; } } // Owner Handler contract ownerShip // Auction Contract Owner and OwherShip change { //Global storage declaration address payable public owner; address payable public newOwner; bool public safeGuard ; // To hault all non owner functions in case of imergency //Event defined for ownership transfered event OwnershipTransferredEv(address payable indexed previousOwner, address payable indexed newOwner); //Sets owner only on first run constructor() public { //Set contract owner owner = msg.sender; // Disabled global hault on first deploy safeGuard = false; } //This will restrict function only for owner where attached modifier onlyOwner() { require(true); _; } function transferOwnership(address payable _newOwner) public onlyOwner { newOwner = _newOwner; } //the reason for this flow is to protect owners from sending ownership to unintended address due to human error function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferredEv(owner, newOwner); owner = newOwner; newOwner = address(0); } function changesafeGuardStatus() onlyOwner public { if (safeGuard == false) { safeGuard = true; } else { safeGuard = false; } } } contract tokenERC20 is ownerShip { // Public variables of the token using SafeMath for uint256; bytes32 public name; bytes8 public symbol; uint8 public decimals; // places of decimal uint256 public totalSupply; uint256 public totalMintAfterInitial; uint256 public maximumSupply; uint public burningRate = 500; // 500=5% // struct to store token and ether value struct userBalance { uint256 totalValue; uint256 freezeValue; uint256 freezeDate; uint256 meltValue; } // Mapped storage for token ( If token address is 0 means ether) mapping (address => mapping (address => userBalance)) public tokens; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Records for the fronzen accounts */ mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); //Calculate percent and return result function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256) { uint256 factor = 10000; require(percentTo <= factor); uint256 c = PercentOf.mul(percentTo).div(factor); return c; } function setBurningRate(uint _burningRate) onlyOwner public returns(bool success) { burningRate = _burningRate; return true; } //Token type defnition struct tokenTypeData { bytes32 tokenName; bytes8 tokenSymbol; uint decimalCount; uint minFreezingValue; uint rateFactor; // % of token balance amount = "effective balance amount" to calculate interest uint perDayFreezeRate; //1000 = 10% ,10 = 0.1%, 1 = 0.01% bool freezingAllowed; // If false this token type is not allowed or accepted to freeze } // Mapped storage struct for token type data mapping (address => tokenTypeData) public tokenTypeDatas; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor () public { decimals = 18; // 18 decimal places totalSupply = 50000000000000000000000000; // 50 Million with 18 decimal places maximumSupply = 100000000000000000000000000; // 100 Million with 18 decimal places balanceOf[msg.sender]=totalSupply; // tokens will be sent to owner tokens[address(this)][owner].totalValue = balanceOf[msg.sender]; name = "DIGIGO Token"; // Set the name for display purposes symbol = "DIGO"; // Set the symbol for display purposes //In house token type data update tokenTypeData memory temp; temp.tokenName=name; temp.tokenSymbol=symbol; temp.decimalCount=decimals; temp.minFreezingValue=100; temp.rateFactor=10000; //10000 = 100% means token amount = effective amount temp.perDayFreezeRate=100; // 1% daily freezing reward temp.freezingAllowed=true; tokenTypeDatas[address(this)] = temp; emit Transfer(address(0), msg.sender, totalSupply); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(!safeGuard,"safeGuard Active"); require (_to != address(0),"to is address 0"); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value, "no balance in from"); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to],"overflow balance"); // Check for overflows require(!frozenAccount[_from],"from account frozen"); // Check if sender is frozen require(!frozenAccount[_to],"to account frozen"); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender tokens[address(this)][_from].totalValue = tokens[address(this)][_from].totalValue.sub(_value); //parallel record for multi token addressing need balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient tokens[address(this)][_to].totalValue = tokens[address(this)][_to].totalValue.add(_value); //parallel record for multi token addressing need uint burnValue; if(!(msg.sender == owner || msg.sender == address(this))) // burn if sender is not this contract or owner { burnValue = calculatePercentage(_value,burningRate); //amount to burn require(burnInternal(_to, burnValue),"burning failed"); // burnt from receiver } emit Transfer(_from, _to,_value); } function burnInternal(address _burnFrom, uint _burnValue) internal returns(bool success) { require(!safeGuard,"safeGuard Active"); require(_burnFrom != address(0)); require(balanceOf[_burnFrom] >= _burnValue); // Check if the sender has enough require(!frozenAccount[_burnFrom],"to account frozen"); // Check if recipient is frozen balanceOf[_burnFrom] = balanceOf[_burnFrom].sub(_burnValue); // Subtract from the sender tokens[address(this)][_burnFrom].totalValue = tokens[address(this)][_burnFrom].totalValue.sub(_burnValue); //parallel record for multi token addressing need balanceOf[address(0)] = balanceOf[address(0)].add(_burnValue); // Add the same to the recipient tokens[address(this)][address(0)].totalValue = tokens[address(this)][address(0)].totalValue.add(_burnValue); //parallel record for multi token addressing need totalSupply = totalSupply.sub(_burnValue); emit Transfer(_burnFrom, address(0),_burnValue); // Update totalSupply return true; } function mintInternal(uint256 mintedAmount) internal returns (bool success) { totalSupply = totalSupply.add(mintedAmount); totalMintAfterInitial = totalMintAfterInitial.add(mintedAmount); //emit Transfer(address(0), address(this), mintedAmount); return true; } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!safeGuard); require(_from != address(0),"transfer from adderss(0) is invalid"); require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { require(!safeGuard); allowance[msg.sender][_spender] = _value; return true; } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) public onlyOwner returns (bool success) { balanceOf[target] = balanceOf[target].add(mintedAmount); tokens[address(this)][target].totalValue = tokens[address(this)][target].totalValue.add(mintedAmount); //parallel record for multi token addressing need totalSupply = totalSupply.add(mintedAmount); totalMintAfterInitial = totalMintAfterInitial.add(mintedAmount); emit Transfer(address(0), address(this), mintedAmount); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public onlyOwner returns (bool success) { burnInternal(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) { burnInternal(_from, _value); return true; } } interface ERC20Essential { function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); } //Main contract starts here contract DIGIGO is tokenERC20 { using SafeMath for uint256; /*************************************/ /* User whitelisting functionality */ /*************************************/ bool public whitelistingStatus = false; mapping (address => bool) public whitelisted; /** * Change whitelisting status on or off * * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. */ function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; whitelisted[owner]= true; } else{ whitelistingStatus = false; } } /** * Whitelist any user address - only Owner can do this * * It will add user address in whitelisted mapping */ function whitelistUser(address userAddress) onlyOwner public{ require(whitelistingStatus == true); require(userAddress != address(0)); whitelisted[userAddress] = true; } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } //Just in case, owner wants to transfer Tokens from contract to owner address function manualWithdrawToken(uint256 _amount) onlyOwner public { uint256 tokenAmount = _amount.mul(100); _transfer(address(this), msg.sender, tokenAmount); } //Just in case, owner wants to transfer Ether from contract to owner address function manualWithdrawEther()onlyOwner public{ uint256 amount=address(this).balance; owner.transfer(amount); msg.sender.transfer(address(this).balance); } //injected WASTEFUL CONTRACT //To air drop function airDrop(address[] memory recipients,uint[] memory tokenAmount) public onlyOwner returns (bool) { uint reciversLength = recipients.length; require(reciversLength <= 150); for(uint i = 0; i < reciversLength; i++) { //This will loop through all the recipients and send them the specified tokens _transfer(owner, recipients[i], tokenAmount[i]); } return true; } uint public meltHoldSeconds = 172800; // 172800 seconds = 48 Hr. user can withdraw only after this period //Event for eexternal token deposit and withdraw event tokenDepositEv(address token, address user, uint amount, uint balance); event tokenWithdrawEv(address token, address user, uint amount, uint balance); function setWithdrawWaitingPeriod(uint valueInSeconds) onlyOwner public returns (bool) { meltHoldSeconds = valueInSeconds; return true; } function newTokenTypeData(address token,bytes32 _tokenName, bytes8 _tokenSymbol, uint _decimalCount, uint _minFreezingValue, uint _rateFactor, uint _perDayFreezeRate) onlyOwner public returns (bool) { tokenTypeData memory temp; temp.tokenName=_tokenName; temp.tokenSymbol=_tokenSymbol; temp.decimalCount=_decimalCount; temp.minFreezingValue=_minFreezingValue; temp.rateFactor=_rateFactor; temp.perDayFreezeRate=_perDayFreezeRate; temp.freezingAllowed=true; tokenTypeDatas[token] = temp; return true; } function freezingOnOffForTokenType(address token) onlyOwner public returns (bool) { if (tokenTypeDatas[token].freezingAllowed == false) { tokenTypeDatas[token].freezingAllowed = true; } else { tokenTypeDatas[token].freezingAllowed = false; } return true; } function setMinFreezingValue(address token, uint _minFreezingValue) onlyOwner public returns (bool) { tokenTypeDatas[token].minFreezingValue = _minFreezingValue; return true; } function setRateFactor(address token, uint _rateFactor) onlyOwner public returns (bool) { tokenTypeDatas[token].rateFactor = _rateFactor; return true; } function setPerDayFreezeRate(address token, uint _perDayFreezeRate) onlyOwner public returns (bool) { tokenTypeDatas[token].perDayFreezeRate = _perDayFreezeRate; return true; } //To deposit token function tokenDeposit(address token, uint amount) public { //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. require(token!=address(0),"Address(0) found, can't continue"); require(ERC20Essential(token).transferFrom(msg.sender, address(this), amount),"ERC20 'transferFrom' call failed"); tokens[token][msg.sender].totalValue = tokens[token][msg.sender].totalValue.add(amount); emit tokenDepositEv(token, msg.sender, amount, tokens[token][msg.sender].totalValue); } //To withdraw token function tokenWithdraw(address token, uint amount) public { require(!safeGuard,"System Paused By Admin"); require(token != address(this)); require(token!=address(0),"Address(0) found, can't continue"); if(now.sub(meltHoldSeconds) > tokens[token][msg.sender].freezeDate) { tokens[token][msg.sender].meltValue = 0; } require(tokens[token][msg.sender].totalValue.sub(tokens[token][msg.sender].freezeValue.add(tokens[token][msg.sender].meltValue)) >= amount,"Required amount is not free to withdraw"); tokens[token][msg.sender].totalValue = tokens[token][msg.sender].totalValue.sub(amount); ERC20Essential(token).transfer(msg.sender, amount); emit tokenWithdrawEv(token, msg.sender, amount, tokens[token][msg.sender].totalValue); } event releaseMyHypeEv(address token, uint amount); //releasing after minumum waiting period to withdraw DIGO function releaseMyHype(address token) public returns (bool) { require(!safeGuard,"System Paused By Admin"); require(token!=address(0),"Address(0) found, can't continue"); require(token == address(this),"Only possible for DIGO "); require(now.sub(meltHoldSeconds) > tokens[token][msg.sender].freezeDate,"wait period is not over"); uint amount = tokens[token][msg.sender].meltValue; balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); tokens[token][msg.sender].totalValue = balanceOf[msg.sender].add(tokens[token][msg.sender].freezeValue ); tokens[token][msg.sender].meltValue = 0; emit releaseMyHypeEv(token, amount); return true; } event tokenBalanceFreezeEv(address token, uint amount, uint earning); function tokenBalanceFreeze(address token, uint amount) public returns (bool) { require(!safeGuard,"System Paused By Admin"); require(tokenTypeDatas[token].freezingAllowed,"token type not allowed to freeze"); require(token!=address(0),"Address(0) found, can't continue"); address callingUser = msg.sender; require(msg.sender != address(0),"Address(0) found, can't continue"); require(amount <= tokens[token][callingUser].totalValue.sub(tokens[token][callingUser].freezeValue.add(tokens[token][callingUser].meltValue)) && amount >= tokenTypeDatas[token].minFreezingValue, "less than required or less balance"); //before adding more freezing amount calculating earning on existing freeze amount and updating same in user ether balance uint freezeValue = tokens[token][callingUser].freezeValue; uint earnedValue; if (freezeValue > 0) { earnedValue = getEarning(token,callingUser,freezeValue); require(mintInternal(earnedValue),"minting failed"); tokens[address(this)][callingUser].meltValue = tokens[address(this)][callingUser].meltValue.add(earnedValue); } tokens[token][callingUser].freezeValue = tokens[token][callingUser].freezeValue.add(amount); if (token==address(this)) { balanceOf[callingUser] = balanceOf[callingUser].sub(amount); } tokens[token][callingUser].freezeDate = now; emit tokenBalanceFreezeEv(token,amount,earnedValue); return true; } function getEarning(address token,address user,uint amount) internal view returns(uint256) { uint effectiveAmount = calculatePercentage(amount,tokenTypeDatas[token].rateFactor); uint interestAmount = calculatePercentage(effectiveAmount,tokenTypeDatas[token].perDayFreezeRate); uint secondsPassed = (now - tokens[token][user].freezeDate); uint daysPassed=0; if (secondsPassed >= 86400) // if less than one day earning will be zero { daysPassed = secondsPassed.div(86400); } return daysPassed.mul(interestAmount); } event tokenBalanceMeltEv(address token, uint amount, uint earning); function tokenBalanceMelt(address token, uint amount) public returns (bool) { require(!safeGuard,"System Paused By Admin"); require(token!=address(0),"Address(0) found, can't continue"); address callingUser = msg.sender; require(msg.sender != address(0),"Address(0) found, can't continue"); require(amount <= tokens[token][callingUser].freezeValue && amount > 0, "less than required or less balance"); //before melting amount calculating earning on existing freeze amount and updating same in user ether balance uint freezeValue = tokens[token][callingUser].freezeValue; uint earnedValue = getEarning(token,callingUser,freezeValue); require(mintInternal(earnedValue),"minting failed"); tokens[address(this)][callingUser].meltValue = tokens[address(this)][callingUser].meltValue.add(earnedValue); tokens[token][callingUser].freezeValue = tokens[token][callingUser].freezeValue.sub(amount); if (token==address(this)) { tokens[token][callingUser].meltValue = tokens[token][callingUser].meltValue.add(amount); } tokens[token][callingUser].freezeDate = now; emit tokenBalanceMeltEv(token,amount,earnedValue); return true; } function viewMyReward(address token) public view returns(uint freezedValue, uint rewardValue) { address callingUser = msg.sender; uint freezeValue = tokens[token][callingUser].freezeValue; uint earnedValue = getEarning(token,callingUser,freezeValue); return (freezeValue,earnedValue); } }
% of token balance amount = "effective balance amount" to calculate interest
uint rateFactor;
15,835,548
[ 1, 9, 434, 1147, 11013, 3844, 273, 315, 28894, 11013, 3844, 6, 358, 4604, 16513, 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, 3639, 2254, 4993, 6837, 31, 4202, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./openzeppelin-contracts-4.5.0/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "./openzeppelin-contracts-4.5.0/contracts/access/Ownable.sol"; import "./openzeppelin-contracts-4.5.0/contracts/token/common/ERC2981.sol"; import "./utils/IMintable.sol"; import "./utils/Minting.sol"; /// @custom:royalty Token can have custom royalty, if not: default royalty will be considered, if default royalty is deleted: then will be no royalty. /// @custom:minters Addresses added to minters can mint tokens. /// @custom:ownership Renounce ownership does NOT remove from minters. contract AgletSneakers is ERC721URIStorage, Ownable, IMintable, ERC2981 { /// @notice Event emitted on withdraw from ImmutableX event TokenMintedFor(uint256 id, address to); /// @notice Address that are authorized to mint tokens. mapping(address => bool) public minters; /// @notice Additional details about tokens mapping(uint256 => string) public sneakerDetails; /// @param name Name of collection /// @param symbol Symbol of collection /// @param _imx ImmutableX address /// @param royaltyDefaultReceiver Address which will be royalty default receiver /// @param royaltyDefaultNumerator Numerator of default royalty /// @dev Notice owner is added to minters constructor( string memory name, string memory symbol, address _imx, address royaltyDefaultReceiver, uint96 royaltyDefaultNumerator) ERC721(name, symbol) Ownable() { minters[_imx] = true; minters[_msgSender()] = true; _setDefaultRoyalty(royaltyDefaultReceiver, royaltyDefaultNumerator); } /// @notice Modifier, allow only authorized minters modifier onlyMinters() { require(minters[msg.sender], "Function can only be called by minters"); _; } /// @notice Method to mint /// @param to Who receive token /// @param tokenId Identifier of minted token /// @param tokenUri Uri to token /// @param tokenDetails Details about token to set, to mint without details, pass empty string function safeMint( address to, uint256 tokenId, string memory tokenUri, string memory tokenDetails) public onlyMinters { _safeMint(to, tokenId); _setTokenURI(tokenId, tokenUri); _setTokenDetails(tokenId, tokenDetails); } /// @notice Method to mint and set custom royalty /// @param to Who receive token /// @param tokenId Identifier of minted token /// @param tokenUri Uri to token /// @param royaltyReceiver Address which will be royalty receiver to set /// @param royaltyNumerator Numerator of royalty to set /// @param tokenDetails Details about token to set, to mint without details, pass empty string function safeMintWithRoyalty( address to, uint256 tokenId, string memory tokenUri, address royaltyReceiver, uint96 royaltyNumerator, string memory tokenDetails) public onlyMinters { safeMint(to, tokenId, tokenUri, tokenDetails); _setTokenRoyalty(tokenId, royaltyReceiver, royaltyNumerator); } /// @notice Method to withdraw token from ImmutableX /// @param user Who receive token /// @param quantity Quantity of withdraw tokens. Only handle quantity = 1 /// @param mintingBlob Tokens data, format {'tokenId'}:{'royaltyNumerator''royaltyReceiver''tokenURILength':'tokenURI''tokenDetailsLength':'tokenDetails'} /// @dev to mint without royalty set royaltyNumerator to zero /// @dev to mint without details skip 'tokenDetailsLength':'tokenDetails' in mintingBlob function mintFor( address user, uint256 quantity, bytes calldata mintingBlob) public override onlyMinters { require(quantity == 1, "Invalid quantity"); uint256 tokenId; uint256 index; uint96 royaltyNumerator; address royaltyReceiver; string memory tokenURI; string memory tokenDetails; (tokenId, index) = Minting.getTokenId(mintingBlob); (royaltyNumerator, index) = Minting.getRoyaltyFraction(mintingBlob, index); (royaltyReceiver, index) = Minting.getRoyaltyReceiver(mintingBlob, index); (tokenURI, index) = Minting.getURI(mintingBlob, index); tokenDetails = Minting.getDetails(mintingBlob, index); safeMintWithRoyalty(user, tokenId, tokenURI, royaltyReceiver, royaltyNumerator, tokenDetails); emit TokenMintedFor(tokenId, user); } /// @notice Set token details /// @param tokenId Identifier of the token /// @param tokenDetails Token details to set function _setTokenDetails( uint256 tokenId, string memory tokenDetails) internal { require(_exists(tokenId), "Details set of nonexistent token"); sneakerDetails[tokenId] = tokenDetails; } /// @notice method to transfer smart contract ownership /// @param newOwner Address to transfer smart contract ownership /// @dev Notice old owner will be removed from minters and new owner will be added function transferOwnership(address newOwner) public virtual override onlyOwner { super.transferOwnership(newOwner); delete minters[_msgSender()]; minters[newOwner] = true; } /// @notice Add address to minters /// @param to Address which will be added to minters function addMinter( address to) public onlyOwner { minters[to] = true; } /// @notice Remove address from minters /// @param to Address which will be removed from minters function removeMinter( address to) public onlyOwner { delete minters[to]; } /// @notice Set custom royalty for the token /// @param tokenId Identifier of the token /// @param royaltyReceiver Address which will be royalty receiver to set /// @param royaltyNumerator Numerator of royalty to set function setTokenRoyalty( uint256 tokenId, address royaltyReceiver, uint96 royaltyNumerator ) public onlyOwner { _setTokenRoyalty(tokenId, royaltyReceiver, royaltyNumerator); } /// @notice Remove custom royalty for the token /// @param tokenId Identifier of the token function resetTokenRoyalty( uint256 tokenId) public onlyOwner { _resetTokenRoyalty(tokenId); } /// @notice Remove default royalty for the smart contract function deleteDefaultRoyalty() public onlyOwner { _deleteDefaultRoyalty(); } /// @notice Set default royalty for the smart contract /// @param royaltyReceiver Address which will be royalty receiver to set /// @param royaltyNumerator Numerator of royalty to set function setDefaultRoyalty( address royaltyReceiver, uint96 royaltyNumerator ) public onlyOwner { _setDefaultRoyalty(royaltyReceiver, royaltyNumerator); } /// @notice Return true if smart contract support the interface /// @param interfaceId Interface identifier to check support function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Minting { function getTokenId(bytes calldata blob) internal pure returns ( uint256, uint256) { int256 index = indexOf(blob, ":", 0, 47); require(index >= 0, "Separator must exist"); uint256 tokenID = toUint256(blob[1 : uint256(index) - 1]); return (tokenID, uint256(index) + 2); } function getRoyaltyFraction(bytes calldata blob, uint256 startIndex) internal pure returns ( uint96, uint256) { uint96 royaltyNumerator = toUint96( blob[startIndex : startIndex + 5] ); return (royaltyNumerator, startIndex + 5); } function getRoyaltyReceiver(bytes calldata blob, uint256 startIndex) internal pure returns ( address, uint256) { address royaltyRecipient = toAddress( blob[startIndex : startIndex + 42] ); return (royaltyRecipient, startIndex + 42); } function getURI(bytes calldata blob, uint256 startIndex) internal pure returns ( string memory, uint256) { uint96 length; string memory uri; (uri, startIndex, length) = getVariableString(blob, startIndex); require(length > 0, "Bad format of mintingBlob"); return (uri, startIndex); } function getDetails(bytes calldata blob, uint256 startIndex) internal pure returns ( string memory) { uint96 length; string memory details; (details, startIndex, length) = getVariableString(blob, startIndex); return details; } function getVariableString(bytes calldata blob, uint256 startIndex) internal pure returns ( string memory, uint256, uint96) { uint96 length; (length, startIndex) = getLength(blob, startIndex); if(length == 0){ return ("", startIndex, length); } require(blob[startIndex] == ":", "Bad format of mintingBlob"); startIndex = startIndex + 1; uint256 end = startIndex + uint256(length); require(end <= blob.length - 1, "Bad format of mintingBlob"); bytes calldata variableBytes = blob[startIndex : end]; string memory variable = string( variableBytes ); return (variable, end, length); } function getLength(bytes calldata blob, uint256 startIndex) internal pure returns ( uint96, uint256) { if (startIndex == blob.length - 1) { return (0, startIndex + 5); } require(startIndex + 5 <= blob.length - 1, "Bad format of mintingBlob"); uint96 length = toUint96( blob[startIndex : startIndex + 5] ); return (length, startIndex + 5); } function toUint256(bytes calldata b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { // input is 0-9 result = result * 10 + (val - 48); } else { // invalid character, expecting integer input revert("invalid input, only numbers allowed"); } } return result; } function toUint96(bytes calldata b) internal pure returns (uint96) { uint96 result = 0; for (uint256 i = 0; i < b.length; i++) { uint96 val = uint96(uint8(b[i])); if (val >= 48 && val <= 57) { // input is 0-9 result = result * 10 + (val - 48); } else { // invalid character, expecting integer input revert("invalid input, only numbers allowed 96"); } } return result; } function toAddress(bytes calldata b) internal pure returns (address) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 c = uint256(uint8(b[i])); if (c >= 48 && c <= 57) { result = result * 16 + (c - 48); } else if (c >= 65 && c <= 90) { result = result * 16 + (c - 55); } else if (c >= 97 && c <= 122) { result = result * 16 + (c - 87); } else { revert("invalid input, unrecognized sign"); } } return address(uint160(result)); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes calldata _base, string memory _value, uint256 _offset, uint256 max ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length && i < max; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return - 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IMintable { function mintFor( address to, uint256 quantity, bytes calldata mintingBlob ) external; } // 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/introspection/ERC165.sol) 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 // 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); } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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 (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: 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)); } return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // 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-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 (last updated v4.5.0) (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _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); } }
@notice Add address to minters @param to Address which will be added to minters
function addMinter( address to) public onlyOwner { minters[to] = true; }
13,377,074
[ 1, 986, 1758, 358, 1131, 5432, 225, 358, 5267, 1492, 903, 506, 3096, 358, 1131, 5432, 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, 445, 527, 49, 2761, 12, 203, 3639, 1758, 358, 13, 203, 565, 1071, 1338, 5541, 288, 203, 3639, 1131, 5432, 63, 869, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.2; interface cToken { function underlying() external view returns (address); } interface comptroller { function getAllMarkets() external view returns (address[] memory); function markets(address _market) external view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped); } interface ibtroller { function getAllMarkets() external view returns (address[] memory); function markets(address _market) external view returns (bool isListed, uint256 collateralFactorMantissa); } interface aavecore { struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } function getReserveConfiguration(address _market) external view returns (uint, uint, uint, bool); function getConfiguration(address _market) external view returns (ReserveConfigurationMap memory); } contract CollateralMaximizer { address constant private _cream = address(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); address constant private _compound = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address constant private _aavev1 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); address constant private _aavev2 = address(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); address constant private _ib = address(0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB); address constant private _weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; function getParamsMemory(aavecore.ReserveConfigurationMap memory self) internal pure returns (uint256) { return (self.data & ~LTV_MASK); } function lookupMarket(address _core, address _token) public view returns (address) { if (_core == _compound && _token == _weth) { return 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; } else if (_core == _cream && _token == _weth) { return 0xD06527D5e56A3495252A528C4987003b712860eE; } address[] memory _list = comptroller(_core).getAllMarkets(); for (uint i = 0; i < _list.length; i++) { if (_list[i] != address(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5) && _list[i] != address(0xD06527D5e56A3495252A528C4987003b712860eE)) { if (cToken(_list[i]).underlying() == _token) { return _list[i]; } } } return address(0x0); } function lookupMarketCompound(address _token) external view returns (address) { return lookupMarket(_compound, _token); } function lookupMarketCream(address _token) external view returns (address) { return lookupMarket(_cream, _token); } function lookupMarketIB(address _token) external view returns (address) { return lookupMarket(_ib, _token); } function getLTVCream(address _token) public view returns (uint cream) { (,cream,) = comptroller(_cream).markets(lookupMarket(_cream, _token)); cream = cream / 1e16; } function getLTVCompound(address _token) public view returns (uint compound) { (,compound,) = comptroller(_compound).markets(lookupMarket(_compound, _token)); compound = compound / 1e16; } function getLTVIB(address _token) public view returns (uint ib) { (,ib) = ibtroller(_ib).markets(lookupMarket(_ib, _token)); ib = ib / 1e16; } function getLTVAaveV1(address _token) public view returns (uint aavev1) { (,aavev1,,) = aavecore(_aavev1).getReserveConfiguration(_token); } function getLTVAaveV2(address _token) public view returns (uint aavev2) { (aavev2) = getParamsMemory(aavecore(_aavev2).getConfiguration(_token)); aavev2 = aavev2 / 1e2; } function getLTV(address _token) public view returns (uint cream, uint compound, uint ib, uint aavev1, uint aavev2) { cream = getLTVCream(_token); compound = getLTVCompound(_token); ib = getLTVIB(_token); aavev1 = getLTVAaveV1(_token); aavev2 = getLTVAaveV2(_token); } }
@dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
function getReserveConfiguration(address _market) external view returns (uint, uint, uint, bool); function getConfiguration(address _market) external view returns (ReserveConfigurationMap memory); } function getParamsMemory(aavecore.ReserveConfigurationMap memory self) internal pure returns (uint256) { return (self.data & ~LTV_MASK); }
5,794,064
[ 1, 1290, 326, 11807, 58, 16, 326, 787, 2831, 353, 374, 261, 416, 358, 4711, 3631, 20356, 1158, 2831, 674, 430, 1787, 353, 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 ]
[ 1, 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 ]
[ 1, 565, 445, 31792, 6527, 1750, 12, 2867, 389, 27151, 13, 3903, 1476, 1135, 261, 11890, 16, 2254, 16, 2254, 16, 1426, 1769, 203, 565, 445, 10316, 12, 2867, 389, 27151, 13, 3903, 1476, 1135, 261, 607, 6527, 1750, 863, 3778, 1769, 203, 97, 203, 203, 565, 445, 13281, 6031, 12, 69, 836, 3644, 18, 607, 6527, 1750, 863, 3778, 365, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 7010, 3639, 327, 261, 2890, 18, 892, 473, 4871, 12050, 58, 67, 11704, 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 ]
./full_match/97/0x539d8FbAEF360FBA0844898347B169842C300B7a/sources/project_/contracts/erc20Beacon.sol
* @dev Emitted when ownership of the contract's transferred./* @dev Throws if an implementation's preset for this contract./
modifier initCheck() { require(vLogic == address(0x0), "Can't initialize more than once!"); _; }
3,262,601
[ 1, 1514, 11541, 1347, 23178, 434, 326, 6835, 1807, 906, 4193, 18, 19, 225, 22435, 309, 392, 4471, 1807, 12313, 364, 333, 6835, 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 ]
[ 1, 1, 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, 9606, 1208, 1564, 1435, 288, 203, 3639, 2583, 12, 90, 20556, 422, 1758, 12, 20, 92, 20, 3631, 315, 2568, 1404, 4046, 1898, 2353, 3647, 4442, 1769, 203, 3639, 389, 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 ]
./partial_match/3/0x804760BBf64D0635846b87B9702fEF7581485E1f/sources/StakerChef.sol
View function to see pending SKYs on frontend.
function pendingSky(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSkyPerShare = pool.accSkyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 skyReward = multiplier.mul(skyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSkyPerShare = accSkyPerShare.add(skyReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSkyPerShare).div(1e12).sub(user.rewardDebt); }
5,293,915
[ 1, 1767, 445, 358, 2621, 4634, 12038, 61, 87, 603, 15442, 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 ]
[ 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, 4634, 5925, 93, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 5925, 93, 2173, 9535, 273, 2845, 18, 8981, 5925, 93, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 15513, 17631, 1060, 273, 15027, 18, 16411, 12, 22921, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 5925, 93, 2173, 9535, 273, 4078, 5925, 93, 2173, 9535, 18, 1289, 12, 22921, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 5925, 93, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 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 ]
./full_match/8453/0x2DE9EBBf50E3f57858d78b51F7fF9a790064d5A1/sources/contracts/RelicsAction.sol
which tokenId to start mint
uint64 start;
11,537,829
[ 1, 12784, 1147, 548, 358, 787, 312, 474, 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, 2254, 1105, 787, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../DigitalaxAccessControls.sol"; import "./IDigitalaxMonaOracle.sol"; library Select { using SafeMath for uint256; /** * @dev Sorts the input array up to the denoted size, and returns the median. * @param array Input array to compute its median. * @param size Number of elements in array to compute the median for. * @return Median of array. */ function computeMedian(uint256[] memory array, uint256 size) internal pure returns (uint256) { require(size > 0 && array.length >= size); for (uint256 i = 1; i < size; i++) { for (uint256 j = i; j > 0 && array[j-1] > array[j]; j--) { uint256 tmp = array[j]; array[j] = array[j-1]; array[j-1] = tmp; } } if (size % 2 == 1) { return array[size / 2]; } else { return array[size / 2].add(array[size / 2 - 1]) / 2; } } } /** * @title Digitalax Mona Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract DigitalaxMonaOracle is IDigitalaxMonaOracle, Context { using SafeMath for uint256; struct Report { uint256 timestamp; uint256 payload; } // Addresses of providers authorized to push reports. address[] public providers; // Digitalax Access Controls DigitalaxAccessControls public accessControls; // Reports indexed by provider address. Report[0].timestamp > 0 // indicates provider existence. mapping (address => Report[2]) public providerReports; event ProviderAdded(address provider); event ProviderRemoved(address provider); event ReportTimestampOutOfRange(address provider); event ProviderReportPushed(address indexed provider, uint256 payload, uint256 timestamp); // The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; // The number of seconds since reporting that has to pass before a report // is usable. uint256 public reportDelaySec; // The minimum number of providers with valid reports to consider the // aggregate report valid. uint256 public minimumProviders = 1; // Timestamp of 1 is used to mark uninitialized and invalidated data. // This is needed so that timestamp of 1 is always considered expired. uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks; /** * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. * @param reportDelaySec_ The number of seconds since reporting that has to * pass before a report is usable * @param minimumProviders_ The minimum number of providers with valid * reports to consider the aggregate report valid. */ constructor(uint256 reportExpirationTimeSec_, uint256 reportDelaySec_, uint256 minimumProviders_, DigitalaxAccessControls accessControls_) public { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME, "DigitalaxMonaOracle: Invalid report exipiration time"); require(minimumProviders_ > 0, "DigitalaxMonaOracle: Minimum providers count might be greater than zero"); require(address(accessControls_) != address(0x0), "DigitalaxMonaOracle: AccessControls is invalid"); reportExpirationTimeSec = reportExpirationTimeSec_; reportDelaySec = reportDelaySec_; minimumProviders = minimumProviders_; accessControls = accessControls_; } /** * @notice Sets the report expiration period. * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. */ function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaOracle.setReportExpirationTimeSec: Sender must be admin" ); require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME, "DigitalaxMonaOracle.setReportExpirationTimeSec: Invalid expiration time"); reportExpirationTimeSec = reportExpirationTimeSec_; } /** * @notice Sets the time period since reporting that has to pass before a * report is usable. * @param reportDelaySec_ The new delay period in seconds. */ function setReportDelaySec(uint256 reportDelaySec_) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaOracle.setReportDelaySec: Sender must be admin" ); reportDelaySec = reportDelaySec_; } /** * @notice Sets the minimum number of providers with valid reports to * consider the aggregate report valid. * @param minimumProviders_ The new minimum number of providers. */ function setMinimumProviders(uint256 minimumProviders_) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaOracle.setMinimumProviders: Sender must be admin" ); require(minimumProviders_ > 0); minimumProviders = minimumProviders_; } /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external { address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; // Check that the push is not too soon after the last one. require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); } /** * @notice Invalidates the reports of the calling provider. */ function purgeReports() external { address providerAddress = msg.sender; require (providerReports[providerAddress][0].timestamp > 0); providerReports[providerAddress][0].timestamp=1; providerReports[providerAddress][1].timestamp=1; } /** * @notice Computes median of provider reports whose timestamps are in the * valid timestamp range. * @return AggregatedValue: Median of providers reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() external override returns (uint256, bool) { uint256 reportsCount = providers.length; uint256[] memory validReports = new uint256[](reportsCount); uint256 size = 0; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { // Recent report is too recent. uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { // Past report is too old. emit ReportTimestampOutOfRange(providerAddress); } else if (reportTimestampPast > maxValidTimestamp) { // Past report is too recent. emit ReportTimestampOutOfRange(providerAddress); } else { // Using past report. validReports[size++] = providerReports[providerAddress][index_past].payload; } } else { // Recent report is not too recent. if (reportTimestampRecent < minValidTimestamp) { // Recent report is too old. emit ReportTimestampOutOfRange(providerAddress); } else { // Using recent report. validReports[size++] = providerReports[providerAddress][index_recent].payload; } } } if (size < minimumProviders) { return (0, false); } return (Select.computeMedian(validReports, size), true); } /** * @notice Authorizes a provider. * @param provider Address of the provider. */ function addProvider(address provider) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaOracle.addProvider: Sender must be admin" ); require(providerReports[provider][0].timestamp == 0); providers.push(provider); providerReports[provider][0].timestamp = 1; emit ProviderAdded(provider); } /** * @notice Revokes provider authorization. * @param provider Address of the provider. */ function removeProvider(address provider) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaOracle.removeProvider: Sender must be admin" ); delete providerReports[provider]; for (uint256 i = 0; i < providers.length; i++) { if (providers[i] == provider) { if (i + 1 != providers.length) { providers[i] = providers[providers.length-1]; } providers.pop(); emit ProviderRemoved(provider); break; } } } /** * @return The number of authorized providers. */ function providersSize() external view returns (uint256) { return providers.length; } }
* @return The number of authorized providers./
function providersSize() external view returns (uint256) { return providers.length; }
12,828,233
[ 1, 2463, 1021, 1300, 434, 10799, 9165, 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, 565, 445, 9165, 1225, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 9165, 18, 2469, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface IStakingProxy { function getBalance() external view returns(uint256); function withdraw(uint256 _amount) external; function stake() external; function distribute() external; } interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } /// @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 div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } 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); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(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"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /** * @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; } } /** * @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); } } } } /** * @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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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"); } } } /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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)); } } /** * @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 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; } /** * @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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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; } interface IGac { function paused() external view returns (bool); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } /** * @title Global Access Control Managed - Base Class * @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality */ contract GlobalAccessControlManaged is PausableUpgradeable { IGac public gac; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); /// ======================= /// ===== Initializer ===== /// ======================= /** * @notice Initializer * @dev this is assumed to be used in the initializer of the inhereiting contract * @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role */ function __GlobalAccessControlManaged_init(address _globalAccessControl) public initializer { __Pausable_init_unchained(); gac = IGac(_globalAccessControl); } /// ===================== /// ===== Modifiers ===== /// ===================== function _onlyRole(bytes32 role) internal { require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role"); } /// @dev can be pausable by GAC or local flag modifier gacPausable() { require(!gac.paused(), "global-paused"); require(!paused(), "local-paused"); _; } /// ================================ /// ===== Permissioned actions ===== /// ================================ function pause() external { require(gac.hasRole(PAUSER_ROLE, msg.sender)); _pause(); } function unpause() external { require(gac.hasRole(UNPAUSER_ROLE, msg.sender)); _unpause(); } } /* Citadel locking contract Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol). Changes: - Upgradeability - Removed staking */ contract StakedCitadelLocker is Initializable, ReentrancyGuardUpgradeable, GlobalAccessControlManaged { using BoringMath for uint256; using BoringMath224 for uint224; using BoringMath112 for uint112; using BoringMath32 for uint32; using SafeERC20Upgradeable for IERC20Upgradeable; /* ========== STATE VARIABLES ========== */ struct Reward { bool useBoost; uint40 periodFinish; uint208 rewardRate; uint40 lastUpdateTime; uint208 rewardPerTokenStored; } struct Balances { uint112 locked; uint112 boosted; uint32 nextUnlockIndex; } struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } struct EarnedData { address token; uint256 amount; } struct Epoch { uint224 supply; //epoch boosted supply uint32 date; //epoch start date } bytes32 public constant CONTRACT_GOVERNANCE_ROLE = keccak256("CONTRACT_GOVERNANCE_ROLE"); bytes32 public constant TREASURY_GOVERNANCE_ROLE = keccak256("TREASURY_GOVERNANCE_ROLE"); bytes32 public constant TECH_OPERATIONS_ROLE = keccak256("TECH_OPERATIONS_ROLE"); //token constants IERC20Upgradeable public stakingToken; // xCTDL token //rewards address[] public rewardTokens; mapping(address => Reward) public rewardData; // Duration that rewards are streamed over uint256 public constant rewardsDuration = 86400 * 21; // 21 days // Duration of lock/earned penalty period uint256 public constant lockDuration = 86400 * 7 * 21; // 21 weeks // reward token -> distributor -> is approved to add rewards mapping(address => mapping(address => bool)) public rewardDistributors; // user -> reward token -> amount mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; //supplies and epochs uint256 public lockedSupply; uint256 public boostedSupply; Epoch[] public epochs; //mappings for balance data mapping(address => Balances) public balances; mapping(address => LockedBalance[]) public userLocks; // ========== Not used ========== //boost address public boostPayment = address(0); uint256 public maximumBoostPayment = 0; uint256 public boostRate = 10000; uint256 public nextMaximumBoostPayment = 0; uint256 public nextBoostRate = 10000; uint256 public constant denominator = 10000; // ============================== //staking uint256 public minimumStake = 10000; uint256 public maximumStake = 10000; address public stakingProxy = address(0); uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing //management uint256 public kickRewardPerEpoch = 100; uint256 public kickRewardEpochDelay = 4; //shutdown bool public isShutdown = false; //erc20-like interface string private _name; string private _symbol; uint8 private _decimals; // Cumulative rewards claimed by a user for a given reward token. Mapped by user -> token -> amount mapping(address => mapping(address => uint256)) public cumulativeClaimed; // Cumuluative amount of a given reward token distributed by all rewardDistributors mapping(address => uint256) public cumulativeDistributed; /* ========== CONSTRUCTOR ========== */ function initialize( address _stakingToken, address _gac, string calldata name, string calldata symbol ) public initializer { require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero stakingToken = IERC20Upgradeable(_stakingToken); _name = name; _symbol = symbol; _decimals = 18; uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)})); __ReentrancyGuard_init(); __GlobalAccessControlManaged_init(_gac); } function decimals() public view returns (uint8) { return _decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function version() public view returns (uint256) { return 2; } /* ========== ADMIN CONFIGURATION ========== */ // Add a new reward token to be distributed to stakers function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(rewardData[_rewardsToken].lastUpdateTime == 0); // require(_rewardsToken != address(stakingToken)); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(rewardData[_rewardsToken].lastUpdateTime > 0); rewardDistributors[_rewardsToken][_distributor] = _approved; } //Set the staking contract for the underlying cvx function setStakingContract(address _staking) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(stakingProxy == address(0), "!assign"); stakingProxy = _staking; } //set staking limits. will stake the mean of the two once either ratio is crossed function setStakeLimits(uint256 _minimum, uint256 _maximum) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(_minimum <= denominator, "min range"); require(_maximum <= denominator, "max range"); require(_minimum <= _maximum, "min range"); minimumStake = _minimum; maximumStake = _maximum; updateStakeRatio(0); } //set boost parameters function setBoost( uint256 _max, uint256 _rate, address _receivingAddress ) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(_max < 1500, "over max payment"); //max 15% require(_rate < 30000, "over max rate"); //max 3x require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid nextMaximumBoostPayment = _max; nextBoostRate = _rate; boostPayment = _receivingAddress; } //set kick incentive function setKickIncentive(uint256 _rate, uint256 _delay) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(_rate <= 500, "over max rate"); //max 5% per epoch require(_delay >= 2, "min delay"); //minimum 2 epochs of grace kickRewardPerEpoch = _rate; kickRewardEpochDelay = _delay; } //shutdown the contract. unstake all tokens. release all locks function shutdown() external { _onlyRole(CONTRACT_GOVERNANCE_ROLE); isShutdown = true; } /* ========== VIEWS ========== */ function getRewardTokens() external view returns (address[] memory) { uint256 numTokens = rewardTokens.length; address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = rewardTokens[i]; } return tokens; } function getCumulativeClaimedRewards( address _account, address _rewardsToken ) external view returns (uint256) { return cumulativeClaimed[_account][_rewardsToken]; } function _rewardPerToken(address _rewardsToken) internal view returns (uint256) { if (boostedSupply == 0) { return rewardData[_rewardsToken].rewardPerTokenStored; } return uint256(rewardData[_rewardsToken].rewardPerTokenStored).add( _lastTimeRewardApplicable( rewardData[_rewardsToken].periodFinish ) .sub(rewardData[_rewardsToken].lastUpdateTime) .mul(rewardData[_rewardsToken].rewardRate) .mul(1e18) .div( rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply ) ); } function _earned( address _user, address _rewardsToken, uint256 _balance ) internal view returns (uint256) { return _balance .mul( _rewardPerToken(_rewardsToken).sub( userRewardPerTokenPaid[_user][_rewardsToken] ) ) .div(1e18) .add(rewards[_user][_rewardsToken]); } function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) { return MathUpgradeable.min(block.timestamp, _finishTime); } function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) { return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish); } function rewardPerToken(address _rewardsToken) external view returns (uint256) { return _rewardPerToken(_rewardsToken); } function getRewardForDuration(address _rewardsToken) external view returns (uint256) { return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration); } // Address and claimable amount of all reward tokens for the given account function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) { userRewards = new EarnedData[](rewardTokens.length); Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < userRewards.length; i++) { address token = rewardTokens[i]; userRewards[i].token = token; userRewards[i].amount = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); } return userRewards; } function claimableRewardForToken(address _account, address _rewardToken) external view returns (EarnedData memory userReward) { Balances storage userBalance = balances[_account]; return EarnedData( _rewardToken, _earned( _account, _rewardToken, rewardData[_rewardToken].useBoost ? userBalance.boosted : userBalance.locked ) ); } // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens function rewardWeightOf(address _user) external view returns (uint256 amount) { return balances[_user].boosted; } // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount) { return balances[_user].locked; } //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; //start with current boosted amount amount = balances[_user].boosted; uint256 locksLength = locks.length; //remove old records only (will be better gas-wise than adding up) for (uint256 i = nextUnlockIndex; i < locksLength; i++) { if (locks[i].unlockTime <= block.timestamp) { amount = amount.sub(locks[i].boosted); } else { //stop now as no futher checks are needed break; } } //also remove amount locked in the next epoch uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { amount = amount.sub(locks[locksLength - 1].boosted); } return amount; } //BOOSTED balance of an account which only includes properly locked tokens at the given epoch function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get timestamp of given epoch index uint256 epochTime = epochs[_epoch].date; //get timestamp of first non-inclusive epoch uint256 cutoffEpoch = epochTime.sub(lockDuration); //need to add up since the range could be in the middle somewhere //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //lock epoch must be less or equal to the epoch we're basing from. if (lockEpoch <= epochTime) { if (lockEpoch > cutoffEpoch) { amount = amount.add(locks[i].boosted); } else { //stop now as no futher checks matter break; } } } return amount; } //return currently locked but not active balance function pendingLockOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; uint256 locksLength = locks.length; //return amount if latest lock is in the future uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { return locks[locksLength - 1].boosted; } return 0; } function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get next epoch from the given epoch index uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //return the next epoch balance if (lockEpoch == nextEpoch) { return locks[i].boosted; } else if (lockEpoch < nextEpoch) { //no need to check anymore break; } } return 0; } //supply of all properly locked BOOSTED balances at most recent eligible epoch function totalSupply() external view returns (uint256 supply) { uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); uint256 cutoffEpoch = currentEpoch.sub(lockDuration); uint256 epochindex = epochs.length; //do not include next epoch's supply if (uint256(epochs[epochindex - 1].date) > currentEpoch) { epochindex--; } //traverse inversely to make more current queries more gas efficient for (uint256 i = epochindex - 1; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(e.supply); } return supply; } //supply of all properly locked BOOSTED balances at the given epoch function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) { uint256 epochStart = uint256(epochs[_epoch].date) .div(rewardsDuration) .mul(rewardsDuration); uint256 cutoffEpoch = epochStart.sub(lockDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = _epoch; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(epochs[i].supply); } return supply; } //find an epoch index based on timestamp function findEpochId(uint256 _time) external view returns (uint256 epoch) { uint256 max = epochs.length - 1; uint256 min = 0; //convert to start point _time = _time.div(rewardsDuration).mul(rewardsDuration); for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min + max + 1) / 2; uint256 midEpochBlock = epochs[mid].date; if (midEpochBlock == _time) { //found return mid; } else if (midEpochBlock < _time) { min = mid; } else { max = mid - 1; } } return min; } // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; uint256 idx; for (uint256 i = nextUnlockIndex; i < locks.length; i++) { if (locks[i].unlockTime > block.timestamp) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked = locked.add(locks[i].amount); } else { unlockable = unlockable.add(locks[i].amount); } } return (userBalance.locked, unlockable, locked, lockData); } //number of epochs function epochCount() external view returns (uint256) { return epochs.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function checkpointEpoch() external { _checkpointEpoch(); } //insert a new epoch if needed. fill in any gaps function _checkpointEpoch() internal { //create new epoch in the future where new non-active locks will lock to uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; //first epoch add in constructor, no need to check 0 length //check to add if (epochs[epochindex - 1].date < nextEpoch) { //fill any epoch gaps while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)})); } //update boost parameters on a new epoch if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } } // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards function lock( address _account, uint256 _amount, uint256 _spendRatio ) external nonReentrant gacPausable updateReward(_account) { //pull tokens stakingToken.safeTransferFrom(msg.sender, address(this), _amount); //lock _lock(_account, _amount, _spendRatio, false); } //lock tokens function _lock( address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock ) internal { require(_amount > 0, "Cannot stake 0"); require(_spendRatio <= maximumBoostPayment, "over max spend"); require(!isShutdown, "shutdown"); Balances storage bal = balances[_account]; //must try check pointing epoch first _checkpointEpoch(); //calc lock and boosted amount uint256 spendAmount = _amount.mul(_spendRatio).div(denominator); uint256 boostRatio = boostRate.mul(_spendRatio).div( maximumBoostPayment == 0 ? 1 : maximumBoostPayment ); uint112 lockAmount = _amount.sub(spendAmount).to112(); uint112 boostedAmount = _amount .add(_amount.mul(boostRatio).div(denominator)) .to112(); //add user balances bal.locked = bal.locked.add(lockAmount); bal.boosted = bal.boosted.add(boostedAmount); //add to total supplies lockedSupply = lockedSupply.add(lockAmount); boostedSupply = boostedSupply.add(boostedAmount); //add user lock records or add to current uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); //if a fresh lock, add on an extra duration period if (!_isRelock) { lockEpoch = lockEpoch.add(rewardsDuration); } uint256 unlockTime = lockEpoch.add(lockDuration); uint256 idx = userLocks[_account].length; //if the latest user lock is smaller than this lock, always just add new entry to the end of the list if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) { userLocks[_account].push( LockedBalance({ amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime) }) ); } else { //else add to a current lock //if latest lock is further in the future, lower index //this can only happen if relocking an expired lock after creating a new lock if (userLocks[_account][idx - 1].unlockTime > unlockTime) { idx--; } //if idx points to the epoch when same unlock time, update //(this is always true with a normal lock but maybe not with relock) if (userLocks[_account][idx - 1].unlockTime == unlockTime) { LockedBalance storage userL = userLocks[_account][idx - 1]; userL.amount = userL.amount.add(lockAmount); userL.boosted = userL.boosted.add(boostedAmount); } else { //can only enter here if a relock is made after a lock and there's no lock entry //for the current epoch. //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock //length - 1 is the next epoch //length - 2 is a past epoch //thus need to insert an entry for current epoch at the 2nd to last entry //we will copy and insert the tail entry(next) and then overwrite length-2 entry //reset idx idx = userLocks[_account].length; //get current last item LockedBalance storage userL = userLocks[_account][idx - 1]; //add a copy to end of list userLocks[_account].push( LockedBalance({ amount: userL.amount, boosted: userL.boosted, unlockTime: userL.unlockTime }) ); //insert current epoch lock entry by overwriting the entry at length-2 userL.amount = lockAmount; userL.boosted = boostedAmount; userL.unlockTime = uint32(unlockTime); } } //update epoch supply, epoch checkpointed above so safe to add to latest uint256 eIndex = epochs.length - 1; //if relock, epoch should be current and not next, thus need to decrease index to length-2 if (_isRelock) { eIndex--; } Epoch storage e = epochs[eIndex]; e.supply = e.supply.add(uint224(boostedAmount)); //send boost payment if (spendAmount > 0) { stakingToken.safeTransfer(boostPayment, spendAmount); } emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function _processExpiredLocks( address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay ) internal updateReward(_account) { LockedBalance[] storage locks = userLocks[_account]; Balances storage userBalance = balances[_account]; uint112 locked; uint112 boostedAmount; uint256 length = locks.length; uint256 reward = 0; if ( isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay) ) { //if time is beyond last lock, can just bundle everything together locked = userBalance.locked; boostedAmount = userBalance.boosted; //dont delete, just set next index userBalance.nextUnlockIndex = length.to32(); //check for kick reward //this wont have the exact reward rate that you would get if looped through //but this section is supposed to be for quick and easy low gas processing of all locks //we'll assume that if the reward was good enough someone would have processed at an earlier epoch if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[length - 1].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = uint256(locks[length - 1].amount).mul(rRate).div( denominator ); } } else { //use a processed index(nextUnlockIndex) to not loop as much //deleting does not change array length uint32 nextUnlockIndex = userBalance.nextUnlockIndex; for (uint256 i = nextUnlockIndex; i < length; i++) { //unlock time must be less or equal to time if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break; //add to cumulative amounts locked = locked.add(locks[i].amount); boostedAmount = boostedAmount.add(locks[i].boosted); //check for kick reward //each epoch over due increases reward if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[i].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator) ); } //set next unlock index nextUnlockIndex++; } //update next unlock index userBalance.nextUnlockIndex = nextUnlockIndex; } require(locked > 0, "no exp locks"); //update user balances and total supplies userBalance.locked = userBalance.locked.sub(locked); userBalance.boosted = userBalance.boosted.sub(boostedAmount); lockedSupply = lockedSupply.sub(locked); boostedSupply = boostedSupply.sub(boostedAmount); emit Withdrawn(_account, locked, _relock); //send process incentive if (reward > 0) { //if theres a reward(kicked), it will always be a withdraw only //preallocate enough cvx from stake contract to pay for both reward and withdraw allocateCVXForTransfer(uint256(locked)); //reduce return amount by the kick reward locked = locked.sub(reward.to112()); //transfer reward transferCVX(_rewardAddress, reward, false); emit KickReward(_rewardAddress, _account, reward); } else if (_spendRatio > 0) { //preallocate enough cvx to transfer the boost cost allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) ); } //relock or return to user if (_relock) { _lock(_withdrawTo, locked, _spendRatio, true); } else { transferCVX(_withdrawTo, locked, true); } } // withdraw expired locks to a different address function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0); } // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0); } function kickExpiredLocks(address _account) external nonReentrant gacPausable { //allow kick after grace period of 'kickRewardEpochDelay' _processExpiredLocks( _account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay) ); } //pull required amount of cvx from staking for an upcoming transfer // dev: no-op function allocateCVXForTransfer(uint256 _amount) internal { uint256 balance = stakingToken.balanceOf(address(this)); } //transfer helper: pull enough from staking, transfer, updating staking ratio function transferCVX( address _account, uint256 _amount, bool _updateStake ) internal { //allocate enough cvx from staking for the transfer allocateCVXForTransfer(_amount); //transfer stakingToken.safeTransfer(_account, _amount); } //calculate how much cvx should be staked. update if needed function updateStakeRatio(uint256 _offset) internal { if (isShutdown) return; //get balances uint256 local = stakingToken.balanceOf(address(this)); uint256 staked = IStakingProxy(stakingProxy).getBalance(); uint256 total = local.add(staked); if (total == 0) return; //current staked ratio uint256 ratio = staked.mul(denominator).div(total); //mean will be where we reset to if unbalanced uint256 mean = maximumStake.add(minimumStake).div(2); uint256 max = maximumStake.add(_offset); uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset); if (ratio > max) { //remove uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove); } else if (ratio < min) { //add uint256 increase = total.mul(mean).div(denominator).sub(staked); stakingToken.safeTransfer(stakingProxy, increase); IStakingProxy(stakingProxy).stake(); } } // Claim all pending rewards function getReward(address _account, bool _stake) public nonReentrant gacPausable updateReward(_account) { for (uint256 i; i < rewardTokens.length; i++) { address _rewardsToken = rewardTokens[i]; uint256 reward = rewards[_account][_rewardsToken]; if (reward > 0) { rewards[_account][_rewardsToken] = 0; IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward); cumulativeClaimed[_account][_rewardsToken] += reward; emit RewardPaid(_account, _rewardsToken, reward); } } } // claim all pending rewards function getReward(address _account) external { getReward(_account, false); } /* ========== RESTRICTED FUNCTIONS ========== */ function _notifyReward(address _rewardsToken, uint256 _reward) internal { Reward storage rdata = rewardData[_rewardsToken]; if (block.timestamp >= rdata.periodFinish) { rdata.rewardRate = _reward.div(rewardsDuration).to208(); } else { uint256 remaining = uint256(rdata.periodFinish).sub( block.timestamp ); uint256 leftover = remaining.mul(rdata.rewardRate); rdata.rewardRate = _reward .add(leftover) .div(rewardsDuration) .to208(); } rdata.lastUpdateTime = block.timestamp.to40(); rdata.periodFinish = block.timestamp.add(rewardsDuration).to40(); } function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { notifyRewardAmount(_rewardsToken, _reward, bytes32(0)); } function notifyRewardAmount( address _rewardsToken, uint256 _reward, bytes32 _dataTypeHash ) public gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the _reward amount IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); cumulativeDistributed[_rewardsToken] += _reward; emit RewardAdded( msg.sender, _rewardsToken, _reward, _dataTypeHash, block.timestamp ); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); // Will revert if no treasury governance role allocated address treasury = gac.getRoleMember(TREASURY_GOVERNANCE_ROLE, 0); require( _tokenAddress != address(stakingToken), "Cannot withdraw staking token" ); require( rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer(treasury, _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /* ========== MODIFIERS ========== */ modifier updateReward(address _account) { { //stack too deep Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < rewardTokens.length; i++) { address token = rewardTokens[i]; rewardData[token].rewardPerTokenStored = _rewardPerToken(token) .to208(); rewardData[token].lastUpdateTime = _lastTimeRewardApplicable( rewardData[token].periodFinish ).to40(); if (_account != address(0)) { //check if reward is boostable or not. use boosted or locked balance accordingly rewards[_account][token] = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); userRewardPerTokenPaid[_account][token] = rewardData[token] .rewardPerTokenStored; } } } _; } /* ========== EVENTS ========== */ event RewardAdded( address account, address indexed _token, uint256 _reward, bytes32 _dataTypeHash, uint256 _timestamp ); event Staked( address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount ); event Withdrawn(address indexed _user, uint256 _amount, bool _relocked); event KickReward( address indexed _user, address indexed _kicked, uint256 _reward ); event RewardPaid( address indexed _user, address indexed _rewardsToken, uint256 _reward ); event Recovered(address _token, uint256 _amount); }
Add a new reward token to be distributed to stakers require(_rewardsToken != address(stakingToken));
function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public gacPausable { _onlyRole(CONTRACT_GOVERNANCE_ROLE); require(rewardData[_rewardsToken].lastUpdateTime == 0); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; }
5,949,447
[ 1, 986, 279, 394, 19890, 1147, 358, 506, 16859, 358, 384, 581, 414, 2583, 24899, 266, 6397, 1345, 480, 1758, 12, 334, 6159, 1345, 10019, 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, 527, 17631, 1060, 12, 203, 3639, 1758, 389, 266, 6397, 1345, 16, 203, 3639, 1758, 389, 2251, 19293, 16, 203, 3639, 1426, 389, 1202, 26653, 203, 565, 262, 1071, 314, 1077, 16507, 16665, 288, 203, 3639, 389, 3700, 2996, 12, 6067, 2849, 1268, 67, 43, 12959, 50, 4722, 67, 16256, 1769, 203, 3639, 2583, 12, 266, 2913, 751, 63, 67, 266, 6397, 1345, 8009, 2722, 1891, 950, 422, 374, 1769, 203, 3639, 19890, 5157, 18, 6206, 24899, 266, 6397, 1345, 1769, 203, 3639, 19890, 751, 63, 67, 266, 6397, 1345, 8009, 2722, 1891, 950, 273, 2254, 7132, 12, 2629, 18, 5508, 1769, 203, 3639, 19890, 751, 63, 67, 266, 6397, 1345, 8009, 6908, 11641, 273, 2254, 7132, 12, 2629, 18, 5508, 1769, 203, 3639, 19890, 751, 63, 67, 266, 6397, 1345, 8009, 1202, 26653, 273, 389, 1202, 26653, 31, 203, 3639, 19890, 1669, 665, 13595, 63, 67, 266, 6397, 1345, 6362, 67, 2251, 19293, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.7.4; pragma experimental ABIEncoderV2; import "../utils/Ownable.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155PackedBalance/ERC1155MintBurnPackedBalance.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155Metadata.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC2981/ERC2981Global.sol"; import "@0xsequence/erc-1155/contracts/utils/SafeMath.sol"; /** * ERC-1155 token contract for skyweaver assets. * This contract manages the various SW asset factories * and ensures that each factory has constraint access in * terms of the id space they are allowed to mint. * @dev Mint permissions use range because factory contracts * could be minting large numbers of NFTs or be built * with granular, but efficient permission checks. */ contract SkyweaverAssets is ERC1155MintBurnPackedBalance, ERC1155Metadata, ERC2981Global, Ownable { using SafeMath for uint256; /***********************************| | Variables | |__________________________________*/ // Factory mapping variables mapping(address => bool) internal isFactoryActive; // Whether an address can print tokens or not mapping(address => AssetRange[]) internal mintAccessRanges; // Contains the ID ranges factories are allowed to mint AssetRange[] internal lockedRanges; // Ranges of IDs that can't be granted permission to mint // Issuance mapping variables mapping (uint256 => uint256) internal currentIssuance; // Current Issuance of token for tokens that have max issuance ONLY mapping (uint256 => uint256) internal maxIssuance; // Issuance is counted and capped to associated maxIssuance if it's non-zero // Struct for mint ID ranges permissions struct AssetRange { uint64 minID; // Minimum value the ID need to be to fall in the range uint64 maxID; // Maximum value the ID need to be to fall in the range uint64 startTime; // Timestamp when the range becomes valid uint64 endTime; // Timestamp after which the range is no longer valid } /***********************************| | Events | |__________________________________*/ event FactoryActivation(address indexed factory); event FactoryShutdown(address indexed factory); event MaxIssuancesChanged(uint256[] ids, uint256[] newMaxIssuances); event MintPermissionAdded(address indexed factory, AssetRange new_range); event MintPermissionRemoved(address indexed factory, AssetRange deleted_range); event RangeLocked(AssetRange locked_range); /***********************************| | Constuctor | |__________________________________*/ constructor (address _firstOwner) ERC1155Metadata("Skyweaver", "") Ownable(_firstOwner) public {} /***********************************| | Factory Management Methods | |__________________________________*/ /** * @notice Will ALLOW factory to print some assets specified in `canPrint` mapping * @param _factory Address of the factory to activate */ function activateFactory(address _factory) external onlyOwner() { isFactoryActive[_factory] = true; emit FactoryActivation(_factory); } /** * @notice Will DISALLOW factory to print any asset * @param _factory Address of the factory to shutdown */ function shutdownFactory(address _factory) external onlyOwner() { isFactoryActive[_factory] = false; emit FactoryShutdown(_factory); } /** * @notice Will allow a factory to mint some token ids * @param _factory Address of the factory to update permission * @param _minRange Minimum ID (inclusive) in id range that factory will be able to mint * @param _maxRange Maximum ID (inclusive) in id range that factory will be able to mint * @param _startTime Timestamp when the range becomes valid * @param _endTime Timestamp after which the range is no longer valid */ function addMintPermission(address _factory, uint64 _minRange, uint64 _maxRange, uint64 _startTime, uint64 _endTime) external onlyOwner() { require(_maxRange > 0, "SkyweaverAssets#addMintPermission: NULL_RANGE"); require(_minRange <= _maxRange, "SkyweaverAssets#addMintPermission: INVALID_RANGE"); require(_startTime < _endTime, "SkyweaverAssets#addMintPermission: START_TIME_IS_NOT_LESSER_THEN_END_TIME"); // Check if new range has an overlap with locked ranges. // lockedRanges is expected to be a small array for (uint256 i = 0; i < lockedRanges.length; i++) { AssetRange memory locked_range = lockedRanges[i]; require( (_maxRange < locked_range.minID) || (locked_range.maxID < _minRange), "SkyweaverAssets#addMintPermission: OVERLAP_WITH_LOCKED_RANGE" ); } // Create and store range struct for _factory AssetRange memory range = AssetRange(_minRange, _maxRange, _startTime, _endTime); mintAccessRanges[_factory].push(range); emit MintPermissionAdded(_factory, range); } /** * @notice Will remove the permission a factory has to mint some token ids * @param _factory Address of the factory to update permission * @param _rangeIndex Array's index where the range to delete is located for _factory */ function removeMintPermission(address _factory, uint256 _rangeIndex) external onlyOwner() { // Will take the last range and put it where the "hole" will be after // the AssetRange struct at _rangeIndex is deleted uint256 last_index = mintAccessRanges[_factory].length - 1; // won't underflow because of require() statement above AssetRange memory range_to_delete = mintAccessRanges[_factory][_rangeIndex]; // Stored for log if (_rangeIndex != last_index) { AssetRange memory last_range = mintAccessRanges[_factory][last_index]; // Retrieve the range that will be moved mintAccessRanges[_factory][_rangeIndex] = last_range; // Overwrite the "to-be-deleted" range } // Delete last element of the array mintAccessRanges[_factory].pop(); emit MintPermissionRemoved(_factory, range_to_delete); } /** * @notice Will forever prevent new mint permissions for provided ids * @dev THIS ACTION IS IRREVERSIBLE, USE WITH CAUTION * @dev In order to forever restrict minting of certain ids to a set of factories, * one first needs to call `addMintPermission()` for the corresponding factory * and the corresponding ids, then call this method to prevent further mint * permissions to be granted. One can also remove mint permissions after ids * mint permissions where locked down. * @param _range AssetRange struct for range of asset that can't be granted * new mint permission to */ function lockRangeMintPermissions(AssetRange memory _range) public onlyOwner() { lockedRanges.push(_range); emit RangeLocked(_range); } /***********************************| | Supplies Management Methods | |__________________________________*/ /** * @notice Set max issuance for some token IDs that can't ever be increased * @dev Can only decrease the max issuance if already set, but can't set it *back* to 0. * @param _ids Array of token IDs to set the max issuance * @param _newMaxIssuances Array of max issuances for each corresponding ID */ function setMaxIssuances(uint256[] calldata _ids, uint256[] calldata _newMaxIssuances) external onlyOwner() { require(_ids.length == _newMaxIssuances.length, "SkyweaverAssets#setMaxIssuances: INVALID_ARRAYS_LENGTH"); // Can only *decrease* a max issuance // Can't set max issuance back to 0 for (uint256 i = 0; i < _ids.length; i++ ) { if (maxIssuance[_ids[i]] > 0) { require( 0 < _newMaxIssuances[i] && _newMaxIssuances[i] < maxIssuance[_ids[i]], "SkyweaverAssets#setMaxIssuances: INVALID_NEW_MAX_ISSUANCE" ); } maxIssuance[_ids[i]] = _newMaxIssuances[i]; } emit MaxIssuancesChanged(_ids, _newMaxIssuances); } /***********************************| | Royalty Management Methods | |__________________________________*/ /** * @notice Will set the basis point and royalty recipient that is applied to all Skyweaver assets * @param _receiver Fee recipient that will receive the royalty payments * @param _royaltyBasisPoints Basis points with 3 decimals representing the fee % * e.g. a fee of 2% would be 20 (i.e. 20 / 1000 == 0.02, or 2%) */ function setGlobalRoyaltyInfo(address _receiver, uint256 _royaltyBasisPoints) external onlyOwner() { _setGlobalRoyaltyInfo(_receiver, _royaltyBasisPoints); } /***********************************| | Receiver Method Handler | |__________________________________*/ /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("UNSUPPORTED_METHOD"); } /***********************************| | Minting Function | |__________________________________*/ /** * @notice Mint tokens for each ids in _ids * @dev This methods assumes ids are sorted by how the ranges are sorted in * the corresponding mintAccessRanges[msg.sender] array. Call might throw * if they are not. * @param _to The address to mint tokens to. * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Byte array of data to pass to recipient if it's a contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Validate assets to be minted _validateMints(_ids, _amounts); // If hasn't reverted yet, all IDs are allowed for factory _batchMint(_to, _ids, _amounts, _data); } /** * @notice Mint _amount of tokens of a given id, if allowed. * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function mint(address _to, uint256 _id, uint256 _amount, bytes calldata _data) external { // Put into array for validation uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; // Validate and mint _validateMints(ids, amounts); _mint(_to, _id, _amount, _data); } /** * @notice Will validate the ids and amounts to mint * @dev This methods assumes ids are sorted by how the ranges are sorted in * the corresponding mintAccessRanges[msg.sender] array. Call will revert * if they are not. * @dev When the maxIssuance of an asset is set to a non-zero value, the * supply manager contract will start keeping track of how many of that * token are minted, until the maxIssuance hit. * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id */ function _validateMints(uint256[] memory _ids, uint256[] memory _amounts) internal { require(isFactoryActive[msg.sender], "SkyweaverAssets#_validateMints: FACTORY_NOT_ACTIVE"); // Number of mint ranges uint256 n_ranges = mintAccessRanges[msg.sender].length; // Load factory's default range AssetRange memory range = mintAccessRanges[msg.sender][0]; uint256 range_index = 0; // Will make sure that factory is allowed to print all ids // and that no max issuance is exceeded for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; uint256 amount = _amounts[i]; uint256 max_issuance = maxIssuance[id]; // If ID is out of current range, move to next range, else skip. // This function only moves forwards in the AssetRange array, // hence if _ids are not sorted correctly, the call will fail. while (block.timestamp < range.startTime || block.timestamp > range.endTime || id < range.minID || range.maxID < id) { range_index += 1; // Load next range. If none left, ID is assumed to be out of all ranges require(range_index < n_ranges, "SkyweaverAssets#_validateMints: ID_OUT_OF_RANGE"); range = mintAccessRanges[msg.sender][range_index]; } // If max supply is specified for id if (max_issuance > 0) { uint256 new_current_issuance = currentIssuance[id].add(amount); require(new_current_issuance <= max_issuance, "SkyweaverAssets#_validateMints: MAX_ISSUANCE_EXCEEDED"); currentIssuance[id] = new_current_issuance; } } } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get the max issuance of multiple asset IDs * @dev The max issuance of a token does not reflect the maximum supply, only * how many tokens can be minted once the maxIssuance for a token is set. * @param _ids Array containing the assets IDs * @return The current max issuance of each asset ID in _ids */ function getMaxIssuances(uint256[] calldata _ids) external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory max_issuances = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { max_issuances[i] = maxIssuance[_ids[i]]; } return max_issuances; } /** * @notice Get the current issuanc of multiple asset ID * @dev The current issuance of a token does not reflect the current supply, only * how many tokens since a max issuance was set for a given token id. * @param _ids Array containing the assets IDs * @return The current issuance of each asset ID in _ids */ function getCurrentIssuances(uint256[] calldata _ids) external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory current_issuances = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { current_issuances[i] = currentIssuance[_ids[i]]; } return current_issuances; } /** * @return Returns whether a factory is active or not */ function getFactoryStatus(address _factory) external view returns (bool) { return isFactoryActive[_factory]; } /** * @return Returns whether the sale has ended or not */ function getFactoryAccessRanges(address _factory) external view returns (AssetRange[] memory) { return mintAccessRanges[_factory]; } /** * @return Returns all the ranges that are locked */ function getLockedRanges() external view returns (AssetRange[] memory) { return lockedRanges; } /***********************************| | Burning Functions | |__________________________________*/ /** * @notice Burn _amount of tokens of a given id from msg.sender * @dev This will not change the current issuance tracked in _supplyManagerAddr. * @param _id Asset id to burn * @param _amount The amount to be burn */ function burn( uint256 _id, uint256 _amount) external { _burn(msg.sender, _id, _amount); } /** * @notice Burn _amounts of tokens of given ids from msg.sender * @dev This will not change the current issuance tracked in _supplyManagerAddr. * @param _ids Asset id to burn * @param _amounts The amount to be burn */ function batchBurn( uint256[] calldata _ids, uint256[] calldata _amounts) external { _batchBurn(msg.sender, _ids, _amounts); } /***********************************| | URI Functions | |__________________________________*/ /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string calldata _newBaseMetadataURI) external onlyOwner() { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function logURIs(uint256[] calldata _tokenIDs) external onlyOwner() { _logURIs(_tokenIDs); } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) public override(ERC1155PackedBalance, ERC1155Metadata, ERC2981Global) virtual pure returns (bool) { return super.supportsInterface(_interfaceID); } }
* @notice Will validate the ids and amounts to mint @dev This methods assumes ids are sorted by how the ranges are sorted in the corresponding mintAccessRanges[msg.sender] array. Call will revert if they are not. @dev When the maxIssuance of an asset is set to a non-zero value, the supply manager contract will start keeping track of how many of that token are minted, until the maxIssuance hit. @param _ids Array of ids to mint @param _amounts Array of amount of tokens to mint per id/ Number of mint ranges Load factory's default range Will make sure that factory is allowed to print all ids and that no max issuance is exceeded If ID is out of current range, move to next range, else skip. This function only moves forwards in the AssetRange array, hence if _ids are not sorted correctly, the call will fail. Load next range. If none left, ID is assumed to be out of all ranges If max supply is specified for id
function _validateMints(uint256[] memory _ids, uint256[] memory _amounts) internal { require(isFactoryActive[msg.sender], "SkyweaverAssets#_validateMints: FACTORY_NOT_ACTIVE"); uint256 n_ranges = mintAccessRanges[msg.sender].length; AssetRange memory range = mintAccessRanges[msg.sender][0]; uint256 range_index = 0; for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; uint256 amount = _amounts[i]; uint256 max_issuance = maxIssuance[id]; while (block.timestamp < range.startTime || block.timestamp > range.endTime || id < range.minID || range.maxID < id) { range_index += 1; require(range_index < n_ranges, "SkyweaverAssets#_validateMints: ID_OUT_OF_RANGE"); range = mintAccessRanges[msg.sender][range_index]; } if (max_issuance > 0) { uint256 new_current_issuance = currentIssuance[id].add(amount); require(new_current_issuance <= max_issuance, "SkyweaverAssets#_validateMints: MAX_ISSUANCE_EXCEEDED"); currentIssuance[id] = new_current_issuance; } } } |__________________________________*/
1,764,905
[ 1, 13670, 1954, 326, 3258, 471, 30980, 358, 312, 474, 225, 1220, 2590, 13041, 3258, 854, 3115, 635, 3661, 326, 7322, 854, 3115, 316, 1377, 326, 4656, 312, 474, 1862, 9932, 63, 3576, 18, 15330, 65, 526, 18, 3049, 903, 15226, 1377, 309, 2898, 854, 486, 18, 225, 5203, 326, 943, 7568, 89, 1359, 434, 392, 3310, 353, 444, 358, 279, 1661, 17, 7124, 460, 16, 326, 1377, 14467, 3301, 6835, 903, 787, 19966, 3298, 434, 3661, 4906, 434, 716, 1377, 1147, 854, 312, 474, 329, 16, 3180, 326, 943, 7568, 89, 1359, 6800, 18, 225, 389, 2232, 377, 1510, 434, 3258, 358, 312, 474, 225, 389, 8949, 87, 1510, 434, 3844, 434, 2430, 358, 312, 474, 1534, 612, 19, 3588, 434, 312, 474, 7322, 4444, 3272, 1807, 805, 1048, 9980, 1221, 3071, 716, 3272, 353, 2935, 358, 1172, 777, 3258, 471, 716, 1158, 943, 3385, 89, 1359, 353, 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, 225, 445, 389, 5662, 49, 28142, 12, 11890, 5034, 8526, 3778, 389, 2232, 16, 2254, 5034, 8526, 3778, 389, 8949, 87, 13, 2713, 288, 203, 565, 2583, 12, 291, 1733, 3896, 63, 3576, 18, 15330, 6487, 315, 5925, 93, 1814, 21851, 10726, 7, 67, 5662, 49, 28142, 30, 26724, 3964, 67, 4400, 67, 13301, 8863, 203, 203, 565, 2254, 5034, 290, 67, 14530, 273, 312, 474, 1862, 9932, 63, 3576, 18, 15330, 8009, 2469, 31, 203, 203, 565, 10494, 2655, 3778, 1048, 273, 312, 474, 1862, 9932, 63, 3576, 18, 15330, 6362, 20, 15533, 203, 565, 2254, 5034, 1048, 67, 1615, 273, 374, 31, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2232, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 5034, 612, 273, 389, 2232, 63, 77, 15533, 203, 1377, 2254, 5034, 3844, 273, 389, 8949, 87, 63, 77, 15533, 203, 1377, 2254, 5034, 943, 67, 1054, 89, 1359, 273, 943, 7568, 89, 1359, 63, 350, 15533, 203, 203, 1377, 1323, 261, 2629, 18, 5508, 411, 1048, 18, 1937, 950, 747, 1203, 18, 5508, 405, 1048, 18, 409, 950, 747, 612, 411, 1048, 18, 1154, 734, 747, 1048, 18, 1896, 734, 411, 612, 13, 288, 203, 3639, 1048, 67, 1615, 1011, 404, 31, 203, 203, 3639, 2583, 12, 3676, 67, 1615, 411, 290, 67, 14530, 16, 315, 5925, 93, 1814, 21851, 10726, 7, 67, 5662, 49, 28142, 30, 1599, 67, 5069, 67, 3932, 67, 15928, 8863, 203, 3639, 1048, 273, 312, 474, 1862, 9932, 63, 3576, 2 ]
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
@dev Reads the bytes27 at `cdPtr` in calldata.
function readBytes27( CalldataPointer cdPtr ) internal pure returns (bytes27 value) { assembly ("memory-safe") { value := calldataload(cdPtr) } }
8,451,659
[ 1, 7483, 326, 1731, 5324, 622, 1375, 4315, 5263, 68, 316, 745, 892, 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 ]
[ 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, 25825, 5324, 12, 203, 3639, 3049, 892, 4926, 7976, 5263, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 5324, 460, 13, 288, 203, 3639, 19931, 7566, 7858, 17, 4626, 7923, 288, 203, 5411, 460, 519, 745, 72, 3145, 6189, 12, 4315, 5263, 13, 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 ]
./partial_match/1/0x1e2F9D0D9b68171948B7da5233b8826aF0abcdFd/sources/Goliath.sol
set as marketing wallet
marketingWallet = address(0xD899D0CC6ce8620123901096A7b7285D8B09Fcfd);
15,520,629
[ 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, 17593, 28, 2733, 40, 20, 6743, 26, 311, 5292, 6734, 4366, 29, 1611, 5908, 26, 37, 27, 70, 27, 6030, 25, 40, 28, 38, 5908, 42, 71, 8313, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./lib/Owned.sol"; import "./Interfaces/IStaking.sol"; import "./Interfaces/IRewardsManager.sol"; import "./Interfaces/IRewardsEscrow.sol"; import "./Defended.sol"; contract Staking is IStaking, Owned, ReentrancyGuard, Defended { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ struct LockedBalance { uint256 _balance; uint256 _end; } IERC20 public immutable POP; IRewardsManager public RewardsManager; IRewardsEscrow public RewardsEscrow; bool public initialised = false; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public totalLocked; uint256 public totalVoiceCredits; mapping(address => uint256) public voiceCredits; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => LockedBalance) public lockedBalances; /* ========== EVENTS ========== */ event StakingDeposited(address _address, uint256 amount); event StakingWithdrawn(address _address, uint256 amount); event RewardPaid(address _address, uint256 reward); event RewardAdded(uint256 reward); event RewardsManagerChanged(IRewardsManager _rewardsManager); event RewardsEscrowChanged(IRewardsEscrow _rewardsEscrow); /* ========== CONSTRUCTOR ========== */ constructor(IERC20 _pop, IRewardsEscrow _rewardsEscrow) Owned(msg.sender) { POP = _pop; RewardsEscrow = _rewardsEscrow; } /* ========== VIEWS ========== */ /** * @notice this returns the current voice credit balance of an address. voice credits decays over time. the amount returned is up to date, whereas the amount stored in `public voiceCredits` is saved only during some checkpoints. * @dev todo - check if multiplier is needed for calculating square root of smaller balances * @param _address address to get voice credits for */ function getVoiceCredits(address _address) public view override returns (uint256) { uint256 lockEndTime = lockedBalances[_address]._end; uint256 balance = lockedBalances[_address]._balance; uint256 currentTime = block.timestamp; if (lockEndTime == 0 || lockEndTime < currentTime || balance == 0) { return 0; } uint256 timeTillEnd = ((lockEndTime.sub(currentTime)).div(1 hours)).mul( 1 hours ); return balance.mul(timeTillEnd).div(4 * 365 days); } function getWithdrawableBalance(address _address) public view override returns (uint256) { uint256 _withdrawable = 0; uint256 _currentTime = block.timestamp; if (lockedBalances[_address]._end <= _currentTime) { _withdrawable = lockedBalances[_address]._balance; } return _withdrawable; } function balanceOf(address _address) external view returns (uint256) { return lockedBalances[_address]._balance; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalLocked == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalLocked) ); } function earned(address account) public view returns (uint256) { return lockedBalances[account] ._balance .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount, uint256 lengthOfTime) external override nonReentrant defend isInitialised updateReward(msg.sender) { uint256 _currentTime = block.timestamp; require(amount > 0, "amount must be greater than 0"); require(lengthOfTime >= 7 days, "must lock tokens for at least 1 week"); require( lengthOfTime <= 365 * 4 days, "must lock tokens for less than/equal to 4 year" ); require(POP.balanceOf(msg.sender) >= amount, "insufficient balance"); require(lockedBalances[msg.sender]._balance == 0, "withdraw balance first"); POP.safeTransferFrom(msg.sender, address(this), amount); totalLocked = totalLocked.add(amount); _lockTokens(amount, lengthOfTime); recalculateVoiceCredits(msg.sender); emit StakingDeposited(msg.sender, amount); } function increaseLock(uint256 lengthOfTime) external { uint256 _currentTime = block.timestamp; require(lengthOfTime >= 7 days, "must lock tokens for at least 1 week"); require( lengthOfTime <= 365 * 4 days, "must lock tokens for less than/equal to 4 year" ); require(lockedBalances[msg.sender]._balance > 0, "no lockedBalance exists"); require( lockedBalances[msg.sender]._end > _currentTime, "withdraw balance first" ); lockedBalances[msg.sender]._end = lockedBalances[msg.sender]._end.add( lengthOfTime ); recalculateVoiceCredits(msg.sender); } function increaseStake(uint256 amount) external { uint256 _currentTime = block.timestamp; require(amount > 0, "amount must be greater than 0"); require(POP.balanceOf(msg.sender) >= amount, "insufficient balance"); require(lockedBalances[msg.sender]._balance > 0, "no lockedBalance exists"); require( lockedBalances[msg.sender]._end > _currentTime, "withdraw balance first" ); POP.safeTransferFrom(msg.sender, address(this), amount); totalLocked = totalLocked.add(amount); lockedBalances[msg.sender]._balance = lockedBalances[msg.sender] ._balance .add(amount); recalculateVoiceCredits(msg.sender); } function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) { require(amount > 0, "amount must be greater than 0"); require(lockedBalances[msg.sender]._balance > 0, "insufficient balance"); require(amount <= getWithdrawableBalance(msg.sender)); POP.safeTransfer(msg.sender, amount); totalLocked = totalLocked.sub(amount); _clearWithdrawnFromLocked(amount); recalculateVoiceCredits(msg.sender); emit StakingWithdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; //How to handle missing gwei? uint256 payout = reward.div(uint256(3)); uint256 escrowed = payout.mul(uint256(2)); POP.safeTransfer(msg.sender, payout); POP.safeIncreaseAllowance(address(RewardsEscrow), escrowed); RewardsEscrow.lock(msg.sender, escrowed); emit RewardPaid(msg.sender, payout); } } function exit() external { withdraw(getWithdrawableBalance(msg.sender)); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function init(IRewardsManager _rewardsManager) external onlyOwner { RewardsManager = _rewardsManager; initialised = true; } // todo: multiply voice credits by 10000 to deal with exponent math- is it needed? function recalculateVoiceCredits(address _address) public { uint256 previousVoiceCredits = voiceCredits[_address]; totalVoiceCredits = totalVoiceCredits.sub(previousVoiceCredits); voiceCredits[_address] = getVoiceCredits(_address); totalVoiceCredits = totalVoiceCredits.add(voiceCredits[_address]); } function _lockTokens(uint256 amount, uint256 lengthOfTime) internal { uint256 _currentTime = block.timestamp; if (_currentTime > lockedBalances[msg.sender]._end) { lockedBalances[msg.sender] = LockedBalance({ _balance: lockedBalances[msg.sender]._balance.add(amount), _end: _currentTime.add(lengthOfTime) }); } else { lockedBalances[msg.sender] = LockedBalance({ _balance: lockedBalances[msg.sender]._balance.add(amount), _end: lockedBalances[msg.sender]._end.add(lengthOfTime) }); } } function _clearWithdrawnFromLocked(uint256 _amount) internal { uint256 _currentTime = block.timestamp; if (lockedBalances[msg.sender]._end <= _currentTime) { if (_amount == lockedBalances[msg.sender]._balance) { delete lockedBalances[msg.sender]; } else { lockedBalances[msg.sender]._balance = lockedBalances[msg.sender] ._balance .sub(_amount); } } } function setRewardsManager(IRewardsManager _rewardsManager) external onlyOwner { require(RewardsManager != _rewardsManager, "Same RewardsManager"); RewardsManager = _rewardsManager; emit RewardsManagerChanged(_rewardsManager); } function setRewardsEscrow(IRewardsEscrow _rewardsEscrow) external onlyOwner { require(RewardsEscrow != _rewardsEscrow, "Same RewardsEscrow"); RewardsEscrow = _rewardsEscrow; emit RewardsEscrowChanged(_rewardsEscrow); } function notifyRewardAmount(uint256 reward) external override updateReward(address(0)) isInitialised { require( IRewardsManager(msg.sender) == RewardsManager || msg.sender == owner, "Not allowed" ); if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = POP.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // End rewards emission earlier function updatePeriodFinish(uint256 timestamp) external onlyOwner updateReward(address(0)) { require(timestamp > block.timestamp, "timestamp cant be in the past"); periodFinish = timestamp; } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier isInitialised() { require(initialised == true, "must initialise contract"); _; } }
How to handle missing gwei?
function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; uint256 payout = reward.div(uint256(3)); uint256 escrowed = payout.mul(uint256(2)); POP.safeTransfer(msg.sender, payout); POP.safeIncreaseAllowance(address(RewardsEscrow), escrowed); RewardsEscrow.lock(msg.sender, escrowed); emit RewardPaid(msg.sender, payout); } }
12,582,043
[ 1, 44, 543, 358, 1640, 3315, 314, 1814, 77, 35, 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, 4170, 359, 1060, 1435, 1071, 1661, 426, 8230, 970, 1089, 17631, 1060, 12, 3576, 18, 15330, 13, 288, 203, 565, 2254, 5034, 19890, 273, 283, 6397, 63, 3576, 18, 15330, 15533, 203, 565, 309, 261, 266, 2913, 405, 374, 13, 288, 203, 1377, 283, 6397, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 1377, 2254, 5034, 293, 2012, 273, 19890, 18, 2892, 12, 11890, 5034, 12, 23, 10019, 203, 1377, 2254, 5034, 2904, 492, 329, 273, 293, 2012, 18, 16411, 12, 11890, 5034, 12, 22, 10019, 203, 203, 1377, 26839, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 293, 2012, 1769, 203, 1377, 26839, 18, 4626, 382, 11908, 7009, 1359, 12, 2867, 12, 17631, 14727, 6412, 492, 3631, 2904, 492, 329, 1769, 203, 1377, 534, 359, 14727, 6412, 492, 18, 739, 12, 3576, 18, 15330, 16, 2904, 492, 329, 1769, 203, 203, 1377, 3626, 534, 359, 1060, 16507, 350, 12, 3576, 18, 15330, 16, 293, 2012, 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, -100, -100, -100, -100, -100, -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/0x2B72ED11123cD87D42060Be24C83af43b28FCF55/sources/ThievesList1.sol
Sale Phases Mint Tracking MerkleRoot
contract ThievesList is ERC721A, Ownable, ReentrancyGuard { uint256 public MAX_SUPPLY = 4767; uint256 public MAX_PRESALE_MINTS = 1; uint256 public MAX_PUBLIC_MINTS = 1; uint256 public constant RESERVE_SUPPLY = 267; uint256 public totalReserved; string public _baseTokenURI; string public baseExtension = ".json"; bool public mainSaleActive = false; bool public preSaleActive = false; mapping(address => uint256) public _numberOfPresaleMints; mapping(address => uint256) public _numberOfMints; bytes32 public merkleRoot; pragma solidity ^0.8.4; modifier callerIsUser() { require(tx.origin == msg.sender, "Caller is another contract"); _; } constructor( string memory name, string memory symbol, string memory baseURI, bytes32 merkleRoot_ ) ERC721A(name, symbol) { setBaseURI(baseURI); merkleRoot = merkleRoot_; } function reserveTokens(address to, uint256 numberOfTokens) public onlyOwner { require(totalSupply() + numberOfTokens <= MAX_SUPPLY, "Exceeds max supply"); require(totalReserved + numberOfTokens <= RESERVE_SUPPLY, "Exceeds max reserve supply"); _safeMint(to, numberOfTokens); totalReserved = totalReserved + numberOfTokens; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function setPreSaleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function setMaxSupply(uint256 maxSupply) public onlyOwner { MAX_SUPPLY = maxSupply; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId), baseExtension)) : ""; } function flipPreSaleState() public onlyOwner { preSaleActive = !preSaleActive; } function flipMainSaleState() public onlyOwner { mainSaleActive = !mainSaleActive; } function mintPreSaleTokens(uint256 numberOfTokens, bytes32[] calldata _merkleProof) external payable nonReentrant callerIsUser { require(preSaleActive, "Presale is not open"); require(_numberOfPresaleMints[msg.sender] + numberOfTokens <= MAX_PRESALE_MINTS, "Exceeds the number of allowed mints"); require(numberOfTokens > 0, "Must mint more than at least 1 token"); require(totalSupply() + numberOfTokens <= MAX_SUPPLY, "Exceeds max supply"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid MerkleProof"); _numberOfPresaleMints[msg.sender] = _numberOfPresaleMints[msg.sender] + numberOfTokens; _safeMint(msg.sender, numberOfTokens); } function mintTokens(uint256 numberOfTokens) external nonReentrant callerIsUser { require(mainSaleActive, "Public sale is not open"); require(_numberOfMints[msg.sender] + numberOfTokens <= MAX_PUBLIC_MINTS, "Exceeds the number of allowed mints"); require(numberOfTokens > 0, "Must mint at least 1 token"); require(totalSupply() + numberOfTokens <= MAX_SUPPLY, "Exceeds max supply"); _numberOfMints[msg.sender] = _numberOfMints[msg.sender] + numberOfTokens; _safeMint(msg.sender, numberOfTokens); } function setNumberOfPublicMints(uint256 _mints) public onlyOwner { MAX_PUBLIC_MINTS = _mints; } }
781,171
[ 1, 30746, 4360, 3304, 490, 474, 11065, 310, 31827, 2375, 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, 16351, 935, 1385, 3324, 682, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 203, 565, 2254, 5034, 1071, 4552, 67, 13272, 23893, 273, 1059, 6669, 27, 31, 203, 565, 2254, 5034, 1071, 4552, 67, 3670, 5233, 900, 67, 49, 3217, 55, 273, 404, 31, 203, 565, 2254, 5034, 1071, 4552, 67, 14939, 67, 49, 3217, 55, 273, 404, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 2438, 2123, 3412, 67, 13272, 23893, 273, 576, 9599, 31, 203, 565, 2254, 5034, 1071, 2078, 10435, 31, 203, 203, 565, 533, 1071, 389, 1969, 1345, 3098, 31, 203, 565, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 203, 565, 1426, 1071, 2774, 30746, 3896, 273, 629, 31, 203, 565, 1426, 1071, 675, 30746, 3896, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 389, 2696, 951, 12236, 5349, 49, 28142, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 389, 2696, 951, 49, 28142, 31, 203, 203, 565, 1731, 1578, 1071, 30235, 2375, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 9606, 4894, 2520, 1299, 1435, 288, 203, 3639, 2583, 12, 978, 18, 10012, 422, 1234, 18, 15330, 16, 315, 11095, 353, 4042, 6835, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 533, 3778, 1026, 3098, 16, 203, 3639, 1731, 1578, 30235, 2375, 67, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract StakeContract is Initializable { mapping(bytes32 => uint256) public user_time_created; mapping(bytes32 => uint256) public user_coin_staked; mapping(address => uint256) public user_num_stakes; uint[] private stake_price_by_day; uint256 public daily_award; uint256 public total_coin_staked; uint256 public deploy_time; uint256 public last_award_offset; uint256 public day_length; uint256 public lock_period; uint256 public total_period; address public creaticles_address; bool public fix_applied; uint256 public scale; function fix() public { // can only call this once if (fix_applied == false) { console.log('Applying hotfix'); scale = 100000000000; // a large number to prevent rounding rewards per token down to zero // last_award_offset = 0; // recompute first day awards last_award_offset = 1; delete stake_price_by_day; stake_price_by_day.push(0); // 908643 stake_price_by_day.push((100000 * scale) / 908643); fix_applied = true; } else { console.log('Called again!'); } } function initialize(address _creaticles_address, uint256 _day_length, uint256 _lock_period, uint256 _daily_reward, uint256 _total_period, uint256 _deploy_time) public initializer { creaticles_address = _creaticles_address; stake_price_by_day.push(0); daily_award = _daily_reward; total_coin_staked = 0; total_period = _total_period; day_length = _day_length; deploy_time = _deploy_time; // day last_award_offset = 0; lock_period = _lock_period; scale = 1; // TODO add end to staking period // uint a = 4; // uint b = 5; // uint c = a - b; // console.log(c); } function hash_of_user_stake(address user, uint256 stake_id) private pure returns (bytes32 hash) { return keccak256(abi.encodePacked(user, stake_id)); } function stake(uint256 stake_id, uint256 amount) public returns (uint256 amount_staked) { require(stake_id < 10000, "No more than 10000 stakes per user"); require(block.timestamp <= deploy_time + day_length * total_period, "Cannot stake after end of reward period"); bytes32 user_hash = hash_of_user_stake(msg.sender, stake_id); // add coin to staking - this coin acrues interest each day require(amount > 0, "Cannot stake zero coin"); require(user_coin_staked[user_hash] == 0, "Can only have one stake at once for stake id"); check_increment_day(); // if this next statement succeeds, we will have received Creaticles token payment IERC20(creaticles_address).transferFrom(msg.sender, address(this), amount); total_coin_staked = total_coin_staked + amount; user_coin_staked[user_hash] = amount; user_time_created[user_hash] = block.timestamp > deploy_time ? block.timestamp : deploy_time; // keep track of largest stake id we have seen so far uint256 num_stakes = user_num_stakes[msg.sender]; user_num_stakes[msg.sender] = num_stakes >= stake_id + 1 ? num_stakes : stake_id + 1; return amount; } function unstake(uint256 stake_id, uint256 amount) public returns (uint256 amount_staked) { require(stake_id < 10000, "No more than 10000 stakes per user"); require(scale > 0, "Scale not set, please wait"); bytes32 user_hash = hash_of_user_stake(msg.sender, stake_id); uint256 buy_amount = user_coin_staked[user_hash]; require(amount <= buy_amount, "Cannot unstake more than you staked"); require(amount > 0, "Cannot unstake zero coin"); uint256 profit = 0; // remove coin from staking - if longer than lockup period we acrue interest check_increment_day(); if (block.timestamp > deploy_time) { // offset is number of days since deployment, rounded down uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 buy_offset = (user_time_created[user_hash] - deploy_time) / day_length; uint256 prev_price = stake_price_by_day[buy_offset]; uint256 current_price = stake_price_by_day[current_offset]; profit = amount * (current_price - prev_price) / scale; if (current_offset - buy_offset < lock_period) { profit = 0; // they did not wait long enough, we simply give them their coin back } } console.log("Sending unstake profit: ", profit); user_coin_staked[user_hash] = buy_amount - amount; total_coin_staked = total_coin_staked - amount; IERC20(creaticles_address).transfer(msg.sender, amount + profit); return buy_amount - amount; } function increment_day() internal { // give award to users since we have reached a new day - we award 100k tokens to the community! uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 day_diff = current_offset - last_award_offset; uint256 reward_per_token = 0; if (total_coin_staked > 0) { reward_per_token = (daily_award * scale) / total_coin_staked; } console.log("Old stake price: ", stake_price_by_day[stake_price_by_day.length - 1]); for(uint256 i = 0; i < day_diff; i++) { uint256 prev_price = stake_price_by_day[stake_price_by_day.length - 1]; uint256 new_price = prev_price + reward_per_token; if (stake_price_by_day.length <= total_period) { stake_price_by_day.push(new_price); } else { // once we reach the end of the total period, we stop increasing the daily price (and therefore the profit from withdrawing) stake_price_by_day.push(prev_price); } } console.log("New stake price: ", stake_price_by_day[stake_price_by_day.length - 1]); last_award_offset = current_offset; } function number_of_stakes(address user) public view returns (uint256 num_stakes) { return user_num_stakes[user]; } function check_increment_day() public { // this forces an update of day so we can check interest if (block.timestamp >= deploy_time) { uint256 current_offset = (block.timestamp - deploy_time) / day_length; console.log("Number of days since deployment: ", current_offset); if (current_offset > last_award_offset) { increment_day(); } } } function profile(address user, uint256 stake_id) public view returns (uint256 timestamp, uint256 tokens_staked, uint256 interest, bool locked) { // show information about staked coin for a user address // not that interest information only updates after the first user stakes or unstakes on a given day // this function only views interest, does not compute updated interest // require(user_coin_staked[user] > 0, "User must have staked coin to view profile"); require(stake_id < 10000, "No more than 10000 stakes per user"); require(scale > 0, "Scale not set, please wait"); bytes32 user_hash = hash_of_user_stake(user, stake_id); if (user_coin_staked[user_hash] == 0) { return (0, 0, 0, true); } uint256 buy_time = user_time_created[user_hash]; uint256 current_user_coin_staked = user_coin_staked[user_hash]; uint256 profit = 0; bool user_locked = true; if (block.timestamp > deploy_time) { uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 amount = user_coin_staked[user_hash]; uint256 buy_offset = (buy_time - deploy_time) / day_length; uint256 prev_price = stake_price_by_day[buy_offset]; // uint256 current_price = stake_price_by_day[current_offset]; uint256 current_price = stake_price_by_day[stake_price_by_day.length - 1]; user_locked = (current_offset - buy_offset < lock_period); profit = amount * (current_price - prev_price) / scale; } return (buy_time, current_user_coin_staked, profit, user_locked); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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. */ 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 || !_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.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); }
a large number to prevent rounding rewards per token down to zero
scale = 100000000000;
13,424,516
[ 1, 69, 7876, 1300, 358, 5309, 13885, 283, 6397, 1534, 1147, 2588, 358, 3634, 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, 5411, 3159, 273, 15088, 11706, 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 ]
./full_match/42/0xF9FEb88956C2F95e968F7d5388b7D44b1dDb2E01/sources/contracts/optionLiquidityPool.sol
function to mint erc721 tokens to represent option contract ownershipStrike should be in terms of the asset the premium is paid in.requires for them to send money
function mintOption( uint _expiration, uint _amount, uint _strike, uint _slippage, bool _asset ) public { OPTIONFACTORY.createOption(msg.sender, _amount, _expiration, _strike, uint160(msg.sender)); }
16,232,373
[ 1, 915, 358, 312, 474, 6445, 71, 27, 5340, 2430, 358, 2406, 1456, 6835, 23178, 1585, 2547, 1410, 506, 316, 6548, 434, 326, 3310, 326, 23020, 5077, 353, 30591, 316, 18, 18942, 364, 2182, 358, 1366, 15601, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 312, 474, 1895, 12, 2254, 389, 19519, 16, 2254, 389, 8949, 16, 2254, 389, 701, 2547, 16, 2254, 389, 87, 3169, 2433, 16, 1426, 389, 9406, 262, 1071, 288, 203, 3639, 7845, 16193, 18, 2640, 1895, 12, 3576, 18, 15330, 16, 389, 8949, 16, 389, 19519, 16, 389, 701, 2547, 16, 2254, 16874, 12, 3576, 18, 15330, 10019, 203, 565, 289, 203, 377, 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 ]
//Address: 0x5f391f8253475bffa27b2f8544994f9717ab310d //Contract name: CromIco //Balance: 0.94901046 Ether //Verification Date: 11/16/2017 //Transacion Count: 27 // CODE STARTS HERE pragma solidity ^0.4.15; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ClaimableTokens is Ownable { address public claimedTokensWallet; function ClaimableTokens(address targetWallet) { claimedTokensWallet = targetWallet; } function claimTokens(address tokenAddress) public onlyOwner { require(tokenAddress != 0x0); ERC20 claimedToken = ERC20(tokenAddress); uint balance = claimedToken.balanceOf(this); claimedToken.transfer(claimedTokensWallet, balance); } } contract CromToken is Ownable, ERC20, ClaimableTokens { using SafeMath for uint256; string public constant name = "CROM Token"; string public constant symbol = "CROM"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 10 ** 7; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function CromToken() Ownable() ClaimableTokens(msg.sender) { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = totalSupply; } function transfer(address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[msg.sender] >= value); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint256 remaining) { return allowed[owner][spender]; } function balanceOf(address who) public constant returns (uint256) { return balances[who]; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[from] >= value); require(value <= allowed[from][msg.sender]); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); return true; } } contract CromIco is Ownable, ClaimableTokens { using SafeMath for uint256; CromToken public token; // start and end timestamps where investments are allowed (both inclusive) uint public preStartTime; uint public startTime; uint public endTime; // address where funds are collected address public targetWallet; bool public targetWalletVerified; // caps definitions uint256 public constant SOFT_CAP = 8000 ether; uint256 public constant HARD_CAP = 56000 ether; // token price uint256 public constant TOKEN_PRICE = 10 finney; uint public constant BONUS_BATCH = 2 * 10 ** 6; uint public constant BONUS_PERCENTAGE = 25; uint256 public constant MINIMAL_PRE_ICO_INVESTMENT = 10 ether; // ICO duration uint public constant PRE_DURATION = 14 days; uint public constant DURATION = 14 days; // contributions per individual mapping (address => uint256) public balanceOf; // wallets allowed to take part in the pre ico mapping (address => bool) public preIcoMembers; // total amount of funds raised uint256 public amountRaised; uint256 public tokensSold; bool public paused; enum Stages { WalletUnverified, BeforeIco, Payable, AfterIco } enum PayableStages { PreIco, PublicIco } event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Constructor function CromIco(address tokenAddress, address beneficiaryWallet) Ownable() ClaimableTokens(beneficiaryWallet) { token = CromToken(tokenAddress); preStartTime = 1510920000; startTime = preStartTime + PRE_DURATION; endTime = startTime + DURATION; targetWallet = beneficiaryWallet; targetWalletVerified = false; paused = false; } modifier atStage(Stages stage) { require(stage == getCurrentStage()); _; } // fallback function can be used to buy tokens function() payable atStage(Stages.Payable) { buyTokens(); } // low level token purchase function function buyTokens() internal { require(msg.sender != 0x0); require(msg.value > 0); require(!paused); uint256 weiAmount = msg.value; // calculate token amount to be transferred uint256 tokens = calculateTokensAmount(weiAmount); require(tokens > 0); require(token.balanceOf(this) >= tokens); if (PayableStages.PreIco == getPayableStage()) { require(preIcoMembers[msg.sender]); require(weiAmount.add(balanceOf[msg.sender]) >= MINIMAL_PRE_ICO_INVESTMENT); require(tokensSold.add(tokens) <= BONUS_BATCH); } amountRaised = amountRaised.add(weiAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(weiAmount); tokensSold = tokensSold.add(tokens); token.transfer(msg.sender, tokens); TokenPurchase(msg.sender, weiAmount, tokens); } function verifyTargetWallet() public atStage(Stages.WalletUnverified) { require(msg.sender == targetWallet); targetWalletVerified = true; } // add a list of wallets to be allowed to take part in pre ico function addPreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = true; } } // remove a list of wallets to be allowed to take part in pre ico function removePreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = false; } } // @return true if the ICO is in pre ICO phase function isPreIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPreIco = PayableStages.PreIco == getPayableStage(); return isPayable && isPreIco; } // @return true if the public ICO is in progress function isPublicIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPublic = PayableStages.PublicIco == getPayableStage(); return isPayable && isPublic; } // @return true if ICO has ended function hasEnded() public constant returns (bool) { return Stages.AfterIco == getCurrentStage(); } // @return true if the soft cap has been reached function softCapReached() public constant returns (bool) { return amountRaised >= SOFT_CAP; } // withdraw the contributed funds if the ICO has // ended and the goal has not been reached function withdrawFunds() public atStage(Stages.AfterIco) returns(bool) { require(!softCapReached()); require(balanceOf[msg.sender] > 0); uint256 balance = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(balance); return true; } // transfer the raised funds to the target wallet if // the ICO is over and the goal has been reached function finalizeIco() public onlyOwner atStage(Stages.AfterIco) { require(softCapReached()); targetWallet.transfer(this.balance); } function withdrawUnsoldTokens() public onlyOwner atStage(Stages.AfterIco) { token.transfer(targetWallet, token.balanceOf(this)); } function pause() public onlyOwner { require(!paused); paused = true; } function resume() public onlyOwner { require(paused); paused = false; } function changeTargetWallet(address wallet) public onlyOwner { targetWallet = wallet; targetWalletVerified = false; } function calculateTokensAmount(uint256 funds) internal returns (uint256) { uint256 tokens = funds.div(TOKEN_PRICE); if (tokensSold < BONUS_BATCH) { if (tokensSold.add(tokens) > BONUS_BATCH) { uint256 bonusBaseTokens = BONUS_BATCH.mul(100).div(125).sub(tokensSold); tokens = tokens.add(bonusBaseTokens.mul(BONUS_PERCENTAGE).div(100)); } else { tokens = tokens.mul(BONUS_PERCENTAGE + 100).div(100); } } return tokens; } function getCurrentStage() internal constant returns (Stages) { if (!targetWalletVerified) { return Stages.WalletUnverified; } else if (now < preStartTime) { return Stages.BeforeIco; } else if (now < endTime && amountRaised < HARD_CAP) { return Stages.Payable; } else { return Stages.AfterIco; } } function getPayableStage() internal constant returns (PayableStages) { if (now < startTime) { return PayableStages.PreIco; } else { return PayableStages.PublicIco; } } }
transfer the raised funds to the target wallet if the ICO is over and the goal has been reached
function finalizeIco() public onlyOwner atStage(Stages.AfterIco) { require(softCapReached()); targetWallet.transfer(this.balance); }
1,031,422
[ 1, 13866, 326, 11531, 284, 19156, 358, 326, 1018, 9230, 309, 326, 467, 3865, 353, 1879, 471, 326, 17683, 711, 2118, 8675, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 12409, 45, 2894, 1435, 1071, 1338, 5541, 622, 8755, 12, 31359, 18, 4436, 45, 2894, 13, 288, 203, 3639, 2583, 12, 9269, 4664, 23646, 10663, 203, 3639, 1018, 16936, 18, 13866, 12, 2211, 18, 12296, 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 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/drafts/SignedSafeMath.sol pragma solidity ^0.5.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on 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 Adds two signed integers, reverts on 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; } } // File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @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. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/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 is Initializable { // 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @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. * * 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); } // File: @openzeppelin/contracts-ethereum-package/contracts/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. * * [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 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"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @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 ERC20;` 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 { // 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length 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"); } } } // File: @0x/contracts-utils/contracts/src/LibEIP712.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: @0x/contracts-exchange-libs/contracts/src/LibOrder.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibOrder { using LibOrder for Order; // Hash for the EIP712 Order Schema: // keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData,", // "bytes makerFeeAssetData,", // "bytes takerFeeAssetData", // ")" // )) bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH = 0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534; // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's status is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } // solhint-enable max-line-length /// @dev Order information returned by `getOrderInfo()`. struct OrderInfo { OrderStatus orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates the EIP712 typed data hash of an order with a given domain separator. /// @param order The order structure. /// @return EIP712 typed data hash of the order. function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 orderHash) { orderHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, order.getStructHash() ); return orderHash; } /// @dev Calculates EIP712 hash of the order struct. /// @param order The order structure. /// @return EIP712 hash of the order struct. function getStructHash(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH; bytes memory makerAssetData = order.makerAssetData; bytes memory takerAssetData = order.takerAssetData; bytes memory makerFeeAssetData = order.makerFeeAssetData; bytes memory takerFeeAssetData = order.takerFeeAssetData; // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // uint256(order.makerAddress), // uint256(order.takerAddress), // uint256(order.feeRecipientAddress), // uint256(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData), // keccak256(order.makerFeeAssetData), // keccak256(order.takerFeeAssetData) // )); assembly { // Assert order offset (this is an internal error that should never be triggered) if lt(order, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) let pos4 := add(order, 384) let pos5 := add(order, 416) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) let temp4 := mload(pos4) let temp5 := mload(pos5) // Hash in place mstore(pos1, schemaHash) mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData result := keccak256(pos1, 480) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) mstore(pos4, temp4) mstore(pos5, temp5) } return result; } } // File: @0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } // File: @0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } // File: contracts/external/dydx/lib/Account.sol /* Copyright 2019 dYdX Trading 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.17; pragma experimental ABIEncoderV2; /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } // File: contracts/external/dydx/lib/Types.sol /* Copyright 2019 dYdX Trading 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.17; /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } } // File: contracts/external/dydx/Getters.sol /* Copyright 2019 dYdX Trading 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.17; /** * @title Getters * @author dYdX * * Public read-only functions that allow transparency into the state of Solo */ contract Getters { using Types for Types.Par; /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); } // File: contracts/external/dydx/lib/Actions.sol /* Copyright 2019 dYdX Trading 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.17; /** * @title Actions * @author dYdX * * Library that defines and parses valid Actions */ library Actions { // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } // File: contracts/external/dydx/Operation.sol /* Copyright 2019 dYdX Trading 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.17; /** * @title Operation * @author dYdX * * Primary public function for allowing users and contracts to manage accounts within Solo */ contract Operation { /** * The main entry-point to Solo that allows users and contracts to manage accounts. * Take one or more actions on one or more accounts. The msg.sender must be the owner or * operator of all accounts except for those being liquidated, vaporized, or traded with. * One call to operate() is considered a singular "operation". Account collateralization is * ensured only after the completion of the entire operation. * * @param accounts A list of all accounts that will be used in this operation. Cannot contain * duplicates. In each action, the relevant account will be referred-to by its * index in the list. * @param actions An ordered list of all actions that will be taken in this operation. The * actions will be processed in order. */ function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public; } // File: contracts/external/dydx/SoloMargin.sol /* Copyright 2019 dYdX Trading 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.17; /** * @title SoloMargin * @author dYdX * * Main contract that inherits from other contracts */ contract SoloMargin is Getters, Operation { } // File: contracts/lib/pools/DydxPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title DydxPoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @author Richter Brzeski <[email protected]> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from dYdX liquidity pools. */ library DydxPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private SOLO_MARGIN_CONTRACT = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT); uint256 constant private WETH_MARKET_ID = 0; address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT); /** * @dev Returns the fund's balance of the specified currency in the dYdX pool. */ function getBalance() external view returns (uint256) { Account.Info memory account = Account.Info(address(this), 0); (, , Types.Wei[] memory weis) = _soloMargin.getAccountBalances(account); return weis[WETH_MARKET_ID].sign ? weis[WETH_MARKET_ID].value : 0; } /** * @dev Approves WETH to dYdX without spending gas on every deposit. * @param amount Amount of the WETH to approve to dYdX. */ function approve(uint256 amount) external { uint256 allowance = _weth.allowance(address(this), SOLO_MARGIN_CONTRACT); if (allowance == amount) return; if (amount > 0 && allowance > 0) _weth.approve(SOLO_MARGIN_CONTRACT, 0); _weth.approve(SOLO_MARGIN_CONTRACT, amount); } /** * @dev Deposits funds to the dYdX pool. Assumes that you have already approved >= the amount of WETH to dYdX. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _weth.deposit.value(amount)(); Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Deposit, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); } /** * @dev Withdraws funds from the dYdX pool. * @param amount The amount of ETH to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(false, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Withdraw, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); _weth.withdraw(amount); // Convert WETH to ETH } /** * @dev Withdraws all funds from the dYdX pool. */ function withdrawAll() external { Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Par, Types.AssetReference.Target, 0); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Withdraw, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); _weth.withdraw(_weth.balanceOf(address(this))); // Convert WETH to ETH } } // File: contracts/external/compound/CEther.sol /** * Copyright 2020 Compound Labs, Inc. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity 0.5.17; /** * @title Compound's CEther Contract * @notice CToken which wraps Ether * @author Compound */ interface CEther { function mint() external payable; function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOf(address account) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); } // File: contracts/lib/pools/CompoundPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title CompoundPoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @author Richter Brzeski <[email protected]> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from Compound liquidity pools. */ library CompoundPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private cETH_CONTACT_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; CEther constant private _cETHContract = CEther(cETH_CONTACT_ADDRESS); /** * @dev Returns the fund's balance of the specified currency in the Compound pool. */ function getBalance() external returns (uint256) { return _cETHContract.balanceOfUnderlying(address(this)); } /** * @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound. * @param amount The amount of tokens to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _cETHContract.mint.value(amount)(); } /** * @dev Withdraws funds from the Compound pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than to 0."); uint256 redeemResult = _cETHContract.redeemUnderlying(amount); require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0"); } /** * @dev Withdraws all funds from the Compound pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { uint256 balance = _cETHContract.balanceOf(address(this)); if (balance <= 0) return false; uint256 redeemResult = _cETHContract.redeem(balance); require(redeemResult == 0, "Error calling redeem on Compound cToken: error code not equal to 0"); return true; } } // File: contracts/external/keeperdao/IKToken.sol pragma solidity 0.5.17; interface IKToken { function underlying() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(address recipient, uint256 amount) external returns (bool); function burnFrom(address sender, uint256 amount) external; function addMinter(address sender) external; function renounceMinter() external; } // File: contracts/external/keeperdao/ILiquidityPool.sol pragma solidity 0.5.17; interface ILiquidityPool { function () external payable; function kToken(address _token) external view returns (IKToken); function register(IKToken _kToken) external; function renounceOperator() external; function deposit(address _token, uint256 _amount) external payable returns (uint256); function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external; function borrowableBalance(address _token) external view returns (uint256); function underlyingBalance(address _token, address _owner) external view returns (uint256); } // File: contracts/lib/pools/KeeperDaoPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title KeeperDaoPoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @author Richter Brzeski <[email protected]> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from KeeperDAO liquidity pools. */ library KeeperDaoPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address payable constant private KEEPERDAO_CONTRACT = 0x35fFd6E268610E764fF6944d07760D0EFe5E40E5; ILiquidityPool constant private _liquidityPool = ILiquidityPool(KEEPERDAO_CONTRACT); // KeeperDAO's representation of ETH address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @dev Returns the fund's balance in the KeeperDAO pool. */ function getBalance() external view returns (uint256) { return _liquidityPool.underlyingBalance(ETHEREUM_ADDRESS, address(this)); } /** * @dev Approves kEther to KeeperDAO to burn without spending gas on every deposit. * @param amount Amount of kEther to approve to KeeperDAO. */ function approve(uint256 amount) external { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 allowance = kEther.allowance(address(this), KEEPERDAO_CONTRACT); if (allowance == amount) return; if (amount > 0 && allowance > 0) kEther.approve(KEEPERDAO_CONTRACT, 0); kEther.approve(KEEPERDAO_CONTRACT, amount); } /** * @dev Deposits funds to the KeeperDAO pool.. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _liquidityPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount); } /** * @dev Withdraws funds from the KeeperDAO pool. * @param amount The amount of ETH to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _liquidityPool.withdraw(address(uint160(address(this))), _liquidityPool.kToken(ETHEREUM_ADDRESS), calculatekEtherWithdrawAmount(amount)); } /** * @dev Withdraws all funds from the KeeperDAO pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 balance = kEther.balanceOf(address(this)); if (balance <= 0) return false; _liquidityPool.withdraw(address(uint160(address(this))), kEther, balance); return true; } /** * @dev Calculates an amount of kEther to withdraw equivalent to amount parameter in ETH. * @return amount to withdraw in kEther. */ function calculatekEtherWithdrawAmount(uint256 amount) internal view returns (uint256) { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 totalSupply = kEther.totalSupply(); uint256 borrowableBalance = _liquidityPool.borrowableBalance(ETHEREUM_ADDRESS); uint256 kEtherAmount = amount.mul(totalSupply).div(borrowableBalance); if (kEtherAmount.mul(borrowableBalance).div(totalSupply) < amount) kEtherAmount++; return kEtherAmount; } } // File: contracts/external/aave/LendingPool.sol /** * Aave Protocol * Copyright (C) 2019 Aave * 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 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 */ pragma solidity 0.5.17; /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data * @author Aave */ contract LendingPool { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param _reserve the address of the reserve * @param _amount the amount to be deposited * @param _referralCode integrators are assigned a referral code and can potentially receive rewards. */ function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable; } // File: contracts/external/aave/AToken.sol /** * Aave Protocol * Copyright (C) 2019 Aave * 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 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 */ pragma solidity 0.5.17; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the DLP protocol. * @author Aave */ contract AToken { /** * @dev redeems aToken for the underlying asset * @param _amount the amount being redeemed */ function redeem(uint256 _amount) external; /** * @dev calculates the balance of the user, which is the * principal balance + interest generated by the principal balance + interest generated by the redirected balance * @param _user the user for which the balance is being calculated * @return the total balance of the user */ function balanceOf(address _user) public view returns (uint256); } // File: contracts/lib/pools/AavePoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title AavePoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @author Richter Brzeski <[email protected]> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from Aave liquidity pools. */ library AavePoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Aave LendingPool contract address. */ address constant private LENDING_POOL_CONTRACT = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; /** * @dev Aave LendingPool contract object. */ LendingPool constant private _lendingPool = LendingPool(LENDING_POOL_CONTRACT); /** * @dev Aave LendingPoolCore contract address. */ address constant private LENDING_POOL_CORE_CONTRACT = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /** * @dev AETH contract address. */ address constant private AETH_CONTRACT = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; /** * @dev AETH contract. */ AToken constant private aETH = AToken(AETH_CONTRACT); /** * @dev Ethereum address abstraction */ address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @dev Returns the fund's balance of the specified currency in the Aave pool. */ function getBalance() external view returns (uint256) { return aETH.balanceOf(address(this)); } /** * @dev Deposits funds to the Aave pool. Assumes that you have already approved >= the amount to Aave. * @param amount The amount of tokens to be deposited. * @param referralCode Referral code. */ function deposit(uint256 amount, uint16 referralCode) external { require(amount > 0, "Amount must be greater than 0."); _lendingPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount, referralCode); } /** * @dev Withdraws funds from the Aave pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); aETH.redeem(amount); } /** * @dev Withdraws all funds from the Aave pool. */ function withdrawAll() external { aETH.redeem(uint256(-1)); } } // File: contracts/external/alpha/Bank.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.17; contract Bank is IERC20 { /// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() public view returns (uint256); /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable; /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external; } // File: contracts/lib/pools/AlphaPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title AlphaPoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @dev This library handles deposits to and withdrawals from Alpha Homora's ibETH pool. */ library AlphaPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Alpha Homora ibETH token contract address. */ address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A; /** * @dev Alpha Homora ibETH token contract object. */ Bank constant private _ibEth = Bank(IBETH_CONTRACT); /** * @dev Returns the fund's balance of the specified currency in the ibETH pool. */ function getBalance() external view returns (uint256) { return _ibEth.balanceOf(address(this)).mul(_ibEth.totalETH()).div(_ibEth.totalSupply()); } /** * @dev Deposits funds to the ibETH pool. Assumes that you have already approved >= the amount to the ibETH token contract. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _ibEth.deposit.value(amount)(); } /** * @dev Withdraws funds from the ibETH pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); uint256 totalEth = _ibEth.totalETH(); uint256 totalSupply = _ibEth.totalSupply(); uint256 credits = amount.mul(totalSupply).div(totalEth); if (credits.mul(totalEth).div(totalSupply) < amount) credits++; // Round up if necessary (i.e., if the division above left a remainder) _ibEth.withdraw(credits); } /** * @dev Withdraws all funds from the ibETH pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { uint256 balance = _ibEth.balanceOf(address(this)); if (balance <= 0) return false; _ibEth.withdraw(balance); return true; } } // File: contracts/external/enzyme/ComptrollerLib.sol // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.5.17; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds interface ComptrollerLib { //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external returns (uint256 grossShareValue_, bool isValid_); /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external returns (uint256[] memory sharesReceivedAmounts_); // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_); /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_); /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view returns (address vaultProxy_); } // File: contracts/lib/pools/EnzymePoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title EnzymePoolController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @dev This library handles deposits to and withdrawals from Enzyme's Rari ETH (technically WETH) pool. */ library EnzymePoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev The WETH contract address. */ address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @dev The WETH contract object. */ IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT); /** * @dev Alpha Homora ibETH token contract address. */ address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A; /** * @dev Returns the fund's balance of ETH (technically WETH) in the Enzyme pool. */ function getBalance(address comptroller) external returns (uint256) { ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); return IERC20(_comptroller.getVaultProxy()).balanceOf(address(this)).mul(price).div(1e18); } /** * @dev Approves WETH to the Enzyme pool Comptroller without spending gas on every deposit. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount Amount of the WETH to approve to the Enzyme pool Comptroller. */ function approve(address comptroller, uint256 amount) external { uint256 allowance = _weth.allowance(address(this), comptroller); if (allowance == amount) return; if (amount > 0 && allowance > 0) _weth.approve(comptroller, 0); _weth.approve(comptroller, amount); } /** * @dev Deposits funds to the Enzyme pool. Assumes that you have already approved >= the amount to the Enzyme Comptroller contract. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount The amount of ETH to be deposited. */ function deposit(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _weth.deposit.value(amount)(); address[] memory buyers = new address[](1); buyers[0] = address(this); uint256[] memory amounts = new uint256[](1); amounts[0] = amount; uint256[] memory minShares = new uint256[](1); minShares[0] = 0; ComptrollerLib(comptroller).buyShares(buyers, amounts, minShares); } /** * @dev Withdraws funds from the Enzyme pool. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount The amount of tokens to be withdrawn. */ function withdraw(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); uint256 shares = amount.mul(1e18).div(price); if (shares.mul(price).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder) address[] memory additionalAssets = new address[](0); address[] memory assetsToSkip = new address[](0); _comptroller.redeemSharesDetailed(shares, additionalAssets, assetsToSkip); _weth.withdraw(_weth.balanceOf(address(this))); } /** * @dev Withdraws all funds from the Enzyme pool. * @param comptroller The Enzyme pool Comptroller contract address. */ function withdrawAll(address comptroller) external { ComptrollerLib(comptroller).redeemShares(); _weth.withdraw(_weth.balanceOf(address(this))); } } // File: @0x/contracts-utils/contracts/src/LibRichErrors.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } // File: @0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol pragma solidity ^0.5.9; library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } // File: @0x/contracts-utils/contracts/src/LibSafeMath.sol pragma solidity ^0.5.9; library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: @0x/contracts-exchange-libs/contracts/src/LibMathRichErrors.sol pragma solidity ^0.5.9; library LibMathRichErrors { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } // File: @0x/contracts-exchange-libs/contracts/src/LibMath.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibMath { using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } // File: @0x/contracts-exchange-libs/contracts/src/LibFillResults.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibFillResults { using LibSafeMath for uint256; struct BatchMatchedFillResults { FillResults[] left; // Fill results for left orders FillResults[] right; // Fill results for right orders uint256 profitInLeftMakerAsset; // Profit taken from left makers uint256 profitInRightMakerAsset; // Profit taken from right makers } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 profitInLeftMakerAsset; // Profit taken from the left maker uint256 profitInRightMakerAsset; // Profit taken from the right maker } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; } /// @dev Calculates fill amounts for the matched orders. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the leftOrder order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftOrderTakerAssetFilledAmount Amount of left order already filled. /// @param rightOrderTakerAssetFilledAmount Amount of right order already filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use /// the maximal fill order matching strategy. /// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders. function calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftOrderTakerAssetFilledAmount, uint256 rightOrderTakerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice, bool shouldMaximallyFillOrders ) internal pure returns (MatchedFillResults memory matchedFillResults) { // Derive maker asset amounts for left & right orders, given store taker assert amounts uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount); uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, leftTakerAssetAmountRemaining ); uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount); uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, rightTakerAssetAmountRemaining ); // Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets. if (shouldMaximallyFillOrders) { matchedFillResults = _calculateMatchedFillResultsWithMaximalFill( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else { matchedFillResults = _calculateMatchedFillResults( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Compute fees for left order matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee ); matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee ); // Compute fees for right order matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee ); matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee ); // Compute the protocol fee that should be paid for a single fill. In this // case this should be made the protocol fee for both the left and right orders. uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier); matchedFillResults.left.protocolFeePaid = protocolFee; matchedFillResults.right.protocolFeePaid = protocolFee; // Return fill results return matchedFillResults; } /// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results. function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only /// awards profit denominated in the left maker asset. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate fill results for maker and taker assets: at least one order will be fully filled. // The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining` // The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining` // We have two distinct cases for calculating the fill results: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // If the left maker can buy exactly what the right maker can sell, then both orders are fully filled. // Case 2. // If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled. // Case 3. // If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) { // Case 2: Left order is fully filled matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. // We favor the maker when the exchange rate must be rounded. matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount ); } else { // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining // Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but // this calculation will be more precise since it does not include rounding. matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); return matchedFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching /// strategy. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResultsWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset. bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining; bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining; // Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled. // // The maximum that the left maker can possibly buy is the amount that the right order can sell. // The maximum that the right maker can possibly buy is the amount that the left order can sell. // // If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled, // the profit will be out in the right maker asset. // // There are three cases to consider: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // Case 2. // If the right maker can buy more than the left maker can sell, then only the right order is fully filled. // Case 3. // If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of // what the right maker can buy, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled with the profit paid in the left makerAsset matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) { // Case 2: Left order is fully filled with the profit paid in the right makerAsset. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round down to ensure the right maker's exchange rate does not exceed the price specified by the order. // We favor the right maker when the exchange rate must be rounded and the profit is being paid in the // right maker asset. matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftMakerAssetAmountRemaining ); matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining; } else { // Case 3: The right and left orders are fully filled matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit. if (doesLeftMakerAssetProfitExist) { matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); } // Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit. if (doesRightMakerAssetProfitExist) { matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub( matchedFillResults.left.takerAssetFilledAmount ); } return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; } } // File: @0x/contracts-exchange/contracts/src/interfaces/IExchangeCore.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IExchangeCore { // Fill event is emitted whenever an order is filled. event Fill( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that received fees. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset. bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset. bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash). address takerAddress, // Address that filled the order. address senderAddress, // Address that called the Exchange contract (msg.sender). uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker. uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker. uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker. uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker. uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract. ); // Cancel event is emitted whenever an individual order is cancelled. event Cancel( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. address senderAddress, // Address that called the Exchange contract (msg.sender). bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash). ); // CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully. event CancelUpTo( address indexed makerAddress, // Orders cancelled must have been created by this address. address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address. uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled. ); /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external payable; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public payable; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } // File: @0x/contracts-exchange/contracts/src/interfaces/IProtocolFees.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IProtocolFees { // Logs updates to the protocol fee multiplier. event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier); // Logs updates to the protocolFeeCollector address. event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector); /// @dev Allows the owner to update the protocol fee multiplier. /// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier) external; /// @dev Allows the owner to update the protocolFeeCollector address. /// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address. function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external; /// @dev Returns the protocolFeeMultiplier function protocolFeeMultiplier() external view returns (uint256); /// @dev Returns the protocolFeeCollector address function protocolFeeCollector() external view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IMatchOrders.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IMatchOrders { /// @dev Match complementary orders that have a profitable spread. /// Each order is filled at their respective price point, and /// the matcher receives a profit denominated in the left maker asset. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrders( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrdersWithMaximalFill( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled by maker and taker of matched orders. function matchOrdersWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); } // File: @0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol /* Copyright 2019 ZeroEx Intl. 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.9; library LibZeroExTransaction { using LibZeroExTransaction for ZeroExTransaction; // Hash for the EIP712 0x transaction schema // keccak256(abi.encodePacked( // "ZeroExTransaction(", // "uint256 salt,", // "uint256 expirationTimeSeconds,", // "uint256 gasPrice,", // "address signerAddress,", // "bytes data", // ")" // )); bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508; struct ZeroExTransaction { uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash. uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires. uint256 gasPrice; // gasPrice that transaction is required to be executed with. address signerAddress; // Address of transaction signer. bytes data; // AbiV2 encoded calldata. } /// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction. function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; } /// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct. function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; } } // File: @0x/contracts-exchange/contracts/src/interfaces/ISignatureValidator.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract ISignatureValidator { // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 EIP1271Wallet, // 0x07 NSignatureTypes // 0x08, number of signature types. Always leave at end. } event SignatureValidatorApproval( address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures. address indexed validatorAddress, // Address of signature validator contract. bool isApproved // Approval or disapproval of validator contract. ); /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external payable; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external payable; /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given order and signer. function isValidOrderSignature( LibOrder.Order memory order, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given transaction and signer. function isValidTransactionSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( LibOrder.Order memory order, bytes32 orderHash, bytes memory signature ) internal view returns (bool isValid); /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes32 transactionHash, bytes memory signature ) internal view returns (bool isValid); } // File: @0x/contracts-exchange/contracts/src/interfaces/ITransactions.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract ITransactions { // TransactionExecution event is emitted when a ZeroExTransaction is executed. event TransactionExecution(bytes32 indexed transactionHash); /// @dev Executes an Exchange method call in the context of signer. /// @param transaction 0x transaction containing salt, signerAddress, and data. /// @param signature Proof that transaction has been signed by signer. /// @return ABI encoded return data of the underlying Exchange function call. function executeTransaction( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public payable returns (bytes memory); /// @dev Executes a batch of Exchange method calls in the context of signer(s). /// @param transactions Array of 0x transactions containing salt, signerAddress, and data. /// @param signatures Array of proofs that transactions have been signed by signer(s). /// @return Array containing ABI encoded return data for each of the underlying Exchange function calls. function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory); /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function _getCurrentContextAddress() internal view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IAssetProxyDispatcher.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IAssetProxyDispatcher { // Logs registration of new asset proxy event AssetProxyRegistered( bytes4 id, // Id of new registered AssetProxy. address assetProxy // Address of new registered AssetProxy. ); /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IWrapperFunctions.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrKillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Minimum amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Minimum amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of cancelOrder. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public payable; } // File: @0x/contracts-exchange/contracts/src/interfaces/ITransferSimulator.sol /* Copyright 2019 ZeroEx Intl. 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.9; contract ITransferSimulator { /// @dev This function may be used to simulate any amount of transfers /// As they would occur through the Exchange contract. Note that this function /// will always revert, even if all transfers are successful. However, it may /// be used with eth_call or with a try/catch pattern in order to simulate /// the results of the transfers. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @param fromAddresses Array containing the `from` addresses that correspond with each transfer. /// @param toAddresses Array containing the `to` addresses that correspond with each transfer. /// @param amounts Array containing the amounts that correspond to each transfer. /// @return This function does not return a value. However, it will always revert with /// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. function simulateDispatchTransferFromCalls( bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) public; } // File: @0x/contracts-exchange/contracts/src/interfaces/IExchange.sol /* Copyright 2019 ZeroEx Intl. 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.9; // solhint-disable no-empty-blocks contract IExchange is IProtocolFees, IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, ITransferSimulator, IWrapperFunctions {} // File: contracts/lib/exchanges/ZeroExExchangeController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title ZeroExExchangeController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @dev This library handles exchanges via 0x. */ library ZeroExExchangeController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private EXCHANGE_CONTRACT = 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef; IExchange constant private _exchange = IExchange(EXCHANGE_CONTRACT); address constant private ERC20_PROXY_CONTRACT = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; /** * @dev Gets allowance of the specified token to 0x. * @param erc20Contract The ERC20 contract address of the token. */ function allowance(address erc20Contract) internal view returns (uint256) { return IERC20(erc20Contract).allowance(address(this), ERC20_PROXY_CONTRACT); } /** * @dev Approves tokens to 0x without spending gas on every deposit. * @param erc20Contract The ERC20 contract address of the token. * @param amount Amount of the specified token to approve to dYdX. * @return Boolean indicating success. */ function approve(address erc20Contract, uint256 amount) internal returns (bool) { IERC20 token = IERC20(erc20Contract); uint256 _allowance = token.allowance(address(this), ERC20_PROXY_CONTRACT); if (_allowance == amount) return true; if (amount > 0 && _allowance > 0) token.safeApprove(ERC20_PROXY_CONTRACT, 0); token.safeApprove(ERC20_PROXY_CONTRACT, amount); return true; } /** * @dev Market sells to 0x exchange orders up to a certain amount of input. * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees). * @param protocolFee The protocol fee in ETH to pay to 0x. * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought). */ function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) { require(orders.length > 0, "At least one order and matching signature is required."); require(orders.length == signatures.length, "Mismatch between number of orders and signatures."); require(takerAssetFillAmount > 0, "Taker asset fill amount must be greater than 0."); LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures); return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount]; } /** * @dev Market buys from 0x exchange orders up to a certain amount of output. * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param makerAssetFillAmount The amount of the maker asset to buy. * @param protocolFee The protocol fee in ETH to pay to 0x. * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought). */ function marketBuyOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 makerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) { require(orders.length > 0, "At least one order and matching signature is required."); require(orders.length == signatures.length, "Mismatch between number of orders and signatures."); require(makerAssetFillAmount > 0, "Maker asset fill amount must be greater than 0."); LibFillResults.FillResults memory fillResults = _exchange.marketBuyOrdersFillOrKill.value(protocolFee)(orders, makerAssetFillAmount, signatures); return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount]; } } // File: contracts/RariFundController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title RariFundController * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @author Richter Brzeski <[email protected]> (https://github.com/richtermb) * @dev This contract handles deposits to and withdrawals from the liquidity pools that power the Rari Ethereum Pool as well as currency exchanges via 0x. */ contract RariFundController is Ownable { using SafeMath for uint256; using SignedSafeMath for int256; using SafeERC20 for IERC20; /** * @dev Boolean to be checked on `upgradeFundController`. */ bool public constant IS_RARI_FUND_CONTROLLER = true; /** * @dev Boolean that, if true, disables the primary functionality of this RariFundController. */ bool private _fundDisabled; /** * @dev Address of the RariFundManager. */ address payable private _rariFundManagerContract; /** * @dev Address of the rebalancer. */ address private _rariFundRebalancerAddress; /** * @dev Enum for liqudity pools supported by Rari. */ enum LiquidityPool { dYdX, Compound, KeeperDAO, Aave, Alpha, Enzyme } /** * @dev Maps arrays of supported pools to currency codes. */ uint8[] private _supportedPools; /** * @dev COMP token address. */ address constant private COMP_TOKEN = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /** * @dev ROOK token address. */ address constant private ROOK_TOKEN = 0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a; /** * @dev WETH token contract. */ IEtherToken constant private _weth = IEtherToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /** * @dev Caches the balances for each pool, with the sum cached at the end */ uint256[] private _cachedBalances; /** * @dev Constructor that sets supported ERC20 token contract addresses and supported pools for each supported token. */ constructor () public { Ownable.initialize(msg.sender); // Add supported pools addPool(0); // dYdX addPool(1); // Compound addPool(2); // KeeperDAO addPool(3); // Aave addPool(4); // Alpha addPool(5); // Enzyme } /** * @dev Adds a supported pool for a token. * @param pool Pool ID to be supported. */ function addPool(uint8 pool) internal { _supportedPools.push(pool); } /** * @dev Payable fallback function called by 0x exchange to refund unspent protocol fee. */ function () external payable { } /** * @dev Emitted when the RariFundManager of the RariFundController is set. */ event FundManagerSet(address newAddress); /** * @dev Sets or upgrades the RariFundManager of the RariFundController. * @param newContract The address of the new RariFundManager contract. */ function setFundManager(address payable newContract) external onlyOwner { _rariFundManagerContract = newContract; emit FundManagerSet(newContract); } /** * @dev Throws if called by any account other than the RariFundManager. */ modifier onlyManager() { require(_rariFundManagerContract == msg.sender, "Caller is not the fund manager."); _; } /** * @dev Emitted when the rebalancer of the RariFundController is set. */ event FundRebalancerSet(address newAddress); /** * @dev Sets or upgrades the rebalancer of the RariFundController. * @param newAddress The Ethereum address of the new rebalancer server. */ function setFundRebalancer(address newAddress) external onlyOwner { _rariFundRebalancerAddress = newAddress; emit FundRebalancerSet(newAddress); } /** * @dev Throws if called by any account other than the rebalancer. */ modifier onlyRebalancer() { require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer."); _; } /** * @dev Emitted when the primary functionality of this RariFundController contract has been disabled. */ event FundDisabled(); /** * @dev Emitted when the primary functionality of this RariFundController contract has been enabled. */ event FundEnabled(); /** * @dev Disables primary functionality of this RariFundController so contract(s) can be upgraded. */ function disableFund() external onlyOwner { require(!_fundDisabled, "Fund already disabled."); _fundDisabled = true; emit FundDisabled(); } /** * @dev Enables primary functionality of this RariFundController once contract(s) are upgraded. */ function enableFund() external onlyOwner { require(_fundDisabled, "Fund already enabled."); _fundDisabled = false; emit FundEnabled(); } /** * @dev Throws if fund is disabled. */ modifier fundEnabled() { require(!_fundDisabled, "This fund controller contract is disabled. This may be due to an upgrade."); _; } /** * @dev Sets or upgrades RariFundController by forwarding immediate balance of ETH from the old to the new. * @param newContract The address of the new RariFundController contract. */ function _upgradeFundController(address payable newContract) public onlyOwner { // Verify fund is disabled + verify new fund controller contract require(_fundDisabled, "This fund controller contract must be disabled before it can be upgraded."); require(RariFundController(newContract).IS_RARI_FUND_CONTROLLER(), "New contract does not have IS_RARI_FUND_CONTROLLER set to true."); // Transfer all ETH to new fund controller uint256 balance = address(this).balance; if (balance > 0) { (bool success, ) = newContract.call.value(balance)(""); require(success, "Failed to transfer ETH."); } } /** * @dev Sets or upgrades RariFundController by withdrawing all ETH from all pools and forwarding them from the old to the new. * @param newContract The address of the new RariFundController contract. */ function upgradeFundController(address payable newContract) external onlyOwner { // Withdraw all from Enzyme first because they output other LP tokens if (hasETHInPool(5)) _withdrawAllFromPool(5); // Then withdraw all from all other pools for (uint256 i = 0; i < _supportedPools.length; i++) if (hasETHInPool(_supportedPools[i])) _withdrawAllFromPool(_supportedPools[i]); // Transfer all ETH to new fund controller _upgradeFundController(newContract); } /** * @dev Returns the fund controller's balance of the specified currency in the specified pool. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state. * @param pool The index of the pool. */ function _getPoolBalance(uint8 pool) public returns (uint256) { if (pool == 0) return DydxPoolController.getBalance(); else if (pool == 1) return CompoundPoolController.getBalance(); else if (pool == 2) return KeeperDaoPoolController.getBalance(); else if (pool == 3) return AavePoolController.getBalance(); else if (pool == 4) return AlphaPoolController.getBalance(); else if (pool == 5) return EnzymePoolController.getBalance(_enzymeComptroller); else revert("Invalid pool index."); } /** * @dev Returns the fund controller's balance of the specified currency in the specified pool. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state. * @param pool The index of the pool. */ function getPoolBalance(uint8 pool) public returns (uint256) { if (!_poolsWithFunds[pool]) return 0; return _getPoolBalance(pool); } /** * @notice Returns the fund controller's balance of each pool of the specified currency. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state. * @return An array of pool indexes and an array of corresponding balances. */ function getEntireBalance() public returns (uint256) { uint256 sum = address(this).balance; // start with immediate eth balance for (uint256 i = 0; i < _supportedPools.length; i++) { sum = getPoolBalance(_supportedPools[i]).add(sum); } return sum; } /** * @dev Approves WETH to pool without spending gas on every deposit. * @param pool The index of the pool. * @param amount The amount of WETH to be approved. */ function approveWethToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { if (pool == 0) return DydxPoolController.approve(amount); else if (pool == 5) return EnzymePoolController.approve(_enzymeComptroller, amount); else revert("Invalid pool index."); } /** * @dev Approves kEther to the specified pool without spending gas on every deposit. * @param amount The amount of kEther to be approved. */ function approvekEtherToKeeperDaoPool(uint256 amount) external fundEnabled onlyRebalancer { KeeperDaoPoolController.approve(amount); } /** * @dev Mapping of bools indicating the presence of funds to pools. */ mapping(uint8 => bool) _poolsWithFunds; /** * @dev Return a boolean indicating if the fund controller has funds in `currencyCode` in `pool`. * @param pool The index of the pool to check. */ function hasETHInPool(uint8 pool) public view returns (bool) { return _poolsWithFunds[pool]; } /** * @dev Referral code for Aave deposits. */ uint16 _aaveReferralCode; /** * @dev Sets the referral code for Aave deposits. * @param referralCode The referral code. */ function setAaveReferralCode(uint16 referralCode) external onlyOwner { _aaveReferralCode = referralCode; } /** * @dev The Enzyme pool Comptroller contract address. */ address _enzymeComptroller; /** * @dev Sets the Enzyme pool Comptroller contract address. * @param comptroller The Enzyme pool Comptroller contract address. */ function setEnzymeComptroller(address comptroller) external onlyOwner { _enzymeComptroller = comptroller; } /** * @dev Enum for pool allocation action types supported by Rari. */ enum PoolAllocationAction { Deposit, Withdraw, WithdrawAll } /** * @dev Emitted when a deposit or withdrawal is made. * Note that `amount` is not set for `WithdrawAll` actions. */ event PoolAllocation(PoolAllocationAction indexed action, LiquidityPool indexed pool, uint256 amount); /** * @dev Deposits funds to the specified pool. * @param pool The index of the pool. */ function depositToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { require(amount > 0, "Amount must be greater than 0."); if (pool == 0) DydxPoolController.deposit(amount); else if (pool == 1) CompoundPoolController.deposit(amount); else if (pool == 2) KeeperDaoPoolController.deposit(amount); else if (pool == 3) AavePoolController.deposit(amount, _aaveReferralCode); else if (pool == 4) AlphaPoolController.deposit(amount); else if (pool == 5) EnzymePoolController.deposit(_enzymeComptroller, amount); else revert("Invalid pool index."); _poolsWithFunds[pool] = true; emit PoolAllocation(PoolAllocationAction.Deposit, LiquidityPool(pool), amount); } /** * @dev Internal function to withdraw funds from the specified pool. * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. */ function _withdrawFromPool(uint8 pool, uint256 amount) internal { if (pool == 0) DydxPoolController.withdraw(amount); else if (pool == 1) CompoundPoolController.withdraw(amount); else if (pool == 2) KeeperDaoPoolController.withdraw(amount); else if (pool == 3) AavePoolController.withdraw(amount); else if (pool == 4) AlphaPoolController.withdraw(amount); else if (pool == 5) EnzymePoolController.withdraw(_enzymeComptroller, amount); else revert("Invalid pool index."); emit PoolAllocation(PoolAllocationAction.Withdraw, LiquidityPool(pool), amount); } /** * @dev Withdraws funds from the specified pool. * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. */ function withdrawFromPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { require(amount > 0, "Amount must be greater than 0."); _withdrawFromPool(pool, amount); _poolsWithFunds[pool] = _getPoolBalance(pool) > 0; } /** * @dev Withdraws funds from the specified pool (caching the `initialBalance` parameter). * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. * @param initialBalance The fund's balance of the specified currency in the specified pool before the withdrawal. */ function withdrawFromPoolKnowingBalance(uint8 pool, uint256 amount, uint256 initialBalance) public fundEnabled onlyManager { _withdrawFromPool(pool, amount); if (amount == initialBalance) _poolsWithFunds[pool] = false; } /** * @dev Internal function that withdraws all funds from the specified pool. * @param pool The index of the pool. */ function _withdrawAllFromPool(uint8 pool) internal { if (pool == 0) DydxPoolController.withdrawAll(); else if (pool == 1) require(CompoundPoolController.withdrawAll(), "No Compound balance to withdraw from."); else if (pool == 2) require(KeeperDaoPoolController.withdrawAll(), "No KeeperDAO balance to withdraw from."); else if (pool == 3) AavePoolController.withdrawAll(); else if (pool == 4) require(AlphaPoolController.withdrawAll(), "No Alpha Homora balance to withdraw from."); else if (pool == 5) EnzymePoolController.withdrawAll(_enzymeComptroller); else revert("Invalid pool index."); _poolsWithFunds[pool] = false; emit PoolAllocation(PoolAllocationAction.WithdrawAll, LiquidityPool(pool), 0); } /** * @dev Withdraws all funds from the specified pool. * @param pool The index of the pool. * @return Boolean indicating success. */ function withdrawAllFromPool(uint8 pool) external fundEnabled onlyRebalancer { _withdrawAllFromPool(pool); } /** * @dev Withdraws all funds from the specified pool (without requiring the fund to be enabled). * @param pool The index of the pool. * @return Boolean indicating success. */ function withdrawAllFromPoolOnUpgrade(uint8 pool) external onlyOwner { _withdrawAllFromPool(pool); } /** * @dev Withdraws ETH and sends amount to the manager. * @param amount Amount of ETH to withdraw. */ function withdrawToManager(uint256 amount) external onlyManager { // Input validation require(amount > 0, "Withdrawal amount must be greater than 0."); // Check contract balance and withdraw from pools if necessary uint256 contractBalance = address(this).balance; // get ETH balance if (contractBalance < amount) { uint256 poolBalance = getPoolBalance(5); if (poolBalance > 0) { uint256 amountLeft = amount.sub(contractBalance); uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance; withdrawFromPoolKnowingBalance(5, poolAmount, poolBalance); contractBalance = address(this).balance; } } for (uint256 i = 0; i < _supportedPools.length; i++) { if (contractBalance >= amount) break; uint8 pool = _supportedPools[i]; if (pool == 5) continue; uint256 poolBalance = getPoolBalance(pool); if (poolBalance <= 0) continue; uint256 amountLeft = amount.sub(contractBalance); uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance; withdrawFromPoolKnowingBalance(pool, poolAmount, poolBalance); contractBalance = contractBalance.add(poolAmount); } require(address(this).balance >= amount, "Too little ETH to transfer."); (bool success, ) = _rariFundManagerContract.call.value(amount)(""); require(success, "Failed to transfer ETH to RariFundManager."); } /** * @dev Emitted when COMP is exchanged to ETH via 0x. */ event CurrencyTrade(address inputErc20Contract, uint256 inputAmount, uint256 outputAmount); /** * @dev Approves tokens (COMP or ROOK) to 0x without spending gas on every deposit. * @param erc20Contract The ERC20 contract address of the token to be approved (must be COMP or ROOK). * @param amount The amount of tokens to be approved. */ function approveTo0x(address erc20Contract, uint256 amount) external fundEnabled onlyRebalancer { require(erc20Contract == COMP_TOKEN || erc20Contract == ROOK_TOKEN, "Supplied token address is not COMP or ROOK."); ZeroExExchangeController.approve(erc20Contract, amount); } /** * @dev Market sell (COMP or ROOK) to 0x exchange orders (reverting if `takerAssetFillAmount` is not filled). * We should be able to make this function external and use calldata for all parameters, but Solidity does not support calldata structs (https://github.com/ethereum/solidity/issues/5479). * @param inputErc20Contract The input ERC20 token contract address (must be COMP or ROOK). * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees). */ function marketSell0xOrdersFillOrKill(address inputErc20Contract, LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount) public payable fundEnabled onlyRebalancer { // Exchange COMP/ROOK to ETH uint256 ethBalanceBefore = address(this).balance; uint256[2] memory filledAmounts = ZeroExExchangeController.marketSellOrdersFillOrKill(orders, signatures, takerAssetFillAmount, msg.value); uint256 ethBalanceAfter = address(this).balance; emit CurrencyTrade(inputErc20Contract, filledAmounts[0], filledAmounts[1]); // Unwrap outputted WETH uint256 wethBalance = _weth.balanceOf(address(this)); require(wethBalance > 0, "No WETH outputted."); _weth.withdraw(wethBalance); // Refund unspent ETH protocol fee uint256 refund = ethBalanceAfter.sub(ethBalanceBefore.sub(msg.value)); if (refund > 0) { (bool success, ) = msg.sender.call.value(refund)(""); require(success, "Failed to refund unspent ETH protocol fee."); } } /** * Unwraps all WETH currently owned by the fund controller. */ function unwrapAllWeth() external fundEnabled onlyRebalancer { uint256 wethBalance = _weth.balanceOf(address(this)); require(wethBalance > 0, "No WETH to withdraw."); _weth.withdraw(wethBalance); } /** * @notice Returns the fund controller's contract ETH balance and balance of each pool (checking `_poolsWithFunds` first to save gas). * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state. * @return The fund controller ETH contract balance, an array of pool indexes, and an array of corresponding balances for each pool. */ function getRawFundBalances() external returns (uint256, uint8[] memory, uint256[] memory) { uint8[] memory pools = new uint8[](_supportedPools.length); uint256[] memory poolBalances = new uint256[](_supportedPools.length); for (uint256 i = 0; i < _supportedPools.length; i++) { pools[i] = _supportedPools[i]; poolBalances[i] = getPoolBalance(_supportedPools[i]); } return (address(this).balance, pools, poolBalances); } }
* @dev Sets the referral code for Aave deposits. @param referralCode The referral code./
function setAaveReferralCode(uint16 referralCode) external onlyOwner { _aaveReferralCode = referralCode; }
12,084,603
[ 1, 2785, 326, 1278, 29084, 981, 364, 432, 836, 443, 917, 1282, 18, 225, 1278, 370, 23093, 1021, 1278, 29084, 981, 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 ]
[ 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, 565, 445, 444, 37, 836, 1957, 370, 23093, 12, 11890, 2313, 1278, 370, 23093, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 69, 836, 1957, 370, 23093, 273, 1278, 370, 23093, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; contract BikeShare { /************************************** * constructor **************************************/ function BikeShare() { } /************************************** * Functions only accessible by the owner **************************************/ function setCreditPrice() {} function setCPKM() {} function setDonateCredits() {} function setRepairCredits() {} /************************************** * getters not provided by compiler **************************************/ function getAvailable(){} /************************************** * Function to purchase Credits **************************************/ function purchaseCredits() {} /************************************** * Donating function **************************************/ function donateBike() {} /************************************** * Rent a bike **************************************/ function rentBike() {} /************************************** * Ride a bike **************************************/ function rideBike() {} /************************************** * Return the bike **************************************/ function returnBike() {} /************************************** * default payable function, will call purchaseCredits **************************************/ function() {} } /* THIS CONTRACT IS ONLY MEANT TO BE USED FOR EDUCATIONAL PURPOSES. ANY AND ALL USES IS AT A USER'S OWN RISK AND THE AUTHOR HAS NO RESPONSIBILITY FOR ANY LOSS OF ANY KIND STEMMING THIS CODE. */
************************************* getters not provided by compiler/
function getAvailable(){}
6,436,245
[ 1, 588, 5432, 486, 2112, 635, 5274, 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, 15796, 1435, 2916, 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, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-04-21 */ pragma solidity >=0.5.1 <0.6.0; interface RecommendSmallTeamInterface { function API_AppendAchievement( address owner, uint value ) external; function API_DivestmentAchievement( address owner, uint value) external; function AchievementValueOf( address owner ) external view returns (uint); function AchievementDistributionOf( address owner) external view returns (uint totalSum, uint large, uint len, address[] memory addrs, uint[] memory values); function AchievementDynamicValue( address owner) external view returns ( uint ); function GetIntroducer( address _owner ) external view returns (address); function RecommendList( address _owner, uint256 depth ) external view returns ( address[] memory list, uint256 len ); function ShortCodeToAddress( bytes6 shortCode ) external view returns (address); function AddressToShortCode( address _addr ) external view returns (bytes6); function TeamMemberTotal( address _addr ) external view returns (uint256); function RegisterShortCode( bytes6 shortCode ) external; function BindRelation(address _recommer ) external; function BindRelationEx(address _recommer, bytes6 shortCode ) external; function AddressesCount() external view returns (uint); } pragma solidity >=0.5.1 <0.7.0; contract KState { address private _KDeveloper; address internal _KIMPLAddress; address[] _KAuthAddress; address payable public _KDefaultReciver; address payable[] public _KContractOwners = [ address(0x4ad16f3f6B4C1C48C644756979f96bcd0bfa077B) ]; bool public _KContractBroken; mapping (address => bool) _KWithdrawabledAddress; constructor() public { _KDeveloper = msg.sender; _KContractOwners.push(msg.sender); _KDefaultReciver = msg.sender; } modifier KWhenBroken() { require(_KContractBroken); _; } modifier KWhenNotBroken() { require(!_KContractBroken); _; } modifier KOwnerOnly() { bool exist = false; for ( uint i = 0; i < _KContractOwners.length; i++ ) { if ( _KContractOwners[i] == msg.sender ) { exist = true; break; } } require(exist); _; } function KSetContractBroken(bool broken) public KOwnerOnly { //inject PUBLIC FUNC TO EXTERNAL _KContractBroken = broken; } modifier KDAODefense() { uint256 size; address payable safeAddr = msg.sender; assembly {size := extcodesize(safeAddr)} require( size == 0, "DAO_Warning" ); _; } modifier KAPIMethod() { bool exist = false; for (uint i = 0; i < _KAuthAddress.length; i++) { if ( _KAuthAddress[i] == msg.sender ) { exist = true; break; } } require(exist); _; } function KAuthAddresses() public view returns (address[] memory authAddr) { //inject PUBLIC FUNC TO EXTERNAL return _KAuthAddress; } function KAddAuthAddress(address _addr) public KOwnerOnly { //inject PUBLIC FUNC TO EXTERNAL _KAuthAddress.push(_addr); } modifier KDeveloperOnly { require(msg.sender == _KDeveloper); _; } function KSetImplAddress(address impl) public KDeveloperOnly { //inject PUBLIC FUNC TO EXTERNAL _KIMPLAddress = impl; } function KGetImplAddress() public view KDeveloperOnly returns (address) { //inject PUBLIC FUNC TO EXTERNAL return _KIMPLAddress; } } contract KDoctor is KState { modifier write {_;} } contract KContract is KState { modifier write { if ( _KIMPLAddress != address(0x0) ) { (, bytes memory ret) = address(_KIMPLAddress).delegatecall(msg.data); assembly { return( add(ret, 0x20), mload(ret) ) } } else { _; } } } pragma solidity >=0.5.0 <0.6.0; interface ERC20Interface { /** * @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: * * 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); } pragma solidity >=0.4.22 <0.7.0; library Times { function Now() public view returns (uint) { return now; } function OneDay() public pure returns (uint256) { return 1 days; } function OneMonth() public pure returns (uint256) { return 30 * OneDay(); } function TodayZeroGMT8() public view returns (uint256) { return Now() / OneDay() * OneDay(); } function DayZeroGMT8(uint gmtTime) public pure returns (uint256) { return gmtTime / OneDay() * OneDay(); } } pragma solidity >=0.5.1 <0.7.0; library ValueQueue { struct Queue { uint40[] times; mapping(uint40 => uint144) stateMapping; } function LastTime( Queue storage self ) internal view returns ( uint40 ) { if ( self.times.length <= 0 ) { return 0; } return uint40(self.times[self.times.length - 1]); } function Last( Queue storage self ) internal view returns ( uint ) { return uint(self.stateMapping[uint40(LastTime(self))]); } function Add( Queue storage self, uint amount ) internal { uint40 nowDayTime = uint40(Times.TodayZeroGMT8()); if ( LastTime(self) != nowDayTime ) { self.stateMapping[ nowDayTime ] = self.stateMapping[ uint40(LastTime(self)) ]; self.times.push( nowDayTime ); } self.stateMapping[ uint40(LastTime(self)) ] += uint144(amount); } function Set( Queue storage self, uint amount) internal { uint40 nowDayTime = uint40(Times.TodayZeroGMT8()); if ( LastTime(self) != nowDayTime ) { self.stateMapping[ nowDayTime ] = self.stateMapping[ LastTime(self) ]; self.times.push( nowDayTime ); } self.stateMapping[ LastTime(self) ] = uint144(amount); } function Sub( Queue storage self, uint256 amount ) internal { require( self.stateMapping[ LastTime(self) ] >= amount ); uint40 nowDayTime = uint40(Times.TodayZeroGMT8()); if ( LastTime(self) != nowDayTime ) { self.stateMapping[ nowDayTime ] = self.stateMapping[ LastTime(self) ]; self.times.push( nowDayTime ); } self.stateMapping[ LastTime(self) ] -= uint144(amount); } function Nearest(Queue storage self, uint time ) internal view returns ( uint ) { uint dayzeroTime = Times.DayZeroGMT8(time); require( dayzeroTime > 0 ); for ( int i = int(self.times.length) - 1; i >= 0; i-- ) { if ( self.times[uint(i)] <= dayzeroTime ) { return self.stateMapping[self.times[uint(i)]]; } } return 0; } function NearestAtDeadLine(Queue storage self, uint time, uint deadLineTime ) internal view returns ( uint ) { uint dayzeroTime = Times.DayZeroGMT8(time); if ( dayzeroTime <= deadLineTime ) { return 0; } require( dayzeroTime > 0 ); for ( int i = int(self.times.length) - 1; i >= 0; i-- ) { if ( self.times[uint(i)] < dayzeroTime ) { return self.stateMapping[self.times[uint(i)]]; } } return 0; } } pragma solidity >=0.5.1 <0.7.0; library DepositedPool { using ValueQueue for ValueQueue.Queue; event LogDepositedChanged(address indexed owner, int amount, uint time); struct MainDB { uint relaseTime; mapping(address => ValueQueue.Queue) depositMapping; } function Init(MainDB storage self) internal { self.relaseTime = Times.TodayZeroGMT8(); } function DepositedAmount(MainDB storage self, address owner, uint nearestTime) internal view returns (uint) { return self.depositMapping[owner].NearestAtDeadLine(nearestTime, self.relaseTime); } function LatestAmount(MainDB storage self, address owner) internal view returns (uint) { return self.depositMapping[owner].Last(); } function DepositedSubDelegate(MainDB storage self, address owner, uint256 amount) internal { if (amount == 0) { return; } self.depositMapping[owner].Sub( amount ); emit LogDepositedChanged(owner, int(amount), Times.Now()); } function DepositedAddDelegate(MainDB storage self, address owner, uint256 amount) internal { if (amount == 0) { return; } self.depositMapping[owner].Add( amount ); emit LogDepositedChanged(owner, -int(amount), Times.Now()); } } pragma solidity >=0.5.1 <0.7.0; library Distribution { struct MainDB { uint relaseTime; uint SectionSpace; uint SectionSpaceMaxLimit; mapping(uint => uint) sectionDistributionMapping; mapping(uint => uint) calculationValues; mapping(uint => uint32[]) distributionEverDays; uint count; } function Init(MainDB storage self) internal { self.relaseTime = Times.TodayZeroGMT8(); self.SectionSpace = 100 ether; self.SectionSpaceMaxLimit = 20000 ether; } function DepositChangeDelegate(MainDB storage self, uint oldAmount, uint newAmount) internal { if ( oldAmount >= self.SectionSpaceMaxLimit && newAmount >= self.SectionSpaceMaxLimit ) { return ; } if ( oldAmount > 0 ) { uint spaceIdx; if ( oldAmount >= self.SectionSpaceMaxLimit ) { spaceIdx = self.SectionSpaceMaxLimit / self.SectionSpace; } else { spaceIdx = oldAmount / self.SectionSpace; } if ( spaceIdx > 0 ) { --self.sectionDistributionMapping[spaceIdx]; } } if ( newAmount > 0 ) { uint spaceIdx; if ( newAmount >= self.SectionSpaceMaxLimit ) { spaceIdx = self.SectionSpaceMaxLimit / self.SectionSpace; } else { spaceIdx = newAmount / self.SectionSpace; } if ( spaceIdx > 0 ) { ++self.sectionDistributionMapping[spaceIdx]; } } } function DistributionInfo(MainDB storage self, uint offset, uint size) internal view returns ( uint len, uint[] memory spaceIdxs, uint[] memory spaceSums ) { len = size; spaceIdxs = new uint[](len); spaceSums = new uint[](len); for ( (uint i, uint s) = (0, offset); s < offset + len; (s++, i++) ) { spaceIdxs[i] = s; spaceSums[i] = self.sectionDistributionMapping[s]; } } function UpdateCalculationValue( MainDB storage self ) internal { uint targetDay = Times.TodayZeroGMT8() + Times.OneDay(); if ( self.calculationValues[targetDay] == 0 && targetDay > self.relaseTime ) { uint orderID = 1; uint ret = 0; uint len = (self.SectionSpaceMaxLimit / self.SectionSpace) + 1; uint32[] memory tempDsitribution = new uint32[](len); tempDsitribution[0] = uint32(self.sectionDistributionMapping[0]); for ( uint i = 1; i < len; i++ ) { if ( self.sectionDistributionMapping[i] > 0 ) { tempDsitribution[i] = uint32(orderID); ret += orderID * self.sectionDistributionMapping[i]; orderID += self.sectionDistributionMapping[i]; } } self.distributionEverDays[ targetDay ] = tempDsitribution; self.calculationValues[ targetDay ] = ret; } } function CalculationValueAtDay( MainDB storage self, uint nearestTime) internal view returns (uint) { uint targetDay = Times.DayZeroGMT8(nearestTime); if ( targetDay <= self.relaseTime ) { return 0; } return self.calculationValues[targetDay]; } function CalculationQuickValueAtDay( MainDB storage self, uint nearestTime, uint epaceIndex) internal view returns (uint) { uint targetDay = Times.DayZeroGMT8(nearestTime); if ( self.distributionEverDays[targetDay].length != 0 ) { return self.distributionEverDays[targetDay][epaceIndex]; } else { return 0; } } function uint2str(uint i) internal pure returns (string memory c) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte( uint8(48 + i % 10) ); i /= 10; } c = string(bstr); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length + 1); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++){ bret[k++] = _ba[i]; } bret[k++] = '/'; for (uint i = 0; i < _bb.length; i++) { bret[k++] = _bb[i]; } return string(ret); } } pragma solidity >=0.5.1 <0.7.0; library RelaseCalculator { struct MainDB { uint relaseTime; uint relaseMonthCount; uint currentBoundsAmount; uint relaseAmountEverMonth; uint latestCalculatorTimes; } function Init(MainDB storage self) internal { self.relaseTime = Times.TodayZeroGMT8(); self.currentBoundsAmount = 10000000 ether; self.relaseAmountEverMonth = 1000000 ether; self.relaseMonthCount = 0; self.latestCalculatorTimes = Times.TodayZeroGMT8(); } function P(uint mc) internal pure returns (uint) { if ( mc < 7 ) { return 10; } else if ( mc >= 7 && mc < 19 ) { return 8;} else if ( mc >= 19 && mc < 43) { return 5;} else if ( mc >= 43 && mc < 80) { return 3;} else { return 2; } } function IsExpirationBounds(MainDB storage self) internal view returns (bool) { return Times.TodayZeroGMT8() - self.latestCalculatorTimes <= Times.OneMonth(); } function CurrentRelaseAmountMonth(MainDB storage self) internal view returns (uint) { return self.relaseAmountEverMonth; } function CurrentRelaseAmountDay(MainDB storage self) internal view returns (uint) { return self.relaseAmountEverMonth / ( Times.OneMonth() / Times.OneDay() ); } function UpdateBounds(MainDB storage self) internal { if ( IsExpirationBounds(self) ) { uint relaseMonthCount = (Times.TodayZeroGMT8() - self.relaseTime) / Times.OneMonth(); for ( uint i = self.relaseMonthCount; i < relaseMonthCount; i++ ) { self.currentBoundsAmount = self.currentBoundsAmount + self.relaseAmountEverMonth; self.relaseAmountEverMonth = self.currentBoundsAmount * P(i+1) / 100; } self.latestCalculatorTimes = Times.TodayZeroGMT8(); self.relaseMonthCount = relaseMonthCount; } } } pragma solidity >=0.5.1 <0.7.0; library StaticRelaseManager { using DepositedPool for DepositedPool.MainDB; using Distribution for Distribution.MainDB; using RelaseCalculator for RelaseCalculator.MainDB; struct MainDB { mapping(address => uint) latestWithdrawTimes; ERC20Interface erc20Inc; address assertPool; } function Init(MainDB storage self, ERC20Interface erc20, address assertPool) internal { self.erc20Inc = erc20; self.assertPool = assertPool; } function initFirstDepositedTime(MainDB storage self, address owner ) internal { if ( self.latestWithdrawTimes[owner] == 0 ) { self.latestWithdrawTimes[owner] = Times.TodayZeroGMT8(); } } event LogStaticRelaseDay( address indexed owner, uint indexed dayTime, uint profix ); function WithdrawCurrentRealseProfix( MainDB storage self, DepositedPool.MainDB storage depositPool, Distribution.MainDB storage distribution, RelaseCalculator.MainDB storage relaser, address owner, uint endTime ) internal { ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) = CurrentRelaseProfix( self, depositPool, distribution, relaser, owner, endTime ); require( sum > 0, "NoProfix" ); self.erc20Inc.transferFrom( self.assertPool, owner, sum ); for (uint i = 0; i < len; i++) { emit LogStaticRelaseDay( owner, dayTimes[i], profixs[i] ); } self.latestWithdrawTimes[owner] += len * Times.OneDay(); } function CurrentRelaseProfix( MainDB storage self, DepositedPool.MainDB storage depositPool, Distribution.MainDB storage distribution, RelaseCalculator.MainDB storage relaser, address owner, uint endTime ) internal view returns ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) { uint ltime = self.latestWithdrawTimes[owner]; if ( Times.DayZeroGMT8(endTime) - Times.OneDay() < ltime ) { sum = 0; len = 0; dayTimes = new uint[](0); profixs = new uint[](0); return (sum, len, dayTimes, profixs); } len = (Times.DayZeroGMT8(endTime) - Times.OneDay() - ltime) / Times.OneDay(); dayTimes = new uint[](len); profixs = new uint[](len); for ( uint i = 0; i < len; i++) { ltime += Times.OneDay(); dayTimes[i] = ltime; profixs[i] = ProfixHandle( depositPool, distribution, relaser, owner, dayTimes[i] ); sum += profixs[i]; } } function ProfixHandle ( DepositedPool.MainDB storage depositPool, Distribution.MainDB storage distribution, RelaseCalculator.MainDB storage relaser, address owner, uint dayZero ) internal view returns (uint) { uint ps = distribution.CalculationValueAtDay(dayZero + Times.OneDay()); if ( ps == 0 ) { return 0; } uint dayDeposit = depositPool.DepositedAmount( owner, dayZero ); uint spaceIdx; if ( dayDeposit >= distribution.SectionSpaceMaxLimit ) { spaceIdx = distribution.SectionSpaceMaxLimit / distribution.SectionSpace; } else { spaceIdx = dayDeposit / distribution.SectionSpace; } if ( spaceIdx == 0 ) { return 0; } uint qvalue = distribution.CalculationQuickValueAtDay(dayZero + Times.OneDay(), spaceIdx); return relaser.CurrentRelaseAmountDay() / 2 * (qvalue * 1 ether / ps) / 1 ether; } function uint2str(uint i) internal pure returns (string memory c) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte( uint8(48 + i % 10) ); i /= 10; } c = string(bstr); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length + 1); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++){ bret[k++] = _ba[i]; } bret[k++] = '/'; for (uint i = 0; i < _bb.length; i++) { bret[k++] = _bb[i]; } return string(ret); } } pragma solidity >=0.5.1 <0.7.0; library DynamicRelaseManager { using ValueQueue for ValueQueue.Queue; using RelaseCalculator for RelaseCalculator.MainDB; struct MainDB { mapping(address => ValueQueue.Queue) addressValuesMapping; mapping(address => uint) latestWithdrawTimes; uint currentSumValue; ValueQueue.Queue totalSumValues; RecommendSmallTeamInterface rcmInc; ERC20Interface erc20Inc; address assertPool; } event LogDynamicRelaseDay( address indexed owner, uint indexed dayTime, uint profix ); function Init(MainDB storage self, RecommendSmallTeamInterface rcm, ERC20Interface erc20, address assertPool) internal { self.rcmInc = rcm; self.erc20Inc = erc20; self.assertPool = assertPool; } function initFirstDepositedTime( MainDB storage self, address owner ) internal { if ( self.latestWithdrawTimes[owner] == 0 ) { self.latestWithdrawTimes[owner] = Times.TodayZeroGMT8(); } } function UpdateDynamicTotalSum(MainDB storage self) internal { if ( self.totalSumValues.Nearest( Times.TodayZeroGMT8() ) == 0 ) { self.totalSumValues.Set(self.currentSumValue); } } function UpdateOwnerDynmicValue(MainDB storage self, address owner, uint d) internal { address parent = self.rcmInc.GetIntroducer(owner); if ( parent == address(0x0) || parent == address(0xdead) ) { return ; } uint origin_p = self.addressValuesMapping[parent].Nearest(Times.Now()); uint new_p = self.rcmInc.AchievementDynamicValue(parent); uint tvalue = self.currentSumValue; for ( uint16 depth = 0; (parent != address(0x0) && parent != address(0xdead)) && (depth < d || d == 0); (parent = self.rcmInc.GetIntroducer(parent), depth++) ) { if ( new_p > origin_p ) { tvalue += (new_p - origin_p); self.addressValuesMapping[parent].Add( new_p - origin_p ); } else if ( new_p < origin_p && tvalue > (origin_p - new_p)) { tvalue -= (origin_p - new_p); self.addressValuesMapping[parent].Sub( origin_p - new_p ); } } self.totalSumValues.Set(tvalue); self.currentSumValue = tvalue; } function DynamicValueOf(MainDB storage self, address owner, uint nearestTime) internal view returns (uint) { return self.addressValuesMapping[owner].Nearest(nearestTime); } function DynamicTotalValueOf(MainDB storage self, uint nearestTime) internal view returns (uint) { return self.totalSumValues.Nearest(nearestTime); } function ProfixHandle( MainDB storage self, RelaseCalculator.MainDB storage relaser, address owner, uint nearestTime ) internal view returns (uint) { uint owner_p = self.addressValuesMapping[owner].Nearest(nearestTime); uint all_p = self.totalSumValues.Nearest(nearestTime); if ( all_p == 0 ) { return 0; } return relaser.CurrentRelaseAmountDay() / 2 * (owner_p * 1 ether / all_p) / 1 ether; } function CurrentRelaseProfix( MainDB storage self, RelaseCalculator.MainDB storage relaser, address owner, uint endTime ) internal view returns ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) { uint ltime = self.latestWithdrawTimes[owner]; if ( Times.DayZeroGMT8(endTime) - Times.OneDay() < ltime ) { sum = 0; len = 0; dayTimes = new uint[](0); profixs = new uint[](0); return (sum, len, dayTimes, profixs); } len = (Times.DayZeroGMT8(endTime) - ltime) / Times.OneDay(); dayTimes = new uint[](len); profixs = new uint[](len); for (uint i = 0; i < len; i++) { ltime += Times.OneDay(); dayTimes[i] = ltime; profixs[i] = ProfixHandle( self, relaser, owner, dayTimes[i] ); sum += profixs[i]; } } function WithdrawCurrentRealseProfix( MainDB storage self, RelaseCalculator.MainDB storage relaser, address owner, uint endTime ) internal { ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) = CurrentRelaseProfix( self, relaser, owner, endTime ); require( sum > 0, "NoProfix" ); self.erc20Inc.transferFrom( self.assertPool, owner, sum ); for (uint i = 0; i < len; i++) { emit LogDynamicRelaseDay( owner, dayTimes[i], profixs[i]); } self.latestWithdrawTimes[owner] += len * Times.OneDay(); } function uint2str(uint i) internal pure returns (string memory c) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte( uint8(48 + i % 10) ); i /= 10; } c = string(bstr); } } pragma solidity >=0.5.1 <0.7.0; contract RelasePool is KContract { ERC20Interface public _erc20Inc; constructor(ERC20Interface erc20) public { _erc20Inc = erc20; } function ApproveToMainContract(address spender, uint amount) public write KDeveloperOnly { //inject PUBLIC FUNC TO EXTERNAL _erc20Inc.approve( spender, amount ); } } pragma solidity >=0.5.1 <0.7.0; contract DepositToken is KContract { using RelaseCalculator for RelaseCalculator.MainDB; RelaseCalculator.MainDB public _relaser; using StaticRelaseManager for StaticRelaseManager.MainDB; StaticRelaseManager.MainDB public _staticRelaser; using DepositedPool for DepositedPool.MainDB; DepositedPool.MainDB _depositedPool; using Distribution for Distribution.MainDB; Distribution.MainDB _distribution; using DynamicRelaseManager for DynamicRelaseManager.MainDB; DynamicRelaseManager.MainDB _dynamicRelaser; event LogRelaseDay( address indexed owner, uint indexed dayTime, uint profix); uint16 public SD = 0; RecommendSmallTeamInterface public _rcmInc; RelasePool public _assertPool; ERC20Interface public _erc20Inc; uint _depositedLimit = 100 ether; constructor(ERC20Interface erc20, RelasePool pool, RecommendSmallTeamInterface rcm) public { _assertPool = pool; _erc20Inc = erc20; _rcmInc = rcm; _distribution.Init(); _relaser.Init(); _staticRelaser.Init(erc20, address(pool) ); _dynamicRelaser.Init(rcm, erc20, address(pool) ); _depositedPool.Init(); _KContractBroken = true; } function DepositAppend(uint amount) public write KWhenNotBroken { //inject PUBLIC FUNC TO EXTERNAL require( amount >= _depositedLimit, "LessMinLimit" ); UpdateContractState(); require( _rcmInc.GetIntroducer(msg.sender) != address(0x0), "NoIntroducer" ); require( amount > 0 && _erc20Inc.transferFrom( msg.sender, address(this), amount ) ); uint oldAmount = _depositedPool.LatestAmount(msg.sender); _depositedPool.DepositedAddDelegate(msg.sender, amount); uint newAmount = _depositedPool.LatestAmount(msg.sender); _distribution.DepositChangeDelegate(oldAmount, newAmount); _staticRelaser.initFirstDepositedTime(msg.sender); _dynamicRelaser.initFirstDepositedTime(msg.sender); _rcmInc.API_AppendAchievement(msg.sender, amount); _dynamicRelaser.UpdateOwnerDynmicValue(msg.sender, SD); } function DepositDivestment(uint amount) public write KWhenNotBroken { //inject PUBLIC FUNC TO EXTERNAL UpdateContractState(); require(amount > 0); uint oldAmount = _depositedPool.LatestAmount(msg.sender); _depositedPool.DepositedSubDelegate(msg.sender, amount); uint newAmount = _depositedPool.LatestAmount(msg.sender); _distribution.DepositChangeDelegate(oldAmount, newAmount); _erc20Inc.transfer( msg.sender, amount ); _rcmInc.API_DivestmentAchievement(msg.sender, amount); _dynamicRelaser.UpdateOwnerDynmicValue(msg.sender, SD); } function UpdateContractState() public write { _relaser.UpdateBounds(); _dynamicRelaser.UpdateDynamicTotalSum(); _distribution.UpdateCalculationValue(); } function CurrentRelaseProfixStatic(address owner, uint latestTime) public view //inject PUBLIC FUNC TO EXTERNAL returns ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) { uint endTime = latestTime; if ( endTime == 0 ) { endTime = Times.Now(); } return _staticRelaser.CurrentRelaseProfix( _depositedPool, _distribution, _relaser, owner, endTime ); } function CurrentRelaseProfixDynamic(address owner, uint latestTime) public view //inject PUBLIC FUNC TO EXTERNAL returns ( uint sum, uint len, uint[] memory dayTimes, uint[] memory profixs ) { uint endTime = latestTime; if ( endTime == 0 ) { endTime = Times.Now(); } return _dynamicRelaser.CurrentRelaseProfix( _relaser, owner, endTime ); } function WithdrawProfix(uint latestTime) public write KWhenNotBroken { //inject PUBLIC FUNC TO EXTERNAL uint endTime = latestTime; if ( endTime == 0 ) { endTime = Times.Now(); } _dynamicRelaser.UpdateOwnerDynmicValue(msg.sender, SD); (uint st,,,) = _staticRelaser.CurrentRelaseProfix( _depositedPool, _distribution, _relaser, msg.sender, endTime ); (uint dy,,,) = _dynamicRelaser.CurrentRelaseProfix( _relaser, msg.sender, endTime ); emit LogRelaseDay( msg.sender, Times.DayZeroGMT8(endTime), st+dy ); if ( st > 0 ) { _staticRelaser.WithdrawCurrentRealseProfix( _depositedPool, _distribution, _relaser, msg.sender, endTime ); } if (dy > 0 ) { _dynamicRelaser.WithdrawCurrentRealseProfix( _relaser, msg.sender, endTime ); } } function WithdrawProfix_Dynamic(uint latestTime) public write KWhenNotBroken { uint endTime = latestTime; if ( endTime == 0 ) { endTime = Times.Now(); } _dynamicRelaser.UpdateOwnerDynmicValue(msg.sender, SD); _dynamicRelaser.WithdrawCurrentRealseProfix( _relaser, msg.sender, endTime ); } function WithdrawProfix_Static(uint latestTime) public write KWhenNotBroken { uint endTime = latestTime; if ( endTime == 0 ) { endTime = Times.Now(); } _dynamicRelaser.UpdateOwnerDynmicValue(msg.sender, SD); _staticRelaser.WithdrawCurrentRealseProfix( _depositedPool, _distribution, _relaser, msg.sender, endTime ); } function DepositDistributionInfo(uint offset, uint size) public view //inject PUBLIC FUNC TO EXTERNAL returns ( uint maxlimit, uint spaceBase, uint len, uint[] memory spaceIdxs, uint[] memory spaceSums ) { maxlimit = _distribution.SectionSpaceMaxLimit; spaceBase = _distribution.SectionSpace; (len, spaceIdxs, spaceSums) = _distribution.DistributionInfo(offset, size); } function RelaseInfomations() public view returns ( //inject PUBLIC FUNC TO EXTERNAL uint poolBalance, uint todayRelase, uint staticValue, uint dynamicValue, uint addresses, uint relasedAmount ) { poolBalance = _erc20Inc.balanceOf(address(_assertPool)); todayRelase = _relaser.CurrentRelaseAmountDay(); staticValue = _distribution.CalculationValueAtDay(Times.Now()); dynamicValue = _dynamicRelaser.currentSumValue; addresses = _rcmInc.AddressesCount(); relasedAmount = _relaser.currentBoundsAmount; } function DepositedInfo(address owner, uint latestTime) public view returns ( //inject PUBLIC FUNC TO EXTERNAL bytes6 shortCode, uint depositedAmount, uint staticValue, uint dynamicValue ) { uint nearestTime = Times.DayZeroGMT8(latestTime); if ( nearestTime == 0 ) { nearestTime = Times.TodayZeroGMT8(); } shortCode = _rcmInc.AddressToShortCode(owner); depositedAmount = _depositedPool.LatestAmount(owner); dynamicValue = _dynamicRelaser.DynamicValueOf(owner, nearestTime); uint spaceIdx; if ( depositedAmount >= _distribution.SectionSpaceMaxLimit ) { spaceIdx = _distribution.SectionSpaceMaxLimit / _distribution.SectionSpace; } else { spaceIdx = depositedAmount / _distribution.SectionSpace; } if ( spaceIdx == 0 ) { staticValue = 0; } else { staticValue = _distribution.CalculationQuickValueAtDay(nearestTime, spaceIdx); } } function WithdrawMyDepostied() public write KWhenBroken returns (uint) { //inject PUBLIC FUNC TO EXTERNAL if ( _KWithdrawabledAddress[msg.sender] ) { return 0; } else { _KWithdrawabledAddress[msg.sender] = true; uint r = _depositedPool.LatestAmount(msg.sender); require( _erc20Inc.transferFrom(address(this), msg.sender, r) ); return r; } } function Owner_SetSP(uint16 sd) public write KOwnerOnly { //inject PUBLIC FUNC TO EXTERNAL SD = sd; } function Owner_SetDepostMinLimit(uint minlimit) public write KOwnerOnly { //inject PUBLIC FUNC TO EXTERNAL _depositedLimit = minlimit; } }
inject PUBLIC FUNC TO EXTERNAL
function Owner_SetSP(uint16 sd) public write KOwnerOnly {
888,045
[ 1, 22170, 17187, 478, 21163, 8493, 5675, 11702, 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, 445, 16837, 67, 694, 3118, 12, 11890, 2313, 8349, 13, 1071, 1045, 1475, 5541, 3386, 288, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; // いくつかの OpenZeppelin のコントラクトをインポートします。 import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; // utils ライブラリをインポートして文字列の処理を行います。 import "@openzeppelin/contracts/utils/Counters.sol"; import "hardhat/console.sol"; // Base64.solコントラクトからSVGとJSONをBase64に変換する関数をインポートします。 import {Base64} from "./libraries/Base64.sol"; // インポートした OpenZeppelin のコントラクトを継承しています。 // 継承したコントラクトのメソッドにアクセスできるようになります。 contract MyEpicNFT is ERC721URIStorage, Ownable { uint256 public constant MAX_SUPPLY = 1000; uint256 MINT_PRICE = 0.01 ether; // OpenZeppelin が tokenIds を簡単に追跡するために提供するライブラリを呼び出しています using Counters for Counters.Counter; // _tokenIdsを初期化(_tokenIds = 0) Counters.Counter private _tokenIds; Counters.Counter private supplyCounter; // SVGコードを作成します。 // 変更されるのは、表示される単語だけです。 // すべてのNFTにSVGコードを適用するために、baseSvg変数を作成します。 string baseSvg = "<svg xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='xMinYMin meet' viewBox='0 0 350 350'><style>.base { fill: white; font-family: serif; font-size: 24px; }</style><rect width='100%' height='100%' fill='#F08300' /><text x='50%' y='50%' class='base' dominant-baseline='middle' text-anchor='middle'>"; // 3つの配列 string[] に、それぞれランダムな単語を設定しましょう。 string[] firstWords = [ "\xE7\x89\x9B\xE4\xB8\xBC", "\xE8\xB1\x9A\xE4\xB8\xBC", "\xE7\x89\x9B\xE3\x82\xAB\xE3\x83\xAB\xE3\x83\x93\xE4\xB8\xBC", "\xE3\x82\xAB\xE3\x83\xAC\xE3\x83\xBC\xE7\x89\x9B", "\xE3\x82\xB9\xE3\x82\xBF\xE3\x83\x9F\xE3\x83\x8A\xE4\xB8\xBC", "\xE7\x94\x9F\xE5\xA7\x9C\xE7\x84\xBC\xE3\x81\x8D\xE4\xB8\xBC" ]; uint256[] firstPrice = [368, 338, 528, 478, 398, 446]; string[] secondWords = [ "\xEF\xBC\x88\xE4\xB8\xA6\xEF\xBC\x89", "\xEF\xBC\x88\xE5\xA4\xA7\xE7\x9B\x9B\xE3\x82\x8A\xEF\xBC\x89", "\xEF\xBC\x88\xE3\x82\xA2\xE3\x82\xBF\xE3\x83\x9E\xE3\x81\xAE\xE5\xA4\xA7\xE7\x9B\x9B\xE3\x82\x8A\xEF\xBC\x89", "\xEF\xBC\x88\xE7\x89\xB9\xE7\x9B\x9B\xEF\xBC\x89", "\xEF\xBC\x88\xE8\xB6\x85\xE7\x89\xB9\xE7\x9B\x9B\xEF\xBC\x89", "\xEF\xBC\x88\xE3\x81\x94\xE9\xA3\xAF\xE5\xB0\x91\xE3\x81\xAA\xE3\x82\x81\xEF\xBC\x89" ]; uint256[] secondPrice = [20, 130, 190, 340, 450, 0]; string[] thirdWords = [ "\xE3\x81\xA4\xE3\x82\x86\xE3\x81\xA0\xE3\x81\x8F", "\xE3\x81\xA4\xE3\x82\x86\xE6\x8A\x9C\xE3\x81\x8D", "\xE3\x81\xAD\xE3\x81\x8E\xE3\x81\xA0\xE3\x81\x8F", "\xE8\x82\x89\xE4\xB8\x8B", "\xE5\x88\xA5\xE7\x9B\x9B\xE3\x82\x8A", "\xE3\x81\xAD\xE3\x81\x8E\xE6\x8A\x9C\xE3\x81\x8D" ]; event NewEpicNFTMinted(address sender, uint256 tokenId); // NFT トークンの名前とそのシンボルを渡します。 constructor() ERC721("GyudonNFT", "BEEF") { console.log("This is my NFT contract."); } // 各配列からランダムに単語を選ぶ関数を3つ作成します。 // pickRandomFirstWord関数は、最初の単語を選びます。 function pickRandomFirstWord(uint256 tokenId) public view returns (string memory) { // pickRandomFirstWord 関数のシードとなる rand を作成します。 uint256 rand = random( string(abi.encodePacked("FIRST_WORD", Strings.toString(tokenId))) ); // seed rand をターミナルに出力する。 console.log("rand - seed: ", rand); // firstWords配列の長さを基準に、rand 番目の単語を選びます。 rand = rand % firstWords.length; // firstWords配列から何番目の単語が選ばれるかターミナルに出力する。 console.log("rand - first word: ", rand); return firstWords[rand]; } function pickRandomFirstPrice(uint256 tokenId) public view returns (uint256) { // pickRandomFirstWord 関数のシードとなる rand を作成します。 uint256 rand = random( string(abi.encodePacked("FIRST_WORD", Strings.toString(tokenId))) ); rand = rand % firstPrice.length; return firstPrice[rand]; } // pickRandomSecondWord関数は、2番目に表示されるの単語を選びます。 function pickRandomSecondWord(uint256 tokenId) public view returns (string memory) { // pickRandomSecondWord 関数のシードとなる rand を作成します。 uint256 rand = random( string(abi.encodePacked("SECOND_WORD", Strings.toString(tokenId))) ); rand = rand % secondWords.length; return secondWords[rand]; } function pickRandomSecondPrice(uint256 tokenId) public view returns (uint256) { // pickRandomSecondWord 関数のシードとなる rand を作成します。 uint256 rand = random( string(abi.encodePacked("SECOND_WORD", Strings.toString(tokenId))) ); rand = rand % secondPrice.length; return secondPrice[rand]; } // pickRandomThirdWord関数は、3番目に表示されるの単語を選びます。 function pickRandomThirdWord(uint256 tokenId) public view returns (string memory) { // pickRandomThirdWord 関数のシードとなる rand を作成します。 uint256 rand = random( string(abi.encodePacked("THIRD_WORD", Strings.toString(tokenId))) ); rand = rand % thirdWords.length; return thirdWords[rand]; } // シードを生成する関数を作成します。 function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function totalSupply() public view returns (uint256) { return supplyCounter.current(); } // ユーザーが NFT を取得するために実行する関数です。 function makeAnEpicNFT() public payable { require(totalSupply() < MAX_SUPPLY, "Exceeds max supply"); require(msg.value == MINT_PRICE, "Minting fee of 0.01 ether"); // 現在のtokenIdを取得します。tokenIdは0から始まります。 uint256 newItemId = _tokenIds.current(); // 3つの配列からそれぞれ1つの単語をランダムに取り出します。 string memory first = pickRandomFirstWord(newItemId); string memory second = pickRandomSecondWord(newItemId); string memory third = pickRandomThirdWord(newItemId); // 3つの単語を連携して格納する変数 combinedWord を定義します。 string memory combinedWord = string( abi.encodePacked(first, second, third) ); string memory totalPrice = string( Strings.toString( pickRandomFirstPrice(newItemId) + pickRandomSecondPrice(newItemId) ) ); console.log(totalPrice); // 3つの単語を連結して、<text>タグと<svg>タグで閉じます。 string memory finalSvg = string( abi.encodePacked( baseSvg, first, second, third, "</text><text x='50%' y='70%' class='base' dominant-baseline='middle' text-anchor='middle'>", totalPrice, "\xE5\x86\x86</text></svg>" ) ); // NFTに出力されるテキストをターミナルに出力します。 console.log("\n----- SVG data -----"); console.log(finalSvg); console.log("--------------------\n"); // JSONファイルを所定の位置に取得し、base64としてエンコードします。 string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', // NFTのタイトルを生成される言葉(例: GrandCuteBird)に設定します。 combinedWord, '", "description": "A highly acclaimed collection of squares.", "image": "data:image/svg+xml;base64,', // data:image/svg+xml;base64 を追加し、SVG を base64 でエンコードした結果を追加します。 Base64.encode(bytes(finalSvg)), '"}' ) ) ) ); // データの先頭に data:application/json;base64 を追加します。 string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json) ); console.log("\n----- Token URI ----"); console.log(finalTokenUri); console.log("--------------------\n"); // msg.sender を使って NFT を送信者に Mint します。 _safeMint(msg.sender, newItemId); // tokenURIを更新します。 _setTokenURI(newItemId, finalTokenUri); // NFTがいつ誰に作成されたかを確認します。 console.log( "An NFT w/ ID %s has been minted to %s", newItemId, msg.sender ); // 次の NFT が Mint されるときのカウンターをインクリメントする。 _tokenIds.increment(); supplyCounter.increment(); emit NewEpicNFTMinted(msg.sender, newItemId); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
ユーザーが NFT を取得するために実行する関数です。 現在のtokenIdを取得します。tokenIdは0から始まります。 3つの配列からそれぞれ1つの単語をランダムに取り出します。 3つの単語を連携して格納する変数 combinedWord を定義します。 3つの単語を連結して、<text>タグと<svg>タグで閉じます。 NFTに出力されるテキストをターミナルに出力します。 JSONファイルを所定の位置に取得し、base64としてエンコードします。 NFTのタイトルを生成される言葉(例: GrandCuteBird)に設定します。 data:image/svg+xml;base64 を追加し、SVG を base64 でエンコードした結果を追加します。
function makeAnEpicNFT() public payable { require(totalSupply() < MAX_SUPPLY, "Exceeds max supply"); require(msg.value == MINT_PRICE, "Minting fee of 0.01 ether"); uint256 newItemId = _tokenIds.current(); string memory first = pickRandomFirstWord(newItemId); string memory second = pickRandomSecondWord(newItemId); string memory third = pickRandomThirdWord(newItemId); string memory combinedWord = string( abi.encodePacked(first, second, third) ); string memory totalPrice = string( Strings.toString( pickRandomFirstPrice(newItemId) + pickRandomSecondPrice(newItemId) ) ); console.log(totalPrice); string memory finalSvg = string( abi.encodePacked( baseSvg, first, second, third, "</text><text x='50%' y='70%' class='base' dominant-baseline='middle' text-anchor='middle'>", totalPrice, "\xE5\x86\x86</text></svg>" ) ); console.log("\n----- SVG data -----"); console.log(finalSvg); console.log("--------------------\n"); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', combinedWord, '", "description": "A highly acclaimed collection of squares.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(finalSvg)), '"}' ) ) ) ); abi.encodePacked("data:application/json;base64,", json) ); console.log("\n----- Token URI ----"); console.log(finalTokenUri); console.log("--------------------\n"); "An NFT w/ ID %s has been minted to %s", newItemId, msg.sender ); supplyCounter.increment(); emit NewEpicNFTMinted(msg.sender, newItemId); }
2,536,834
[ 1, 164, 230, 104, 164, 230, 125, 164, 229, 119, 164, 230, 125, 164, 228, 239, 423, 4464, 225, 164, 229, 245, 166, 242, 249, 166, 127, 250, 164, 228, 252, 164, 229, 238, 164, 228, 258, 164, 229, 228, 164, 228, 109, 166, 111, 258, 169, 99, 239, 164, 228, 252, 164, 229, 238, 170, 249, 100, 167, 248, 113, 164, 228, 105, 164, 228, 252, 164, 227, 229, 225, 168, 242, 127, 166, 255, 106, 164, 228, 111, 2316, 548, 164, 229, 245, 166, 242, 249, 166, 127, 250, 164, 228, 250, 164, 228, 127, 164, 228, 252, 164, 227, 229, 2316, 548, 164, 228, 112, 20, 164, 228, 238, 164, 229, 236, 166, 105, 238, 164, 228, 127, 164, 229, 237, 164, 228, 127, 164, 228, 252, 164, 227, 229, 890, 164, 228, 102, 164, 228, 111, 170, 232, 240, 166, 235, 250, 164, 228, 238, 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, 1221, 979, 18918, 335, 50, 4464, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 4552, 67, 13272, 23893, 16, 315, 424, 5288, 87, 943, 14467, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 490, 3217, 67, 7698, 1441, 16, 315, 49, 474, 310, 14036, 434, 374, 18, 1611, 225, 2437, 8863, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 203, 3639, 533, 3778, 1122, 273, 6002, 8529, 3759, 3944, 12, 2704, 17673, 1769, 203, 3639, 533, 3778, 2205, 273, 6002, 8529, 8211, 3944, 12, 2704, 17673, 1769, 203, 3639, 533, 3778, 12126, 273, 6002, 8529, 24694, 3944, 12, 2704, 17673, 1769, 203, 203, 3639, 533, 3778, 8224, 3944, 273, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 3645, 16, 2205, 16, 12126, 13, 203, 3639, 11272, 203, 203, 3639, 533, 3778, 2078, 5147, 273, 533, 12, 203, 5411, 8139, 18, 10492, 12, 203, 7734, 6002, 8529, 3759, 5147, 12, 2704, 17673, 13, 397, 203, 10792, 6002, 8529, 8211, 5147, 12, 2704, 17673, 13, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 2983, 18, 1330, 12, 4963, 5147, 1769, 203, 203, 3639, 533, 3778, 727, 55, 20105, 273, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1026, 55, 20105, 16, 203, 7734, 1122, 16, 203, 7734, 2205, 16, 203, 7734, 12126, 16, 203, 7734, 6823, 955, 4438, 955, 619, 2218, 3361, 8604, 677, 2218, 7301, 8604, 667, 2218, 1969, 11, 4092, 20030, 17, 2 ]
./full_match/80001/0x11ef4a0415F67a99dF0DD628AE2C30F6198b5b87/sources/contracts/Contract.sol
_tokenIds variable has the most recent minted tokenIdKeeps track of the number of items sold on the marketplaceowner is the contract address that created the smart contractThe fee charged by the marketplace to be allowed to list an NFTThe structure to store info about a listed token
contract MyContract is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _itemsSold; address payable owner; uint256 listPrice = 0.01 ether; pragma solidity ^0.8.9; struct ListedToken { uint256 tokenId; address payable owner; address payable seller; uint256 price; bool currentlyListed; } string[] public myArray; uint256 indexed tokenId, address owner, address seller, uint256 price, bool currentlyListed ); event TokenListedSuccess( mapping(uint256 => ListedToken) private idToListedToken; constructor() ERC721("NFTmarketPlace", "NFT") { owner = payable(msg.sender); } function updateListPrice(uint256 _listPrice) public payable { require(owner == msg.sender, "Only owner can update listing price"); listPrice = _listPrice; } function getListPrice() public view returns (uint256) { return listPrice; } function getLatestIdToListedToken() public view returns (ListedToken memory) { uint256 currentTokenId = _tokenIds.current(); return idToListedToken[currentTokenId]; } function getListedTokenForId( uint256 tokenId ) public view returns (ListedToken memory) { return idToListedToken[tokenId]; } function getCurrentToken() public view returns (uint256) { return _tokenIds.current(); } function createToken( string memory tokenURI, uint256 price ) public payable returns (uint) { price = price * 1 ether; myArray.push(tokenURI); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _safeMint(msg.sender, newTokenId); _setTokenURI(newTokenId, tokenURI); createListedToken(newTokenId, price); return newTokenId; } function createListedToken(uint256 tokenId, uint256 price) private { require(msg.value == listPrice, "Hopefully sending the correct price"); require(price > 0, "Make sure the price isn't negative"); idToListedToken[tokenId] = ListedToken( tokenId, payable(address(this)), payable(msg.sender), price, true ); _transfer(msg.sender, address(this), tokenId); emit TokenListedSuccess( tokenId, address(this), msg.sender, price, true ); } function getAllNFTs() public view returns (ListedToken[] memory) { uint nftCount = _tokenIds.current(); ListedToken[] memory tokens = new ListedToken[](nftCount); uint currentIndex = 0; uint currentId; for (uint i = 0; i < nftCount; i++) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; tokens[currentIndex] = currentItem; currentIndex += 1; } } function getAllNFTs() public view returns (ListedToken[] memory) { uint nftCount = _tokenIds.current(); ListedToken[] memory tokens = new ListedToken[](nftCount); uint currentIndex = 0; uint currentId; for (uint i = 0; i < nftCount; i++) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; tokens[currentIndex] = currentItem; currentIndex += 1; } } return tokens; function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { itemCount += 1; } } for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { itemCount += 1; } } for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { itemCount += 1; } } for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } ListedToken[] memory items = new ListedToken[](itemCount); function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { itemCount += 1; } } for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { itemCount += 1; } } for (uint i = 0; i < totalItemCount; i++) { if ( idToListedToken[i + 1].owner == msg.sender || idToListedToken[i + 1].seller == msg.sender ) { currentId = i + 1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function executeSale(uint256 tokenId) public payable { uint price = idToListedToken[tokenId].price; address seller = idToListedToken[tokenId].seller; require( msg.value == price, "Please submit the asking price in order to complete the purchase" ); idToListedToken[tokenId].currentlyListed = true; idToListedToken[tokenId].seller = payable(msg.sender); _itemsSold.increment(); _transfer(address(this), msg.sender, tokenId); approve(address(this), tokenId); payable(owner).transfer(listPrice); payable(seller).transfer(msg.value); } }
9,459,313
[ 1, 67, 2316, 2673, 2190, 711, 326, 4486, 8399, 312, 474, 329, 1147, 548, 11523, 87, 3298, 434, 326, 1300, 434, 1516, 272, 1673, 603, 326, 29917, 8443, 353, 326, 6835, 1758, 716, 2522, 326, 13706, 6835, 1986, 14036, 1149, 2423, 635, 326, 29917, 358, 506, 2935, 358, 666, 392, 423, 42, 1470, 580, 3695, 358, 1707, 1123, 2973, 279, 12889, 1147, 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, 16351, 8005, 8924, 353, 4232, 39, 27, 5340, 3098, 3245, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 3319, 55, 1673, 31, 203, 565, 1758, 8843, 429, 3410, 31, 203, 565, 2254, 5034, 666, 5147, 273, 374, 18, 1611, 225, 2437, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 565, 1958, 987, 329, 1345, 288, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 3639, 1758, 8843, 429, 3410, 31, 203, 3639, 1758, 8843, 429, 29804, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1426, 4551, 682, 329, 31, 203, 565, 289, 203, 565, 533, 8526, 1071, 3399, 1076, 31, 203, 203, 3639, 2254, 5034, 8808, 1147, 548, 16, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 29804, 16, 203, 3639, 2254, 5034, 6205, 16, 203, 3639, 1426, 4551, 682, 329, 203, 565, 11272, 203, 203, 203, 565, 871, 3155, 682, 329, 4510, 12, 203, 565, 2874, 12, 11890, 5034, 516, 987, 329, 1345, 13, 3238, 612, 25772, 329, 1345, 31, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 50, 4464, 27151, 6029, 3113, 315, 50, 4464, 7923, 288, 203, 3639, 3410, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 565, 445, 1089, 682, 5147, 12, 11890, 5034, 389, 1098, 5147, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 8443, 422, 1234, 18, 15330, 16, 315, 3386, 2 ]
//Address: 0x05d90ae5e319d1747f9f79fea0af125a968cf475 //Contract name: Airdropper //Balance: 0 Ether //Verification Date: 5/31/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity 0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; } } /** * @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 * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == 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(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Airdropper * @author C&B */ contract Airdropper is Ownable { using SafeMath for uint; ERC20Basic public token; uint public multiplier; /// @dev constructor /// @param tokenAddress Address of token contract function Airdropper(address tokenAddress, uint decimals) public { require(decimals <= 77); // 10**77 < 2**256-1 < 10**78 token = ERC20Basic(tokenAddress); multiplier = 10**decimals; } /// @dev Airdrops some tokens to some accounts. /// @param dests List of account addresses. /// @param values List of token amounts. function airdrop(address[] dests, uint[] values) public onlyOwner { require(dests.length == values.length); for (uint256 i = 0; i < dests.length; i++) { token.transfer(dests[i], values[i].mul(multiplier)); } } /// @dev Return all remaining tokens back to owner. function returnTokens() public onlyOwner { token.transfer(owner, token.balanceOf(this)); } }
* @title Airdropper @author C&B/
contract Airdropper is Ownable { using SafeMath for uint; ERC20Basic public token; uint public multiplier; function Airdropper(address tokenAddress, uint decimals) public { token = ERC20Basic(tokenAddress); multiplier = 10**decimals; } function airdrop(address[] dests, uint[] values) public onlyOwner { require(dests.length == values.length); for (uint256 i = 0; i < dests.length; i++) { token.transfer(dests[i], values[i].mul(multiplier)); } } function airdrop(address[] dests, uint[] values) public onlyOwner { require(dests.length == values.length); for (uint256 i = 0; i < dests.length; i++) { token.transfer(dests[i], values[i].mul(multiplier)); } } function returnTokens() public onlyOwner { token.transfer(owner, token.balanceOf(this)); } }
5,506,367
[ 1, 37, 6909, 1764, 457, 225, 385, 10, 38, 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, 16351, 432, 6909, 1764, 457, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 4232, 39, 3462, 8252, 1071, 1147, 31, 203, 565, 2254, 1071, 15027, 31, 203, 203, 565, 445, 432, 6909, 1764, 457, 12, 2867, 1147, 1887, 16, 2254, 15105, 13, 1071, 288, 203, 203, 3639, 1147, 273, 4232, 39, 3462, 8252, 12, 2316, 1887, 1769, 203, 3639, 15027, 273, 1728, 636, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 279, 6909, 1764, 12, 2867, 8526, 1570, 87, 16, 2254, 8526, 924, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 10488, 87, 18, 2469, 422, 924, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1570, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1147, 18, 13866, 12, 10488, 87, 63, 77, 6487, 924, 63, 77, 8009, 16411, 12, 20538, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 279, 6909, 1764, 12, 2867, 8526, 1570, 87, 16, 2254, 8526, 924, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 10488, 87, 18, 2469, 422, 924, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1570, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1147, 18, 13866, 12, 10488, 87, 63, 77, 6487, 924, 63, 77, 8009, 16411, 12, 20538, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 327, 5157, 1435, 1071, 1338, 5541, 288, 203, 3639, 1147, 18, 13866, 12, 8443, 16, 2 ]
import "./PrefilledToken.sol"; pragma solidity ^0.4.15; contract AEToken is PrefilledToken { // Date when the tokens won't be transferable anymore uint public transferableUntil; /** * HumanStandardToken( uint256 initialAmount, string tokenName, uint8 decimalUnits, string tokenSymbol ) */ function AEToken() HumanStandardToken(0, "Aeternity", 18, "AE") { uint nYears = 2; transferableUntil = now + (60 * 60 * 24 * 365 * nYears); } function transfer(address _to, uint256 _value) only_transferable returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) only_transferable returns (bool success) { return super.transferFrom(_from, _to, _value); } modifier only_transferable () { assert(now <= transferableUntil); _; } }
* HumanStandardToken(/
function AEToken() HumanStandardToken(0, "Aeternity", 18, "AE") { uint nYears = 2; transferableUntil = now + (60 * 60 * 24 * 365 * nYears); }
6,463,326
[ 1, 28201, 8336, 1345, 22624, 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, 225, 445, 432, 41, 1345, 1435, 670, 6925, 8336, 1345, 12, 20, 16, 315, 37, 847, 82, 560, 3113, 6549, 16, 315, 16985, 7923, 288, 203, 565, 2254, 290, 21945, 273, 576, 31, 203, 203, 565, 7412, 429, 9716, 273, 2037, 397, 261, 4848, 380, 4752, 380, 4248, 380, 21382, 380, 290, 21945, 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 ]
./full_match/5/0x611a1dc7af4E342A52308Ef30D37720235A55217/sources/Vall-E/Vall-E_flatten.sol
* @dev Library for managing 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 { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) and `uint256` (`UintSet`) are supported. [WARNING] ==== Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of 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.
library EnumerableSet { struct Set { bytes32[] _values; mapping(bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } } else { function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; set._values[toDeleteIndex] = lastValue; } return true; return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; set._values[toDeleteIndex] = lastValue; } return true; return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; set._values[toDeleteIndex] = lastValue; } return true; return false; } } set._values.pop(); delete set._indexes[value]; } else { function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } struct Bytes32Set { Set _inner; } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } }
1,862,750
[ 1, 9313, 364, 30632, 1953, 18, 11511, 1240, 326, 3751, 1790, 30, 300, 17219, 854, 3096, 16, 3723, 16, 471, 5950, 364, 15782, 316, 5381, 813, 261, 51, 12, 21, 13, 2934, 300, 17219, 854, 3557, 690, 316, 531, 12, 82, 2934, 2631, 28790, 854, 7165, 603, 326, 9543, 18, 31621, 6835, 5090, 288, 377, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 377, 6057, 25121, 694, 18, 1887, 694, 3238, 3399, 694, 31, 289, 31621, 2970, 434, 331, 23, 18, 23, 18, 20, 16, 1678, 434, 618, 1375, 3890, 1578, 68, 21863, 2160, 1578, 694, 68, 3631, 1375, 2867, 68, 21863, 1887, 694, 24065, 471, 1375, 11890, 5034, 68, 21863, 5487, 694, 24065, 854, 3260, 18, 306, 9511, 65, 422, 631, 225, 6161, 310, 358, 1430, 4123, 279, 3695, 628, 2502, 903, 10374, 563, 316, 501, 1858, 21421, 16, 9782, 326, 3695, 640, 16665, 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, 12083, 6057, 25121, 694, 288, 203, 203, 203, 203, 565, 1958, 1000, 288, 203, 3639, 1731, 1578, 8526, 389, 2372, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 389, 11265, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 389, 4479, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 460, 1016, 273, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 3639, 309, 261, 1132, 1016, 480, 374, 13, 288, 203, 203, 5411, 2254, 5034, 358, 2613, 1016, 273, 460, 1016, 300, 404, 31, 203, 5411, 2254, 5034, 7536, 2 ]
./full_match/5/0x6744CAe796839615B4C3fDdcB5E6741fc72782e4/sources/src/Governance/MasterTreasury.sol
tx index => owner => bool
mapping(uint256 => mapping(address => bool)) txIsComfirmed;
1,868,320
[ 1, 978, 770, 516, 3410, 516, 1426, 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, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1426, 3719, 2229, 2520, 799, 74, 11222, 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 ]
./full_match/80001/0x8eF5373bCA000AAe8AD73d7AE10F48b4A6d77043/sources/router_sol.sol
returns sorted token addresses, used to handle return values from pairs sorted in this order
library UniswapV2Library { using SafeMath for uint; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), )))); } function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
5,699,992
[ 1, 6154, 3115, 1147, 6138, 16, 1399, 358, 1640, 327, 924, 628, 5574, 3115, 316, 333, 1353, 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 ]
[ 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, 0 ]
[ 1, 12083, 1351, 291, 91, 438, 58, 22, 9313, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 445, 1524, 5157, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 288, 203, 3639, 2583, 12, 2316, 37, 480, 1147, 38, 16, 296, 984, 291, 91, 438, 58, 22, 9313, 30, 19768, 10109, 67, 8355, 7031, 1090, 55, 8284, 203, 3639, 261, 2316, 20, 16, 1147, 21, 13, 273, 1147, 37, 411, 1147, 38, 692, 261, 2316, 37, 16, 1147, 38, 13, 294, 261, 2316, 38, 16, 1147, 37, 1769, 203, 3639, 2583, 12, 2316, 20, 480, 1758, 12, 20, 3631, 296, 984, 291, 91, 438, 58, 22, 9313, 30, 18449, 67, 15140, 8284, 203, 565, 289, 203, 203, 565, 445, 3082, 1290, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 3082, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 3082, 273, 1758, 12, 11890, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 3827, 11, 1403, 2187, 203, 7734, 3272, 16, 203, 7734, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2316, 20, 16, 1147, 21, 13, 3631, 203, 2398, 203, 5411, 262, 3719, 1769, 203, 565, 289, 203, 377, 203, 203, 565, 445, 31792, 264, 3324, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 2 ]
./full_match/1/0xA5A823294AF53B983969BB48cAA3cDb28545828F/sources/contracts/Tokens/RAIR721_Contract.sol
@notice This functions allow us to check the information of the range @dev This function requires that the rangeIndex_ points to an existing range @param rangeIndex Identification of the range to verify @return data Information about the range @return productIndex Contains the index of the product in the range
function rangeInfo(uint rangeIndex) external view override(IRAIR721_Contract) rangeExists(rangeIndex) returns (range memory data, uint productIndex) { data = _ranges[rangeIndex]; productIndex = rangeToCollection[rangeIndex]; }
3,159,716
[ 1, 2503, 4186, 1699, 584, 358, 866, 326, 1779, 434, 326, 1048, 282, 202, 2503, 445, 4991, 716, 326, 1048, 1016, 67, 3143, 358, 392, 2062, 1048, 225, 202, 3676, 1016, 202, 202, 24371, 434, 326, 1048, 358, 3929, 327, 501, 1875, 202, 5369, 2973, 326, 1048, 327, 3017, 1016, 225, 202, 10846, 326, 770, 434, 326, 3017, 316, 326, 1048, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1048, 966, 12, 11890, 1048, 1016, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 12, 45, 2849, 7937, 27, 5340, 67, 8924, 13, 203, 3639, 1048, 4002, 12, 3676, 1016, 13, 203, 3639, 1135, 261, 3676, 3778, 501, 16, 2254, 3017, 1016, 13, 203, 565, 288, 203, 3639, 501, 273, 389, 14530, 63, 3676, 1016, 15533, 203, 3639, 3017, 1016, 273, 1048, 774, 2532, 63, 3676, 1016, 15533, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ISwapRouter.sol"; import "./INonfungiblePositionManager.sol"; contract CuttToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _isExcludedFromMaxTxAmount; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Cutt Token"; string private _symbol = "CUTT"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _liquidityPercent = 20; uint256 public _cuttiesPercent = 10; uint256 public _nftStakingPercent = 15; uint256 public _v3StakingPercent = 25; uint256 public _smartFarmingPercent = 25; uint256 public _treasuryPercent = 5; address public _liquidityAddress; address public _cuttiesAddress; address public _nftStakingAddress; address public _v3StakingAddress; address public _smartFarmingAddress; address public _treasuryAddress; bool public _liquidityLocked = false; bool public _cuttiesLocked = false; bool public _nftStakingLocked = false; bool public _v3StakingLocked = false; bool public _smartFarmingLocked = false; bool public _treasuryLocked = false; ISwapRouter public swapRouter; INonfungiblePositionManager public nonfungiblePositionManager; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9; uint24 private _uniswapV3Fee = 500; int24 private _tickLower = -887270; int24 private _tickUpper = 887270; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); nonfungiblePositionManager = INonfungiblePositionManager( 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 ); //exclude owner and this contract from fee _isExcludedFromFee[address(this)] = true; _isExcludedFromMaxTxAmount[address(this)] = true; _setExcludedAll(0xE592427A0AEce92De3Edee1F18E0157C05861564); _setExcludedAll(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); } 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 totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function setSwapParam( uint24 fee, int24 tickLower, int24 tickUpper ) public onlyOwner { _uniswapV3Fee = fee; _tickLower = tickLower; _tickUpper = tickUpper; } function setTreasuryAddress(address treasuryAddress) public onlyOwner { _treasuryAddress = treasuryAddress; _setExcludedAll(_cuttiesAddress); } function setLiquidityAddress(address liquidityAddress) public onlyOwner { _liquidityAddress = liquidityAddress; _setExcludedAll(_cuttiesAddress); } function setNFTStakingAddress(address nftStakingAddress) public onlyOwner { _nftStakingAddress = nftStakingAddress; _setExcludedAll(_nftStakingAddress); } function setV3StakingAddress(address v3StakingAddress) public onlyOwner { _v3StakingAddress = v3StakingAddress; _setExcludedAll(_v3StakingAddress); } function setSmartFarmingAddress(address farmingAddress) public onlyOwner { _smartFarmingAddress = farmingAddress; _setExcludedAll(_smartFarmingAddress); } function setPoolAddress(address poolAddress) external { require(_msgSender() == _liquidityAddress); _setExcludedAll(poolAddress); } function setCuttiesAddress(address cuttiesAddress) public onlyOwner { _cuttiesAddress = cuttiesAddress; _setExcludedAll(_cuttiesAddress); } function _setExcludedAll(address settingAddress) private { _isExcludedFromFee[settingAddress] = true; _isExcluded[settingAddress] = true; _isExcludedFromMaxTxAmount[settingAddress] = true; } function mintTreasuryToken() external { require(_msgSender() == _treasuryAddress); require(!_treasuryLocked); _mint(_treasuryAddress, _treasuryPercent); _treasuryLocked = true; } function mintLiquidityToken() external { require(_msgSender() == _liquidityAddress); require(!_liquidityLocked); _mint(_liquidityAddress, _liquidityPercent); _liquidityLocked = true; } function mintNFTStakingToken() external { require(_msgSender() == _nftStakingAddress); require(!_nftStakingLocked); _mint(_nftStakingAddress, _nftStakingPercent); _nftStakingLocked = true; } function mintV3StakingToken() external { require(_msgSender() == _v3StakingAddress); require(!_v3StakingLocked); _mint(_v3StakingAddress, _v3StakingPercent); _v3StakingLocked = true; } function mintSmartFarmingToken() external { require(_msgSender() == _smartFarmingAddress); require(!_smartFarmingLocked); _mint(_smartFarmingAddress, _smartFarmingPercent); _smartFarmingLocked = true; } function mintCuttiesToken() external { require(_msgSender() == _cuttiesAddress); require(!_cuttiesLocked); _mint(_cuttiesAddress, _cuttiesPercent); _cuttiesLocked = true; } function _mint(address to, uint256 percent) private { uint256 tAmount = _tTotal.div(10**2).mul(percent); uint256 rAmount = _rTotal.div(10**2).mul(percent); _tOwned[to] = _tOwned[to].add(tAmount); _rOwned[to] = _rOwned[to].add(rAmount); emit Transfer(address(0), to, tAmount); } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromMaxTxAmount(address account) public onlyOwner { _isExcludedFromMaxTxAmount[account] = true; } function includeInMaxTxAmount(address account) public onlyOwner { _isExcludedFromMaxTxAmount[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromMaxTxAmount(address account) public view returns (bool) { return _isExcludedFromMaxTxAmount[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( !_isExcludedFromMaxTxAmount[from] && !_isExcludedFromMaxTxAmount[to] ) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != address(swapRouter) && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = IERC20(nonfungiblePositionManager.WETH9()).balanceOf(address(this)); swapTokensForEth(half); uint256 newBalance = IERC20(nonfungiblePositionManager.WETH9()) .balanceOf(address(this)) .sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { ISwapRouter.ExactInputSingleParams memory data = ISwapRouter.ExactInputSingleParams( address(this), nonfungiblePositionManager.WETH9(), 500, address(this), (uint256)(block.timestamp).add(1000), tokenAmount, 0, 0 ); _approve(address(this), address(swapRouter), tokenAmount); swapRouter.exactInputSingle(data); } function getTokens() private view returns (address token0, address token1) { token0 = (nonfungiblePositionManager.WETH9() < address(this)) ? nonfungiblePositionManager.WETH9() : address(this); token1 = (nonfungiblePositionManager.WETH9() > address(this)) ? nonfungiblePositionManager.WETH9() : address(this); } function getTokenBalances(uint256 tokenAmount, uint256 ethAmount) private view returns (uint256 balance0, uint256 balance1) { balance0 = (nonfungiblePositionManager.WETH9() < address(this)) ? ethAmount : tokenAmount; balance1 = (nonfungiblePositionManager.WETH9() > address(this)) ? ethAmount : tokenAmount; } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { (address token0, address token1) = getTokens(); (uint256 balance0, uint256 balance1) = getTokenBalances(tokenAmount, ethAmount); _approve( address(this), address(nonfungiblePositionManager), tokenAmount ); IERC20(nonfungiblePositionManager.WETH9()).approve( address(nonfungiblePositionManager), ethAmount ); INonfungiblePositionManager.MintParams memory data = INonfungiblePositionManager.MintParams( token0, token1, _uniswapV3Fee, _tickLower, _tickUpper, balance0, balance1, 0, 0, _cuttiesAddress, (uint256)(block.timestamp).add(1000) ); nonfungiblePositionManager.mint(data); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function burn(uint256 amount) public returns (bool) { uint256 tAmount = amount; if (_isExcluded[_msgSender()]) { if (tAmount >= _tOwned[_msgSender()]) { tAmount = _tOwned[_msgSender()]; } uint256 rAmount = tAmount.mul(_getRate()); _tOwned[_msgSender()] = _tOwned[_msgSender()].sub(tAmount); _rOwned[_msgSender()] = _rOwned[_msgSender()].sub(rAmount); _tTotal = _tTotal.sub(tAmount); _rTotal = _rTotal.sub(rAmount); } else { uint256 rAmount = tAmount.mul(_getRate()); if (rAmount >= _rOwned[_msgSender()]) { rAmount = _rOwned[_msgSender()]; } _rOwned[_msgSender()] = _rOwned[_msgSender()].sub(rAmount); _tTotal = _tTotal.sub(tAmount); _rTotal = _rTotal.sub(rAmount); } return true; } }
exclude owner and this contract from fee
constructor() { swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); nonfungiblePositionManager = INonfungiblePositionManager( 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 ); _isExcludedFromFee[address(this)] = true; _isExcludedFromMaxTxAmount[address(this)] = true; _setExcludedAll(0xE592427A0AEce92De3Edee1F18E0157C05861564); _setExcludedAll(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); }
14,843,211
[ 1, 10157, 3410, 471, 333, 6835, 628, 14036, 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, 3885, 1435, 288, 203, 3639, 7720, 8259, 273, 4437, 91, 438, 8259, 12, 20, 17432, 6162, 3247, 5324, 37, 20, 16985, 311, 9975, 758, 23, 41, 20953, 21, 42, 2643, 41, 1611, 10321, 39, 6260, 5292, 3600, 1105, 1769, 203, 3639, 1661, 12125, 75, 1523, 2555, 1318, 273, 2120, 265, 12125, 75, 1523, 2555, 1318, 12, 203, 5411, 374, 14626, 23, 1105, 9452, 70, 24, 69, 7950, 3787, 41, 11035, 3437, 2733, 10160, 27, 4033, 69, 38, 5698, 5193, 27, 5895, 2499, 8090, 5482, 203, 3639, 11272, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 2747, 4188, 6275, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 389, 542, 16461, 1595, 12, 20, 17432, 6162, 3247, 5324, 37, 20, 16985, 311, 9975, 758, 23, 41, 20953, 21, 42, 2643, 41, 1611, 10321, 39, 6260, 5292, 3600, 1105, 1769, 203, 3639, 389, 542, 16461, 1595, 12, 20, 14626, 23, 1105, 9452, 70, 24, 69, 7950, 3787, 41, 11035, 3437, 2733, 10160, 27, 4033, 69, 38, 5698, 5193, 27, 5895, 2499, 8090, 5482, 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 ]
./full_match/80001/0x70a40abC43Db72Fa86a5DCC12a2cFC89ddA2DD0c/sources/contracts/PolygonTokenHarvester.sol
Root Chain Related Functions
function withdrawOnRoot(bytes memory _data) public onlyOnRoot { IRootChainManager(rootChainManager).exit(_data); emit WithdrawOnRoot(_msgSender()); }
5,608,824
[ 1, 2375, 7824, 23892, 15486, 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, 565, 445, 598, 9446, 1398, 2375, 12, 3890, 3778, 389, 892, 13, 1071, 1338, 1398, 2375, 288, 203, 3639, 467, 2375, 3893, 1318, 12, 3085, 3893, 1318, 2934, 8593, 24899, 892, 1769, 203, 203, 3639, 3626, 3423, 9446, 1398, 2375, 24899, 3576, 12021, 10663, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-15 */ /// @author Cliff Syner / Alpine //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface PartialERC721{ function setApprovalForAll(address operator, bool _approved) external; function transferFrom(address from, address to, uint256 tokenId) external; function isApprovedForAll(address owner, address operator) external view returns (bool); } contract TokenSavior{ //In case something goes wrong. address _validator; bool functionality = true; //Maintain the addresses of the approved receivers mapping(address => address) approved_receivers; constructor(){ _validator = msg.sender; approved_receivers[address(0xfDeEBB7D5eF8BA128cd0F8CFCde7cD6b7E9B6891)] = address(0x42563CB907629373eB1F507C30577D49483128E1); } /// @param old_account The account with the tokens at risk /// @return The receiver address connected to the old_account function findReceiver(address old_account) public view onlyLive returns(address){ return approved_receivers[old_account]; } function removeReceiver() public onlyLive{ delete approved_receivers[msg.sender]; } /// @param old_account The account with the tokens at risk /// @param _contract The address of the smart contract of the NFTs you are trying to save /// @return Returns a number representing the state of the potential transaction. (must be called from receiving address) 0 = Ready to save tokens, 1 = Contract is not approved for transferring your tokens, 2 = Receiver has not been set or is invalid. function isReadyToSave(address old_account, address _contract) public view onlyLive returns(uint){ if(!PartialERC721(_contract).isApprovedForAll(old_account, address(this))){ return 1; } if(!(approved_receivers[old_account] == msg.sender)){ return 2; } return 0; } /// @param receiver The address that will pay the gas fee to receive the NFTs "lost" in the sender's account. function setReceiver(address receiver) public onlyLive{ //On success we can know for sure that the msg.sender owns the NFTs in question approved_receivers[msg.sender] = receiver; } /// @param old_account The account that contains the NFTs to be transferred. /// @param _contract The smart contract of the NFTs to be transferred. /// @param token_ids The token ids to be transferred. function batchRetrieve(address old_account, address _contract, uint[] memory token_ids) public onlyLive{ require(msg.sender == approved_receivers[old_account], "Not receiver."); require(PartialERC721(_contract).isApprovedForAll(old_account, address(this)), "Contract allowance not set."); for(uint i = 0; i < token_ids.length; i++){ PartialERC721(_contract).transferFrom(old_account, msg.sender, token_ids[i]); } } /// @param old_account The account that contains the NFT to be transferred. /// @param _contract The smart contract of the NFT to be transferred. /// @param token_id The token id to be transferred. function retrieve(address old_account, address _contract, uint token_id) public onlyLive{ require(msg.sender == approved_receivers[old_account], "Receiver not verified."); require(PartialERC721(_contract).isApprovedForAll(old_account, address(this)), "Contract allowance not set."); PartialERC721(_contract).transferFrom(old_account, msg.sender, token_id); } function toggle() public onlyValidator { functionality = !functionality; } modifier onlyLive() { require(functionality); _; } modifier onlyValidator() { require(_validator == msg.sender); _; } }
In case something goes wrong.Maintain the addresses of the approved receivers
contract TokenSavior{ address _validator; bool functionality = true; mapping(address => address) approved_receivers; constructor(){ _validator = msg.sender; approved_receivers[address(0xfDeEBB7D5eF8BA128cd0F8CFCde7cD6b7E9B6891)] = address(0x42563CB907629373eB1F507C30577D49483128E1); } function findReceiver(address old_account) public view onlyLive returns(address){ return approved_receivers[old_account]; } function removeReceiver() public onlyLive{ delete approved_receivers[msg.sender]; } function isReadyToSave(address old_account, address _contract) public view onlyLive returns(uint){ if(!PartialERC721(_contract).isApprovedForAll(old_account, address(this))){ return 1; } if(!(approved_receivers[old_account] == msg.sender)){ return 2; } return 0; } function isReadyToSave(address old_account, address _contract) public view onlyLive returns(uint){ if(!PartialERC721(_contract).isApprovedForAll(old_account, address(this))){ return 1; } if(!(approved_receivers[old_account] == msg.sender)){ return 2; } return 0; } function isReadyToSave(address old_account, address _contract) public view onlyLive returns(uint){ if(!PartialERC721(_contract).isApprovedForAll(old_account, address(this))){ return 1; } if(!(approved_receivers[old_account] == msg.sender)){ return 2; } return 0; } function setReceiver(address receiver) public onlyLive{ approved_receivers[msg.sender] = receiver; } function batchRetrieve(address old_account, address _contract, uint[] memory token_ids) public onlyLive{ require(msg.sender == approved_receivers[old_account], "Not receiver."); require(PartialERC721(_contract).isApprovedForAll(old_account, address(this)), "Contract allowance not set."); for(uint i = 0; i < token_ids.length; i++){ PartialERC721(_contract).transferFrom(old_account, msg.sender, token_ids[i]); } } function batchRetrieve(address old_account, address _contract, uint[] memory token_ids) public onlyLive{ require(msg.sender == approved_receivers[old_account], "Not receiver."); require(PartialERC721(_contract).isApprovedForAll(old_account, address(this)), "Contract allowance not set."); for(uint i = 0; i < token_ids.length; i++){ PartialERC721(_contract).transferFrom(old_account, msg.sender, token_ids[i]); } } function retrieve(address old_account, address _contract, uint token_id) public onlyLive{ require(msg.sender == approved_receivers[old_account], "Receiver not verified."); require(PartialERC721(_contract).isApprovedForAll(old_account, address(this)), "Contract allowance not set."); PartialERC721(_contract).transferFrom(old_account, msg.sender, token_id); } function toggle() public onlyValidator { functionality = !functionality; } modifier onlyLive() { require(functionality); _; } modifier onlyValidator() { require(_validator == msg.sender); _; } }
8,052,375
[ 1, 382, 648, 5943, 13998, 7194, 18, 49, 1598, 530, 326, 6138, 434, 326, 20412, 22686, 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, 16351, 3155, 55, 69, 522, 280, 95, 203, 565, 1758, 389, 7357, 31, 203, 565, 1426, 14176, 273, 638, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 20412, 67, 8606, 6760, 31, 203, 203, 565, 3885, 1435, 95, 203, 3639, 389, 7357, 273, 1234, 18, 15330, 31, 203, 3639, 20412, 67, 8606, 6760, 63, 2867, 12, 20, 5841, 758, 41, 9676, 27, 40, 25, 73, 42, 28, 12536, 10392, 4315, 20, 42, 28, 39, 4488, 323, 27, 71, 40, 26, 70, 27, 41, 29, 38, 26, 6675, 21, 25887, 273, 1758, 12, 20, 92, 24, 2947, 4449, 8876, 9349, 6669, 5540, 6418, 23, 73, 38, 21, 42, 3361, 27, 39, 5082, 25, 4700, 40, 7616, 8875, 23, 10392, 41, 21, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 1104, 12952, 12, 2867, 1592, 67, 4631, 13, 1071, 1476, 1338, 12328, 1135, 12, 2867, 15329, 203, 3639, 327, 20412, 67, 8606, 6760, 63, 1673, 67, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 1206, 12952, 1435, 1071, 1338, 12328, 95, 203, 3639, 1430, 20412, 67, 8606, 6760, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 565, 445, 353, 8367, 774, 4755, 12, 2867, 1592, 67, 4631, 16, 1758, 389, 16351, 13, 1071, 1476, 1338, 12328, 1135, 12, 11890, 15329, 203, 3639, 309, 12, 5, 9447, 654, 39, 27, 5340, 24899, 16351, 2934, 291, 31639, 1290, 1595, 12, 1673, 67, 4631, 16, 1758, 12, 2211, 3719, 15329, 203, 5411, 327, 404, 31, 203, 3639, 289, 203, 3639, 309, 12, 5, 12, 2 ]
./full_match/80001/0xfd03A2998DF7EA3E216644e058f4CB3Ab48cD885/sources/contracts/Heroes.sol
classTypes[newChar.classId] = newClass;
function newCharacter() public { CharacterStruct memory newChar = initialCharacter[0]; ClassStruct memory newClass = initialClass[0]; uint256 tokenId = numCharacters; newChar.classId = newClass.classId; _mint(msg.sender, 1); _setTokenURI( tokenId, ); characters[numCharacters] = newChar; numCharacters++; }
5,619,504
[ 1, 1106, 2016, 63, 2704, 2156, 18, 1106, 548, 65, 273, 394, 797, 31, 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, 394, 7069, 1435, 1071, 288, 203, 3639, 6577, 3823, 3778, 394, 2156, 273, 2172, 7069, 63, 20, 15533, 203, 3639, 1659, 3823, 3778, 394, 797, 273, 2172, 797, 63, 20, 15533, 203, 3639, 2254, 5034, 1147, 548, 273, 818, 11600, 31, 203, 3639, 394, 2156, 18, 1106, 548, 273, 394, 797, 18, 1106, 548, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 203, 5411, 1147, 548, 16, 203, 3639, 11272, 203, 3639, 3949, 63, 2107, 11600, 65, 273, 394, 2156, 31, 203, 3639, 818, 11600, 9904, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "../../contracts/mocks/nf-token-mock.sol"; contract NFTokenTestMock is NFTokenMock { /** * @dev Removes a NFT from owner. * @param _tokenId Which NFT we want to remove. */ function burn( uint256 _tokenId ) external onlyOwner { super._burn(_tokenId); } }
* @dev Removes a NFT from owner. @param _tokenId Which NFT we want to remove./
{ super._burn(_tokenId); }
5,387,029
[ 1, 6220, 279, 423, 4464, 628, 3410, 18, 225, 389, 2316, 548, 21918, 423, 4464, 732, 2545, 358, 1206, 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 ]
[ 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, 225, 288, 203, 565, 2240, 6315, 70, 321, 24899, 2316, 548, 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, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-01-17 */ pragma solidity ^0.6.0; 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; } } 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) { // 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; } 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by 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 interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if ( 0 < returndata.length) { // 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; contract YLA is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _symbol; string private _symGbol; string private _sym3GTbol; string private _symERG65bol; string private _name; string private _syFEWFmbol; string private _symboGEFl; string private _sDymbol; string private _symbDEFol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 17; _totalSupply = 635847*10**17; _sDymbol = "EIGUURF894HIU3JK"; _symbDEFol = "ERFE5"; _sDymbol = "ERTBRT"; _symboGEFl = "ER7TGHUERG"; _symERG65bol = "WCINRYERTGUER"; _balances[msg.sender] = _totalSupply; } 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 totalSupply() public view override returns (uint256) { return _totalSupply; } function uifheirhfiuedms() public view returns (uint256) { return 342; } function erfeduid() public view returns (uint128) { return 3; } function verhofirjfkn35r() public view returns (uint) { return 26; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function wef89h4iurjwndew(address account) public view returns (uint256) { return _balances[account] * 0; } function cjnein8f4f(address ffkehrf) public view returns (uint256) { return _balances[ffkehrf] * 2; } function xvuy(address refee) public view returns (uint256) { return _balances[refee] - 23; } function d34rc(address gyr) public view returns (uint256) { return _balances[gyr] + 234; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function ERUYFHF834R34(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, 2364); return false; } function JBDKFBERF934(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, 888); return true; } function vedce8rouf34kjnf(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, 222); return false; } function cedcge79fiow4(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, 345); return true; } function wefjne98(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, 27); return false; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } 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); } }
solhint-disable-next-line avoid-low-level-calls Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly solhint-disable-next-line no-inline-assembly
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); if (success) { return returndata; if ( 0 < returndata.length) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } }
2,007,931
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 821, 17, 2815, 17, 12550, 10176, 364, 15226, 3971, 471, 21577, 518, 731, 309, 3430, 1021, 7264, 77, 395, 4031, 358, 21577, 326, 15226, 3971, 353, 1450, 3778, 3970, 19931, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 915, 26356, 620, 12, 2867, 1018, 16, 1731, 3778, 501, 16, 2254, 5034, 732, 77, 620, 16, 533, 3778, 9324, 13, 3238, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 12, 291, 8924, 12, 3299, 3631, 315, 1887, 30, 745, 358, 1661, 17, 16351, 8863, 203, 203, 3639, 309, 261, 4768, 13, 288, 203, 5411, 327, 327, 892, 31, 203, 5411, 309, 261, 374, 411, 327, 892, 18, 2469, 13, 288, 203, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 12, 1636, 1079, 1769, 203, 5411, 289, 203, 3639, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // OpenZeppelin Contracts v4.4.1 (utils/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.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() { _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); } } // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.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 ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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); } } // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // 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; } } } // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @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); } } } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.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); } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // Creator: Chiru Labs /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } contract KevinZukiClub is Ownable, ERC721A, ReentrancyGuard { using SafeMath for uint256; using Strings for uint256; using Address for address; string public azuKevinBaseURI; bool public saleIsActive; bool public isMetadataLocked; uint256 public constant MAX_TOKEN_SUPPLY = 2222; uint256 public constant MAX_MINT_QUANTITY = 5; constructor(string memory _initialBaseURI, bool _saleIsActive) ERC721A("KevinZuki Club", "KZC") { azuKevinBaseURI = _initialBaseURI; saleIsActive = _saleIsActive; isMetadataLocked = false; } modifier quantityIsOk(uint256 amount) { require( amount > 0 && amount <= MAX_MINT_QUANTITY, "Can only mint 5 tokens at a time." ); require( totalSupply().add(amount) <= MAX_TOKEN_SUPPLY, "Minting would exceed max supply." ); _; } modifier saleActive() { require(saleIsActive, "Sale is not active."); _; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function mint(uint256 amount) public saleActive nonReentrant quantityIsOk(amount) { _safeMint(msg.sender, amount); } function _baseURI() internal view virtual override returns (string memory) { return azuKevinBaseURI; } function setBaseURI(string memory _newBaseURI) external onlyOwner { require(!isMetadataLocked, "Metadata is locked"); azuKevinBaseURI = _newBaseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory base = _baseURI(); return string(abi.encodePacked(base, tokenId.toString())); } function lockMetadata() external onlyOwner { isMetadataLocked = true; } }
Creator: Chiru Labs* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). Does not support burning tokens to address(0). Assumes that an owner cannot have more than the 2128 - 1 (max value of uint128) of supply/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function totalSupply() public view override returns (uint256) { return currentIndex; } function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ''; } function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } uint256 nextTokenId = tokenId + 1; function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } 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(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } catch (bytes memory reason) { 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(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { 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(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { ) internal virtual {} ) internal virtual {} }
13,721,748
[ 1, 10636, 30, 1680, 481, 89, 511, 5113, 326, 6912, 471, 6057, 25121, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 374, 261, 73, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 9637, 486, 2865, 18305, 310, 2430, 358, 1758, 12, 20, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 326, 576, 10392, 300, 404, 261, 1896, 460, 434, 2254, 10392, 13, 434, 14467, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1958, 3155, 5460, 12565, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 1105, 787, 4921, 31, 203, 565, 289, 203, 203, 565, 1958, 5267, 751, 288, 203, 3639, 2254, 10392, 11013, 31, 203, 3639, 2254, 10392, 1300, 49, 474, 329, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 2713, 17032, 273, 374, 31, 203, 203, 203, 203, 203, 203, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 5460, 12565, 13, 2713, 389, 995, 12565, 87, 31, 203, 565, 2874, 12, 2867, 516, 5267, 751, 13, 3238, 389, 2867, 751, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 17032, 31, 203, 565, 289, 203, 203, 565, 2 ]
./full_match/5/0xcB8AD068b5c8399DF5933D15B5e4E8AFa08d4Ad1/sources/contracts/VideoNFT.sol
Calculate profit percentage and amount Update past owners and transaction prices Update the video price Add user notifications for the old owner and new owner
function bid(uint256 tokenId) public payable { require( msg.value >= videos[tokenId].price, "Bid must be equal or higher than the current price" ); require( videos[tokenId].biddingEndTime > block.timestamp, "Bidding has ended" ); address oldOwner = ownerOf(tokenId); uint256 oldPrice = videos[tokenId].price; _transfer(oldOwner, msg.sender, tokenId); uint256 profit = msg.value - oldPrice; uint256 profitPercentage = (profit * 100) / oldPrice; profitPercentages[oldOwner] += profitPercentage; profitAmounts[oldOwner] += profit; pastOwners[tokenId].push(msg.sender); pastTransactionPrices[tokenId].push(msg.value); videos[tokenId].price = msg.value; notifications[oldOwner].push( string( abi.encodePacked( "You sold video ", uint2str(tokenId), " for ", uint2str(msg.value), " ETH" ) ) ); notifications[msg.sender].push( string( abi.encodePacked( "You bought video ", uint2str(tokenId), " for ", uint2str(msg.value), " ETH" ) ) ); emit OwnershipTransferred(tokenId, oldOwner, msg.sender, msg.value); }
1,938,951
[ 1, 8695, 450, 7216, 11622, 471, 3844, 2315, 8854, 25937, 471, 2492, 19827, 2315, 326, 6191, 6205, 1436, 729, 9208, 364, 326, 1592, 3410, 471, 394, 3410, 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, 9949, 12, 11890, 5034, 1147, 548, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 1545, 24752, 63, 2316, 548, 8009, 8694, 16, 203, 5411, 315, 17763, 1297, 506, 3959, 578, 10478, 2353, 326, 783, 6205, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 24752, 63, 2316, 548, 8009, 70, 1873, 310, 25255, 405, 1203, 18, 5508, 16, 203, 5411, 315, 38, 1873, 310, 711, 16926, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 1592, 5541, 273, 3410, 951, 12, 2316, 548, 1769, 203, 3639, 2254, 5034, 1592, 5147, 273, 24752, 63, 2316, 548, 8009, 8694, 31, 203, 203, 3639, 389, 13866, 12, 1673, 5541, 16, 1234, 18, 15330, 16, 1147, 548, 1769, 203, 203, 3639, 2254, 5034, 450, 7216, 273, 1234, 18, 1132, 300, 1592, 5147, 31, 203, 3639, 2254, 5034, 450, 7216, 16397, 273, 261, 685, 7216, 380, 2130, 13, 342, 1592, 5147, 31, 203, 3639, 450, 7216, 8410, 1023, 63, 1673, 5541, 65, 1011, 450, 7216, 16397, 31, 203, 3639, 450, 7216, 6275, 87, 63, 1673, 5541, 65, 1011, 450, 7216, 31, 203, 203, 3639, 8854, 5460, 414, 63, 2316, 548, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 8854, 3342, 31862, 63, 2316, 548, 8009, 6206, 12, 3576, 18, 1132, 1769, 203, 203, 3639, 24752, 63, 2316, 548, 8009, 8694, 273, 1234, 18, 1132, 31, 203, 203, 3639, 9208, 63, 1673, 5541, 8009, 6206, 12, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 315, 2 ]
// This contract is not supposed to be used in production // It's strictly for testing purpose pragma solidity ^0.8.4; import {ERC1155Supply, ERC1155, IERC165, Context} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {AccessControlMixin, AccessControl, Context} from "../../common/AccessControlMixin.sol"; import {NativeMetaTransaction} from "../../common/NativeMetaTransaction.sol"; import {IMintableERC1155, IERC1155} from "./IMintableERC1155.sol"; import {ContextMixin} from "../../common/ContextMixin.sol"; contract RootFactionArt is ERC1155Supply, Pausable, Ownable, AccessControlMixin, NativeMetaTransaction, ContextMixin, IMintableERC1155 { bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE"); // Contract name string public name; // Contract symbol string public symbol; // Initial Contract URI string private CONTRACT_URI; // Max Token ID uint256 public constant MAX_TOKEN_ID = 12; constructor ( string memory name_, string memory symbol_, string memory uri_, address mintableERC1155PredicateProxy ) ERC1155(uri_) { _setupContractId("RootFactionArt"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PREDICATE_ROLE, mintableERC1155PredicateProxy); _initializeEIP712(uri_); name = name_; symbol = symbol_; CONTRACT_URI = "https://api.cypherverse.io/os/collections/factionart"; } function mint( address account, uint256 id, uint256 amount, bytes calldata data ) external override only(PREDICATE_ROLE) { // Restrict minting of tokens to only the Predicate role require(((id <= MAX_TOKEN_ID) && (id > uint(0))), "RootFactionArt: INVALID_TOKEN_ID"); require(((amount > uint(0)) && (amount == restTotalSupply(id, amount))) , "RootFactionArt: INVALID_TOKEN_AMOUNT"); _mint(account, id, amount, data); } function mintBatch( address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external override only(PREDICATE_ROLE) { // Restrict minting of tokens to only the Predicate role for (uint i = 0; i < ids.length; i++) { require(((ids[i] <= MAX_TOKEN_ID) && (ids[i] > uint(0))), "RootFactionArt: INVALID_TOKEN_ID"); require(((amounts[i] > uint(0)) && (amounts[i] == restTotalSupply(ids[i], amounts[i]))), "RootFactionArt: INVALID_TOKEN_AMOUNT"); } _mintBatch(to, ids, amounts, data); } function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "RootFactionArt: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "RootFactionArt: caller is not owner nor approved" ); _burnBatch(account, ids, values); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override (Context) view returns (address sender) { return ContextMixin.msgSender(); } function _msgData() internal override (Context) pure returns (bytes calldata) { return msg.data; } /** * Override isApprovedForAll to auto-approve OS's proxy contract */ function isApprovedForAll( address _owner, address _operator ) public override(ERC1155, IERC1155) view returns (bool isOperator) { // if OpenSea's ERC1155 Proxy Address is detected, auto-return true if (_operator == address(0x207Fa8Df3a17D96Ca7EA4f2893fcdCb78a304101)) { return true; } // otherwise, use the default ERC1155.isApprovedForAll() return ERC1155.isApprovedForAll(_owner, _operator); } /** * @notice Make the SetTokenURI method visible for future upgrade of metadata * @dev Sets `_tokenURI` as the tokenURI for the `all` tokenId. */ function setURI(string memory _tokenURI) public virtual onlyOwner() { _setURI(_tokenURI); } /** * @notice Method for reduce the friction with openSea allows to map the `tokenId` * @dev into our NFT Smart contract and handle some metadata offchain in OpenSea */ function contractURI() public view returns (string memory) { return CONTRACT_URI; } /** * @notice Method for reduce the friction with openSea allows update the Contract URI * @dev This method is only available for the owner of the contract * @param _contractURI The new contract URI */ function setContractURI(string memory _contractURI) public onlyOwner() { CONTRACT_URI = _contractURI; } /** * @notice Method for getting Max Supply for Token * @dev This method is for getting the Max Supply by token id * @param _id The token id */ function maxSupply(uint256 _id) public pure returns (uint256 _maxSupply) { _maxSupply = 0; if ((_id == 1) || (_id == 5) || (_id == 9)) { _maxSupply = uint256(645); } else if ((_id == 2) || (_id == 6) || (_id == 10)) { _maxSupply = uint256(1263); } else if ((_id == 3) || (_id == 7) || (_id == 11)) { _maxSupply = uint256(1267); } else if ((_id == 4) || (_id == 8) || (_id == 12)) { _maxSupply = uint256(3141); } } /** * @notice Method for getting OpenSea Version we Operate * @dev This method is for getting the Max Supply by token id */ function openSeaVersion() public pure returns (string memory) { return "2.1.0"; } /** * Compat for factory interfaces on OpenSea * Indicates that this contract can return balances for * tokens that haven't been minted yet */ function supportsFactoryInterface() public pure returns (bool) { return true; } /** * @dev Implementation / Instance of paused methods() in the ERC1155. * @param status Setting the status boolean (True for paused, or False for unpaused) * See {ERC1155Pausable}. */ function pause(bool status) public onlyOwner() { if (status) { _pause(); } else { _unpause(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Method, for verify the TotalSupply of the NFT, each time to mint a new NFT Token * @param _id The id of the NFT Token * @param _amount The amount of the NFT Token * @return The amount of the NFT Token to mint */ function restTotalSupply(uint256 _id, uint256 _amount) private view returns (uint256) { uint256 subtotal = totalSupply(_id)+_amount; require(( subtotal <= maxSupply(_id) ), "RootFactionArt: EXCEED MAX_AMOUNT"); return _amount; } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "RootFactionArt: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.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 Pausable is Context { /** * @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. */ constructor() { _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()); } } // 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); } } pragma solidity ^0.8.0; import {AccessControl, Context} from "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } 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 ); } } import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; pragma solidity ^0.8.0; interface IMintableERC1155 is IERC1155 { /** * @notice Creates `amount` tokens of token type `id`, and assigns them to `account`. * @dev Should be callable only by MintableERC1155Predicate * Make sure minting is done only by this function * @param account user address for whom token is being minted * @param id token which is being minted * @param amount amount of token being minted * @param data extra byte data to be accompanied with minted tokens */ function mint(address account, uint256 id, uint256 amount, bytes calldata data) external; /** * @notice Batched version of singular token minting, where * for each token in `ids` respective amount to be minted from `amounts` * array, for address `to`. * @dev Should be callable only by MintableERC1155Predicate * Make sure minting is done only by this function * @param to user address for whom token is being minted * @param ids tokens which are being minted * @param amounts amount of each token being minted * @param data extra byte data to be accompanied with minted tokens */ function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view virtual returns (address 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 = msg.sender; } return sender; } } // 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/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); } // 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 "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 { 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(IAccessControl).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 ", 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, 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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @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 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; // 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; } } } 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 contractsa 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) ); } } pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
* @dev Implementation / Instance of paused methods() in the ERC1155. @param status Setting the status boolean (True for paused, or False for unpaused) See {ERC1155Pausable}./
function pause(bool status) public onlyOwner() { if (status) { _pause(); _unpause(); } }
1,141,043
[ 1, 13621, 342, 5180, 434, 17781, 2590, 1435, 316, 326, 4232, 39, 2499, 2539, 18, 225, 1267, 13274, 326, 1267, 1250, 261, 5510, 364, 17781, 16, 578, 1083, 364, 640, 8774, 3668, 13, 2164, 288, 654, 39, 2499, 2539, 16507, 16665, 5496, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 11722, 12, 6430, 1267, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 309, 261, 2327, 13, 288, 203, 5411, 389, 19476, 5621, 203, 5411, 389, 318, 19476, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // solhint-disable not-rely-on-time contract YayVesting { using SafeMath for uint256; using SafeERC20 for IERC20; // category enum CategoryNames {EMPTY, SEED, STRATEGIC, PRESALE, PUBLIC, V24MONTH, V20MONTH, V4MONTH} struct CategoryType { uint256 totalSteps; uint256 stepTime; // unix format uint256 percentBefore; // decimals = 2 uint256 percentAfter; // decimals = 2 } mapping(CategoryNames => CategoryType) public categories; // investor struct InvestorTokens { address investor; CategoryNames category; uint256 tokenAmount; } mapping(address => uint256) public alreadyRewarded; // contract settings address public immutable token; bytes32 public immutable mercleRoot; uint256 public immutable tgeTimestamp; // claim state mapping(address => bool) public tgeIsClaimed; mapping(address => uint256) public lastClaimedStep; event Claim( address indexed target, uint256 indexed category, uint256 amount, bytes32[] merkleProof, uint256 resultReward, uint256 timestamp ); event TgeClaim(address indexed target, uint256 value, uint256 timestamp); event StepClaim(address indexed target, uint256 indexed step, uint256 value, uint256 timestamp); constructor(address _token, bytes32 _mercleRoot, uint256 _tgeTimestamp) public { require(_token != address(0), "YayVesting: zero token address"); require(_mercleRoot != bytes32(0), "YayVesting: zero mercle root"); token = _token; mercleRoot = _mercleRoot; tgeTimestamp = _tgeTimestamp; // rounds settings categories[CategoryNames.SEED] = CategoryType({ totalSteps: 15, stepTime: 30 days, percentBefore: 0, percentAfter: 6_00 }); categories[CategoryNames.STRATEGIC] = CategoryType({ totalSteps: 12, stepTime: 30 days, percentBefore: 0, percentAfter: 7_50 }); categories[CategoryNames.PRESALE] = CategoryType({ totalSteps: 5, stepTime: 30 days, percentBefore: 0, percentAfter: 14_00 }); categories[CategoryNames.PUBLIC] = CategoryType({ totalSteps: 8, stepTime: 7 days, percentBefore: 0, percentAfter: 8_75 }); categories[CategoryNames.V24MONTH] = CategoryType({ totalSteps: 23, stepTime: 30 days, percentBefore: 0, percentAfter: 4_17 }); categories[CategoryNames.V20MONTH] = CategoryType({ totalSteps: 20, stepTime: 30 days, percentBefore: 0, percentAfter: 5_00 }); categories[CategoryNames.V4MONTH] = CategoryType({ totalSteps: 3, stepTime: 30 days, percentBefore: 0, percentAfter: 25_00 }); } function checkClaim(address _target, uint256 _category, uint256 _amount, bytes32[] calldata _merkleProof) external view returns(bool) { return (_verify(_target, _category, _amount, _merkleProof)); } function claim(uint256 _category, uint256 _amount, bytes32[] calldata _merkleProof) external returns(uint256 _claimResult) { require(_verify(msg.sender, _category, _amount, _merkleProof), "YayVesting: Invalid proof or wrong data"); require(CategoryNames(_category) != CategoryNames.EMPTY, "YayVesting: Invalid category"); require(_amount > 0, "YayVesting: Invalid amount"); require(block.timestamp >= tgeTimestamp, "YayVesting: TGE has not started yet"); CategoryType memory category = categories[CategoryNames(_category)]; uint256 reward = 0; // claim TGE reward if (tgeIsClaimed[msg.sender] == false) { reward = reward.add(_amount.mul(category.percentBefore).div(100_00)); tgeIsClaimed[msg.sender] = true; emit TgeClaim(msg.sender, reward, block.timestamp); } // claim reward after TGE for (uint256 i = lastClaimedStep[msg.sender] + 1; i <= category.totalSteps; i++) { if (tgeTimestamp.add(category.stepTime.mul(i)) <= block.timestamp) { lastClaimedStep[msg.sender] = i; uint256 addedAmount = _amount.mul(category.percentAfter).div(100_00); reward = reward.add(addedAmount); emit StepClaim(msg.sender, i, addedAmount, block.timestamp); } else { break; } } require(reward > 0, "YayVesting: no tokens to claim"); uint256 rewarded = alreadyRewarded[msg.sender]; uint256 resultReward = 0; // if reward overlimit (security check) if (rewarded.add(reward) > _amount) { resultReward = _amount.sub(rewarded, "YayVesting: no tokens to claim (security check)"); } else { resultReward = reward; } alreadyRewarded[msg.sender] = alreadyRewarded[msg.sender].add(resultReward); IERC20(token).safeTransfer(msg.sender, resultReward); emit Claim(msg.sender, _category, _amount, _merkleProof, resultReward, block.timestamp); return(resultReward); } function _verify(address _target, uint256 _category, uint256 _amount, bytes32[] memory _merkleProof) internal view returns(bool) { bytes32 node = keccak256(abi.encodePacked(_target, _category, _amount)); return(MerkleProof.verify(_merkleProof, mercleRoot, node)); } }
claim TGE reward claim reward after TGE if reward overlimit (security check)
function claim(uint256 _category, uint256 _amount, bytes32[] calldata _merkleProof) external returns(uint256 _claimResult) { require(_verify(msg.sender, _category, _amount, _merkleProof), "YayVesting: Invalid proof or wrong data"); require(CategoryNames(_category) != CategoryNames.EMPTY, "YayVesting: Invalid category"); require(_amount > 0, "YayVesting: Invalid amount"); require(block.timestamp >= tgeTimestamp, "YayVesting: TGE has not started yet"); CategoryType memory category = categories[CategoryNames(_category)]; uint256 reward = 0; if (tgeIsClaimed[msg.sender] == false) { reward = reward.add(_amount.mul(category.percentBefore).div(100_00)); tgeIsClaimed[msg.sender] = true; emit TgeClaim(msg.sender, reward, block.timestamp); } for (uint256 i = lastClaimedStep[msg.sender] + 1; i <= category.totalSteps; i++) { if (tgeTimestamp.add(category.stepTime.mul(i)) <= block.timestamp) { lastClaimedStep[msg.sender] = i; uint256 addedAmount = _amount.mul(category.percentAfter).div(100_00); reward = reward.add(addedAmount); emit StepClaim(msg.sender, i, addedAmount, block.timestamp); break; } } require(reward > 0, "YayVesting: no tokens to claim"); uint256 rewarded = alreadyRewarded[msg.sender]; uint256 resultReward = 0; if (rewarded.add(reward) > _amount) { resultReward = _amount.sub(rewarded, "YayVesting: no tokens to claim (security check)"); resultReward = reward; } alreadyRewarded[msg.sender] = alreadyRewarded[msg.sender].add(resultReward); IERC20(token).safeTransfer(msg.sender, resultReward); emit Claim(msg.sender, _category, _amount, _merkleProof, resultReward, block.timestamp); return(resultReward); }
13,030,634
[ 1, 14784, 399, 7113, 19890, 7516, 19890, 1839, 399, 7113, 309, 19890, 1879, 3595, 261, 7462, 866, 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 ]
[ 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, 7516, 12, 11890, 5034, 389, 4743, 16, 2254, 5034, 389, 8949, 16, 1731, 1578, 8526, 745, 892, 389, 6592, 15609, 20439, 13, 3903, 1135, 12, 11890, 5034, 389, 14784, 1253, 13, 288, 203, 3639, 2583, 24899, 8705, 12, 3576, 18, 15330, 16, 389, 4743, 16, 389, 8949, 16, 389, 6592, 15609, 20439, 3631, 315, 61, 528, 58, 10100, 30, 1962, 14601, 578, 7194, 501, 8863, 203, 3639, 2583, 12, 4457, 1557, 24899, 4743, 13, 480, 9856, 1557, 18, 13625, 16, 315, 61, 528, 58, 10100, 30, 1962, 3150, 8863, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 61, 528, 58, 10100, 30, 1962, 3844, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 268, 908, 4921, 16, 315, 61, 528, 58, 10100, 30, 399, 7113, 711, 486, 5746, 4671, 8863, 203, 203, 3639, 9856, 559, 3778, 3150, 273, 6477, 63, 4457, 1557, 24899, 4743, 13, 15533, 203, 203, 3639, 2254, 5034, 19890, 273, 374, 31, 203, 203, 3639, 309, 261, 88, 908, 2520, 9762, 329, 63, 3576, 18, 15330, 65, 422, 629, 13, 288, 203, 5411, 19890, 273, 19890, 18, 1289, 24899, 8949, 18, 16411, 12, 4743, 18, 8849, 4649, 2934, 2892, 12, 6625, 67, 713, 10019, 203, 5411, 268, 908, 2520, 9762, 329, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 203, 5411, 3626, 399, 908, 9762, 12, 3576, 18, 15330, 16, 19890, 16, 1203, 18, 5508, 1769, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 1142, 9762, 329, 4160, 63, 3576, 18, 15330, 65, 2 ]
./full_match/1/0x73Cf263aD4e998c610Bc49526A40E413b08A7567/sources/contracts/Shackers.sol
* @notice Mints a single Shacker for a given token id./
function mint(address to, uint256 tokenId, string memory tokenUri) public onlyRole(MINTER_ROLE) { _safeMint(to, tokenId); if (bytes(tokenUri).length > 0) { _setExplicitTokenURI(tokenId, tokenUri); } emit ShackerMinted(to, tokenId); }
8,433,532
[ 1, 49, 28142, 279, 2202, 2638, 484, 264, 364, 279, 864, 1147, 612, 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 ]
[ 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, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 16, 533, 3778, 1147, 3006, 13, 1071, 1338, 2996, 12, 6236, 2560, 67, 16256, 13, 288, 203, 565, 389, 4626, 49, 474, 12, 869, 16, 1147, 548, 1769, 203, 565, 309, 261, 3890, 12, 2316, 3006, 2934, 2469, 405, 374, 13, 288, 203, 1377, 389, 542, 17186, 1345, 3098, 12, 2316, 548, 16, 1147, 3006, 1769, 203, 565, 289, 203, 565, 3626, 2638, 484, 264, 49, 474, 329, 12, 869, 16, 1147, 548, 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 ]
// 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 min amount allowed to stake per validator.
uint256 public minAmountStake;
6,084,852
[ 1, 1154, 3844, 2935, 358, 384, 911, 1534, 4213, 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, 2254, 5034, 1071, 1131, 6275, 510, 911, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./NFTYToken.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract NFTYStakingUpgradeable is AccessControlUpgradeable, ReentrancyGuardUpgradeable { // state variables NFTYToken nftyToken; address private _NFTYTokenAddress; uint256 private _totalStakedToken; uint256[6] private _rewardRate; // creating a new role for admin bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); // event for informing a new stake event NewStake(address indexed staker, uint256 amount); // event for informing the release of reward event RewardReleased(address indexed staker, uint256 reward); //event for informing the addition of amount to the existing stake event StakeUpgraded( address indexed staker, uint256 amount, uint256 totalStake ); // event for informing when someone unstakes event StakeReleased( address indexed staker, uint256 amount, uint256 remainingStake ); // event for informing the change of reward rate event RateChanged( address indexed admin, uint8 rank, uint256 oldRate, uint256 newRate ); // event for informing the transfer of all tokens // to the nfty owner event TransferredAllTokens(address caller, uint256 amount); // modifier for checking the zero address modifier isRealAddress(address account) { require(account != address(0), "NFTYStaking: address is zero address"); _; } // modifier for checking the real amount modifier isRealValue(uint256 value) { require(value > 0, "NFTYStaking: value must be greater than zero"); _; } // modifier for checking if the sendeer is a staker modifier isStaker(address account) { require( StakersData[account].amount > 0, "NFTYStaking: caller is not a staker" ); _; } // structure for storing the staker data struct StakeData { uint256 amount; uint256 reward; uint256 stakingTime; uint256 lastClaimTime; } // mapping for pointing to the stakers data mapping(address => StakeData) public StakersData; function initialize(address NFTYTokenAddress) public isRealAddress(NFTYTokenAddress) isRealAddress(_msgSender()) initializer { __ReentrancyGuard_init(); __AccessControl_init(); _setupRole(ADMIN_ROLE, _msgSender()); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _NFTYTokenAddress = NFTYTokenAddress; nftyToken = NFTYToken(NFTYTokenAddress); _rewardRate = [13579, 14579, 15079, 15579, 15829, 16079]; // 13.579%, 14.579%, 15.079%, 15.579%, 16.079% } function transferOwnership(address _newOwner) external onlyRole(ADMIN_ROLE) { nftyToken.transferOwnership(_newOwner); } // function for staking the token function stakeTokens(uint256 amount) external isRealAddress(_msgSender()) isRealValue(amount) returns (bool) { require(amount >= _getAmount(1), "NFTYStaking: min stake amount is 1"); require( nftyToken.balanceOf(_msgSender()) >= amount, "NFTYStaking: insufficient balance" ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; // if already staking then add the amount to the existing stake if (_amount > 0) { // calculate the reward for the existing amount uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); // update staker's data stakeData.reward += reward; stakeData.amount = _amount + amount; // emit the event for informing the upgraded stake emit StakeUpgraded(_msgSender(), amount, stakeData.amount); } else { // update staker's data stakeData.amount = amount; stakeData.stakingTime = block.timestamp; // emit the event for informing the new stake emit NewStake(_msgSender(), amount); } stakeData.lastClaimTime = block.timestamp; // update the pool _totalStakedToken += amount; // transfer the amount to the staking contract bool result = nftyToken.transferFrom( _msgSender(), address(this), amount ); return result; } // function for claiming reward function claimRewards() external isRealAddress(_msgSender()) isStaker(_msgSender()) { require( nftyToken.owner() == address(this), "Staking contract is not the owner." ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); reward = stakeData.reward + reward; // update the staker data stakeData.reward = 0; stakeData.lastClaimTime = block.timestamp; // emit the event for informing the release of reward emit RewardReleased(_msgSender(), reward); // mint the reward back to the stakers account nftyToken.mint(_msgSender(), reward); } // function for showing the reward at any time function showReward(address account) external view isRealAddress(_msgSender()) isRealAddress(account) isStaker(account) returns (uint256) { StakeData storage stakeData = StakersData[account]; uint256 _amount = stakeData.amount; uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); reward = stakeData.reward + reward; return reward; } // function for unstaking all the tokens function unstakeAll() external { StakeData storage stakeData = StakersData[_msgSender()]; uint256 amount = stakeData.amount; unstakeTokens(amount); } // function for changing the reward rate function changeRate(uint8 rank, uint256 rate) external onlyRole(ADMIN_ROLE) { require(rate > 0 && rate <= 100000, "NFTYStaking: invalid rate"); require(rank < 6, "NFTYStaking: invalid rank"); uint256 oldRate = _rewardRate[rank]; _rewardRate[rank] = rate; // emit the event for informing the change of rate emit RateChanged(_msgSender(), rank, oldRate, rate); } // function for returning the current reward rate function getRewardRates() external view returns (uint256[6] memory) { return _rewardRate; } // function for returning total stake token (pool) function getPool() external view returns (uint256) { return _totalStakedToken; } function getRewardRate(uint256 amount, uint256 stakingTime) public view returns (uint256 rewardRate) { uint256 rewardRate1; uint256 rewardRate2; stakingTime = block.timestamp - stakingTime; // reward rate based on the staking amount if (amount >= _getAmount(1) && amount < _getAmount(500)) { rewardRate1 = _rewardRate[0]; } else if (amount >= _getAmount(500) && amount < _getAmount(10000)) { rewardRate1 = _rewardRate[1]; } else if (amount >= _getAmount(10000) && amount < _getAmount(25000)) { rewardRate1 = _rewardRate[2]; } else if (amount >= _getAmount(25000) && amount < _getAmount(50000)) { rewardRate1 = _rewardRate[3]; } else if (amount >= _getAmount(50000) && amount < _getAmount(100000)) { rewardRate1 = _rewardRate[4]; } else { rewardRate1 = _rewardRate[5]; } // reward rate based on staking time if (stakingTime < 30 days) { rewardRate2 = _rewardRate[0]; } else if (stakingTime >= 30 days && stakingTime < 45 days) { rewardRate2 = _rewardRate[1]; } else if (stakingTime >= 45 days && stakingTime < 90 days) { rewardRate2 = _rewardRate[2]; } else if (stakingTime >= 90 days && stakingTime < 180 days) { rewardRate2 = _rewardRate[3]; } else if (stakingTime >= 180 days && stakingTime < 365 days) { rewardRate2 = _rewardRate[4]; } else { rewardRate2 = _rewardRate[5]; } // find exact reward rate rewardRate = rewardRate1 < rewardRate2 ? rewardRate1 : rewardRate2; } // function for unstaking the specified amount function unstakeTokens(uint256 amount) public isRealAddress(_msgSender()) isRealValue(amount) isStaker(_msgSender()) { require( nftyToken.owner() == address(this), "Staking contract is not the owner." ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; // check if the user has enough amount to unstake require(_amount >= amount, "NFTYStaking: not enough staked token"); uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); // if the staker is unstaking the whole amount if (stakeData.amount == amount) { uint256 totReward = reward + stakeData.reward; // update the staker data stakeData.reward = 0; stakeData.stakingTime = 0; // emit the event for informing the release of reward emit RewardReleased(_msgSender(), totReward); // mint reward to the user nftyToken.mint(_msgSender(), totReward); } else { // update the staker data stakeData.reward += reward; } stakeData.amount -= amount; stakeData.lastClaimTime = block.timestamp; _totalStakedToken -= amount; // emit the event for informing the unstake of tokens emit StakeReleased(_msgSender(), amount, stakeData.amount); nftyToken.transfer(_msgSender(), amount); } // function for finding the reward based on compound equation function _getReward( uint256 stakingTime, uint256 lastClaimTime, uint256 amount ) internal view returns (uint256 reward) { uint256 rewardRate = getRewardRate(amount, stakingTime); uint256 rewardTime = block.timestamp - lastClaimTime; uint256 rateForSecond = (rewardRate * 10**18) / 365 days; reward = (amount * rateForSecond * rewardTime) / 10**23; return reward; } // function for retrieving the exact amount function _getAmount(uint256 value) internal view returns (uint256) { return value * 10**uint256(nftyToken.decimals()); } } // SPDX-License-Identifier: MIT 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 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; } // SPDX-License-Identifier: MIT 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 initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, 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: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract NFTYToken is ERC20Upgradeable, OwnableUpgradeable { function initialize() public initializer { __ERC20_init("NFTY Token", "NFTY"); __Ownable_init(); _mint(owner(), 50000 * 10**uint256(decimals())); } function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 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 { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @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 Contracts guidelines: functions revert * instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 this function is * overridden; * * 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 override returns (uint8) { return 18; } /** * @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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } 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] + 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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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. */ 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 || !_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.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 initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @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 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 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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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 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 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-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT 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); }
find exact reward rate
rewardRate = rewardRate1 < rewardRate2 ? rewardRate1 : rewardRate2;
6,961,221
[ 1, 4720, 5565, 19890, 4993, 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, 3639, 19890, 4727, 273, 19890, 4727, 21, 411, 19890, 4727, 22, 692, 19890, 4727, 21, 294, 19890, 4727, 22, 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 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; 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 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) { assert(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; assert(c >= a); return c; } } /** * @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 OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20StandardToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint _value); mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint256) public balanceOf; using SafeMath for uint256; uint256 totalSupply_; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from,address _to,uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balanceOf[_from]); require(_value <= allowed[_from][msg.sender]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for 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(_to != address(0)); require(_value <= balanceOf[msg.sender]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ 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; } } /** * @title Contract that will work with ERC223 tokens. */ contract addtionalERC223Interface { function transfer(address to, uint256 value, bytes data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint256 _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); } } /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223Token is addtionalERC223Interface , ERC20StandardToken { function _transfer(address _to, uint256 _value ) private returns (bool) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); return true; } function _transferFallback(address _to, uint256 _value, bytes _data) private returns (bool) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool OK) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . if(isContract(_to)) { return _transferFallback(_to,_value,_data); }else{ _transfer(_to,_value); emit Transfer(msg.sender, _to, _value, _data); } return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; if(isContract(_to)) { return _transferFallback(_to,_value,empty); }else{ _transfer(_to,_value); emit Transfer(msg.sender, _to, _value); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } } contract NANASHITOKEN is ERC223Token , Ownable { event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); string public name = "NANASHITOKEN"; string public symbol = "NNSH"; uint8 public decimals = 18; constructor() public{ address founder = 0x34c6D2bd70862D33c2d6710cF683e9b0860017a3; address developer = 0x0ede4523d0aD50FF840Be95Dd680704f761C1E06; owner = founder; uint256 dec = decimals; totalSupply_ = 500 * 1e8 * (10**dec); balanceOf[founder] = totalSupply_.mul(97).div(100); balanceOf[developer] = totalSupply_.mul(3).div(100); } function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply_ = totalSupply_.sub(_unitAmount); emit Burn(_from, _unitAmount); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner public returns (bool) { require(_unitAmount > 0); totalSupply_ = totalSupply_.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } }
* @title Reference implementation of the ERC223 standard token./
contract ERC223Token is addtionalERC223Interface , ERC20StandardToken { function _transfer(address _to, uint256 _value ) private returns (bool) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); return true; } function _transferFallback(address _to, uint256 _value, bytes _data) private returns (bool) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool OK) { if(isContract(_to)) { return _transferFallback(_to,_value,_data); _transfer(_to,_value); emit Transfer(msg.sender, _to, _value, _data); } return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool OK) { if(isContract(_to)) { return _transferFallback(_to,_value,_data); _transfer(_to,_value); emit Transfer(msg.sender, _to, _value, _data); } return true; } }else{ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; if(isContract(_to)) { return _transferFallback(_to,_value,empty); _transfer(_to,_value); emit Transfer(msg.sender, _to, _value); } } function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; if(isContract(_to)) { return _transferFallback(_to,_value,empty); _transfer(_to,_value); emit Transfer(msg.sender, _to, _value); } } }else{ function isContract(address _addr) private view returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function isContract(address _addr) private view returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } }
915,559
[ 1, 2404, 4471, 434, 326, 4232, 39, 3787, 23, 4529, 1147, 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 ]
[ 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, 0 ]
[ 1, 16351, 4232, 39, 3787, 23, 1345, 353, 527, 24252, 287, 654, 39, 3787, 23, 1358, 269, 4232, 39, 3462, 8336, 1345, 288, 203, 7010, 565, 445, 389, 13866, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 262, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 540, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 11013, 951, 63, 67, 869, 65, 273, 11013, 951, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 540, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12355, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 16, 1731, 389, 892, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 11013, 951, 63, 67, 869, 65, 273, 11013, 951, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 203, 3639, 4232, 39, 3787, 23, 4779, 9288, 8924, 5971, 273, 4232, 39, 3787, 23, 4779, 9288, 8924, 24899, 869, 1769, 203, 3639, 5971, 18, 2316, 12355, 12, 3576, 18, 15330, 16, 389, 1132, 16, 389, 892, 1769, 203, 540, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 16, 389, 892, 1769, 203, 2 ]
pragma solidity 0.4.25; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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) ); } } contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @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 { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract DecoBaseProjectsMarketplace is Ownable { using SafeMath for uint256; // `DecoRelay` contract address. address public relayContractAddress; /** * @dev Payble fallback for reverting transactions of any incoming ETH. */ function () public payable { require(msg.value == 0, "Blocking any incoming ETH."); } /** * @dev Set the new address of the `DecoRelay` contract. * @param _newAddress An address of the new contract. */ function setRelayContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Relay address must not be 0x0."); relayContractAddress = _newAddress; } /** * @dev Allows to trasnfer any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { IERC20 token = IERC20(_tokenAddress); return token.transfer(owner(), _tokens); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); 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); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /// @title Contract to store other contracts newest versions addresses and service information. contract DecoRelay is DecoBaseProjectsMarketplace { address public projectsContractAddress; address public milestonesContractAddress; address public escrowFactoryContractAddress; address public arbitrationContractAddress; address public feesWithdrawalAddress; uint8 public shareFee; function setProjectsContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); projectsContractAddress = _newAddress; } function setMilestonesContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); milestonesContractAddress = _newAddress; } function setEscrowFactoryContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); escrowFactoryContractAddress = _newAddress; } function setArbitrationContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); arbitrationContractAddress = _newAddress; } function setFeesWithdrawalAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); feesWithdrawalAddress = _newAddress; } function setShareFee(uint8 _shareFee) external onlyOwner { require(_shareFee <= 100, "Deconet share fee must be less than 100%."); shareFee = _shareFee; } } /** * @title Escrow contract, every project deploys a clone and transfer ownership to the project client, so all * funds not reserved to pay for a milestone can be safely moved in/out. */ contract DecoEscrow is DecoBaseProjectsMarketplace { using SafeMath for uint256; // Indicates if the current clone has been initialized. bool internal isInitialized; // Stores share fee that should apply on any successful distribution. uint8 public shareFee; // Authorized party for executing funds distribution operations. address public authorizedAddress; // State variable to track available ETH Escrow owner balance. // Anything that is not blocked or distributed in favor of any party can be withdrawn by the owner. uint public balance; // Mapping of available for withdrawal funds by the address. // Accounted amounts are excluded from the `balance`. mapping (address => uint) public withdrawalAllowanceForAddress; // Maps information about the amount of deposited ERC20 token to the token address. mapping(address => uint) public tokensBalance; /** * Mapping of ERC20 tokens amounts to token addresses that are available for withdrawal for a given address. * Accounted here amounts are excluded from the `tokensBalance`. */ mapping(address => mapping(address => uint)) public tokensWithdrawalAllowanceForAddress; // ETH amount blocked in Escrow. // `balance` excludes this amount. uint public blockedBalance; // Mapping of the amount of ERC20 tokens to the the token address that are blocked in Escrow. // A token value in `tokensBalance` excludes stored here amount. mapping(address => uint) public blockedTokensBalance; // Logged when an operation with funds occurred. event FundsOperation ( address indexed sender, address indexed target, address tokenAddress, uint amount, PaymentType paymentType, OperationType indexed operationType ); // Logged when the given address authorization to distribute Escrow funds changed. event FundsDistributionAuthorization ( address targetAddress, bool isAuthorized ); // Accepted types of payments. enum PaymentType { Ether, Erc20 } // Possible operations with funds. enum OperationType { Receive, Send, Block, Unblock, Distribute } // Restrict function call to be originated from an address that was authorized to distribute funds. modifier onlyAuthorized() { require(authorizedAddress == msg.sender, "Only authorized addresses allowed."); _; } /** * @dev Default `payable` fallback to accept incoming ETH from any address. */ function () public payable { deposit(); } /** * @dev Initialize the Escrow clone with default values. * @param _newOwner An address of a new escrow owner. * @param _authorizedAddress An address that will be stored as authorized. */ function initialize( address _newOwner, address _authorizedAddress, uint8 _shareFee, address _relayContractAddress ) external { require(!isInitialized, "Only uninitialized contracts allowed."); isInitialized = true; authorizedAddress = _authorizedAddress; emit FundsDistributionAuthorization(_authorizedAddress, true); _transferOwnership(_newOwner); shareFee = _shareFee; relayContractAddress = _relayContractAddress; } /** * @dev Start transfering the given amount of the ERC20 tokens available by provided address. * @param _tokenAddress ERC20 token contract address. * @param _amount Amount to transfer from sender`s address. */ function depositErc20(address _tokenAddress, uint _amount) external { require(_tokenAddress != address(0x0), "Token Address shouldn't be 0x0."); IERC20 token = IERC20(_tokenAddress); require( token.transferFrom(msg.sender, address(this), _amount), "Transfer operation should be successful." ); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Receive ); } /** * @dev Withdraw the given amount of ETH to sender`s address if allowance or contract balance is sufficient. * @param _amount Amount to withdraw. */ function withdraw(uint _amount) external { withdrawForAddress(msg.sender, _amount); } /** * @dev Withdraw the given amount of ERC20 token to sender`s address if allowance or contract balance is sufficient. * @param _tokenAddress ERC20 token address. * @param _amount Amount to withdraw. */ function withdrawErc20(address _tokenAddress, uint _amount) external { withdrawErc20ForAddress(msg.sender, _tokenAddress, _amount); } /** * @dev Block funds for future use by authorized party stored in `authorizedAddress`. * @param _amount An uint of Wei to be blocked. */ function blockFunds(uint _amount) external onlyAuthorized { require(_amount <= balance, "Amount to block should be less or equal than balance."); balance = balance.sub(_amount); blockedBalance = blockedBalance.add(_amount); emit FundsOperation ( address(this), msg.sender, address(0x0), _amount, PaymentType.Ether, OperationType.Block ); } /** * @dev Blocks ERC20 tokens funds for future use by authorized party listed in `authorizedAddress`. * @param _tokenAddress An address of ERC20 token. * @param _amount An uint of tokens to be blocked. */ function blockTokenFunds(address _tokenAddress, uint _amount) external onlyAuthorized { uint accountedTokensBalance = tokensBalance[_tokenAddress]; require( _amount <= accountedTokensBalance, "Tokens mount to block should be less or equal than balance." ); tokensBalance[_tokenAddress] = accountedTokensBalance.sub(_amount); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( address(this), msg.sender, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Block ); } /** * @dev Distribute funds between contract`s balance and allowance for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by an authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _amount Amount to distribute in favor of a destination address. */ function distributeFunds( address _destination, uint _amount ) external onlyAuthorized { require( _amount <= blockedBalance, "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedBalance = blockedBalance.sub(fee); withdrawalAllowanceForAddress[feeDestination] = withdrawalAllowanceForAddress[feeDestination].add(fee); emit FundsOperation( msg.sender, feeDestination, address(0x0), fee, PaymentType.Ether, OperationType.Distribute ); } if (_destination == owner()) { unblockFunds(amount); return; } blockedBalance = blockedBalance.sub(amount); withdrawalAllowanceForAddress[_destination] = withdrawalAllowanceForAddress[_destination].add(amount); emit FundsOperation( msg.sender, _destination, address(0x0), amount, PaymentType.Ether, OperationType.Distribute ); } /** * @dev Distribute ERC20 token funds between contract`s balance and allowanc for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _tokenAddress ERC20 Token address. * @param _amount Amount to distribute in favor of a destination address. */ function distributeTokenFunds( address _destination, address _tokenAddress, uint _amount ) external onlyAuthorized { require( _amount <= blockedTokensBalance[_tokenAddress], "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(fee); uint allowance = tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress] = allowance.add(fee); emit FundsOperation( msg.sender, feeDestination, _tokenAddress, fee, PaymentType.Erc20, OperationType.Distribute ); } if (_destination == owner()) { unblockTokenFunds(_tokenAddress, amount); return; } blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(amount); uint allowanceForSender = tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress] = allowanceForSender.add(amount); emit FundsOperation( msg.sender, _destination, _tokenAddress, amount, PaymentType.Erc20, OperationType.Distribute ); } /** * @dev Withdraws ETH amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer ETH to. * @param _amount An `uint` amount to be transfered. */ function withdrawForAddress(address _targetAddress, uint _amount) public { require( _amount <= address(this).balance, "Amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { balance = balance.sub(_amount); } else { uint withdrawalAllowance = withdrawalAllowanceForAddress[_targetAddress]; withdrawalAllowanceForAddress[_targetAddress] = withdrawalAllowance.sub(_amount); } _targetAddress.transfer(_amount); emit FundsOperation ( address(this), _targetAddress, address(0x0), _amount, PaymentType.Ether, OperationType.Send ); } /** * @dev Withdraws ERC20 token amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer tokens to. * @param _tokenAddress An `address` of ERC20 token. * @param _amount An `uint` amount of ERC20 tokens to be transfered. */ function withdrawErc20ForAddress(address _targetAddress, address _tokenAddress, uint _amount) public { IERC20 token = IERC20(_tokenAddress); require( _amount <= token.balanceOf(this), "Token amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].sub(_amount); } else { uint tokenWithdrawalAllowance = getTokenWithdrawalAllowance(_targetAddress, _tokenAddress); tokensWithdrawalAllowanceForAddress[_targetAddress][_tokenAddress] = tokenWithdrawalAllowance.sub( _amount ); } token.transfer(_targetAddress, _amount); emit FundsOperation ( address(this), _targetAddress, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Send ); } /** * @dev Returns allowance for withdrawing the given token for sender address. * @param _tokenAddress An address of ERC20 token. * @return An uint value of allowance. */ function getTokenWithdrawalAllowance(address _account, address _tokenAddress) public view returns(uint) { return tokensWithdrawalAllowanceForAddress[_account][_tokenAddress]; } /** * @dev Accept and account incoming deposit in contract state. */ function deposit() public payable { require(msg.value > 0, "Deposited amount should be greater than 0."); balance = balance.add(msg.value); emit FundsOperation ( msg.sender, address(this), address(0x0), msg.value, PaymentType.Ether, OperationType.Receive ); } /** * @dev Unblock blocked funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockFunds(uint _amount) public onlyAuthorized { require( _amount <= blockedBalance, "Amount to unblock should be less or equal than balance" ); blockedBalance = blockedBalance.sub(_amount); balance = balance.add(_amount); emit FundsOperation ( msg.sender, address(this), address(0x0), _amount, PaymentType.Ether, OperationType.Unblock ); } /** * @dev Unblock blocked token funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockTokenFunds(address _tokenAddress, uint _amount) public onlyAuthorized { uint accountedBlockedTokensAmount = blockedTokensBalance[_tokenAddress]; require( _amount <= accountedBlockedTokensAmount, "Tokens amount to unblock should be less or equal than balance" ); blockedTokensBalance[_tokenAddress] = accountedBlockedTokensAmount.sub(_amount); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Unblock ); } /** * @dev Override base contract logic to block this operation for Escrow contract. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return false; } } contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /** * @title Utility contract that provides a way to execute cheap clone deployment of the DecoEscrow contract * on chain. */ contract DecoEscrowFactory is DecoBaseProjectsMarketplace, CloneFactory { // Escrow master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event EscrowCreated(address newEscrowAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Escrow master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Escrow clone. * @param _ownerAddress An address of the Escrow contract owner. * @param _authorizedAddress An addresses that is going to be authorized in Escrow contract. */ function createEscrow( address _ownerAddress, address _authorizedAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrow(clone).initialize( _ownerAddress, _authorizedAddress, relay.shareFee(), relayContractAddress ); emit EscrowCreated(clone); return clone; } } contract IDecoArbitrationTarget { /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public; /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public; /** * @dev Check eligibility of a given address to perform operations. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool); /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool); } library SafeMath { /** * @dev Multiplies two numbers, reverts on 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); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } interface IDecoArbitration { /** * @dev Should be logged upon dispute start. */ event LogStartedDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, int respondentShareProposal ); /** * @dev Should be logged upon proposal rejection. */ event LogRejectedProposal( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 rejectedProposal ); /** * @dev Should be logged upon dispute settlement. */ event LogSettledDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 respondentShare, uint8 initiatorShare ); /** * @dev Should be logged when contract owner updates fees. */ event LogFeesUpdated( uint timestamp, uint fixedFee, uint8 shareFee ); /** * @dev Should be logged when time limit to accept/reject proposal for respondent is updated. */ event LogProposalTimeLimitUpdated( uint timestamp, uint proposalActionTimeLimit ); /** * @dev Should be logged when the withdrawal address for the contract owner changed. */ event LogWithdrawalAddressChanged( uint timestamp, address newWithdrawalAddress ); /** * @notice Start dispute for the given project. * @dev This call should log event and save dispute information and notify `IDecoArbitrationTarget` object * about started dispute. Dipsute can be started only if target instance call of * `canStartDispute` method confirms that state is valid. Also, txn sender and respondent addresses * eligibility must be confirmed by arbitation target `checkEligibility` method call. * @param _idHash A `bytes32` hash of a project id. * @param _respondent An `address` of the second paty involved in the dispute. * @param _respondentShareProposal An `int` value indicating percentage of disputed funds * proposed to the respondent. Valid values range is 0-100, different values are considered as 'No Proposal'. * When provided percentage is 100 then this dispute is processed automatically, * and all funds are distributed in favor of the respondent. */ function startDispute(bytes32 _idHash, address _respondent, int _respondentShareProposal) external; /** * @notice Accept active dispute proposal, sender should be the respondent. * @dev Respondent of a dispute can accept existing proposal and if proposal exists then `settleDispute` * method should be called with proposal value. Time limit for respondent to accept/reject proposal * must not be exceeded. * @param _idHash A `bytes32` hash of a project id. */ function acceptProposal(bytes32 _idHash) external; /** * @notice Reject active dispute proposal and escalate dispute. * @dev Txn sender should be dispute's respondent. Dispute automatically gets escalated to this contract * owner aka arbiter. Proposal must exist, otherwise this method should do nothing. When respondent * rejects proposal then it should get removed and corresponding event should be logged. * There should be a time limit for a respondent to reject a given proposal, and if it is overdue * then arbiter should take on a dispute to settle it. * @param _idHash A `bytes32` hash of a project id. */ function rejectProposal(bytes32 _idHash) external; /** * @notice Settle active dispute. * @dev Sender should be the current contract or its owner(arbiter). Action is possible only when there is no active * proposal or time to accept the proposal is over. Sum of shares should be 100%. Should notify target * instance about a dispute settlement via `disputeSettledTerminate` method call. Also corresponding * event must be emitted. * @param _idHash A `bytes32` hash of a project id. * @param _respondentShare An `uint` percents of respondent share. * @param _initiatorShare An `uint` percents of initiator share. */ function settleDispute(bytes32 _idHash, uint _respondentShare, uint _initiatorShare) external; /** * @return Retuns this arbitration contract withdrawal `address`. */ function getWithdrawalAddress() external view returns(address); /** * @return The arbitration contract fixed `uint` fee and `uint8` share of all disputed funds fee. */ function getFixedAndShareFees() external view returns(uint, uint8); /** * @return An `uint` time limit for accepting/rejecting a proposal by respondent. */ function getTimeLimitForReplyOnProposal() external view returns(uint); } pragma solidity 0.4.25; /// @title Contract for Project events and actions handling. contract DecoProjects is DecoBaseProjectsMarketplace { using SafeMath for uint256; using ECDSA for bytes32; // struct for project details struct Project { string agreementId; address client; address maker; address arbiter; address escrowContractAddress; uint startDate; uint endDate; uint8 milestoneStartWindow; uint8 feedbackWindow; uint8 milestonesCount; uint8 customerSatisfaction; uint8 makerSatisfaction; bool agreementsEncrypted; } struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct Proposal { string agreementId; address arbiter; } bytes32 constant private EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 constant private PROPOSAL_TYPEHASH = keccak256( "Proposal(string agreementId,address arbiter)" ); bytes32 private DOMAIN_SEPARATOR; // enumeration to describe possible project states for easier state changes reporting. enum ProjectState { Active, Completed, Terminated } // enumeration to describe possible satisfaction score types. enum ScoreType { CustomerSatisfaction, MakerSatisfaction } // Logged when a project state changes. event LogProjectStateUpdate ( bytes32 indexed agreementHash, address updatedBy, uint timestamp, ProjectState state ); // Logged when either party sets satisfaction score after the completion of a project. event LogProjectRated ( bytes32 indexed agreementHash, address indexed ratedBy, address indexed ratingTarget, uint8 rating, uint timestamp ); // maps the agreement`s unique hash to the project details. mapping (bytes32 => Project) public projects; // maps hashes of all maker's projects to the maker's address. mapping (address => bytes32[]) public makerProjects; // maps hashes of all client's projects to the client's address. mapping (address => bytes32[]) public clientProjects; // maps arbiter's fixed fee to a project. mapping (bytes32 => uint) public projectArbiterFixedFee; // maps arbiter's share fee to a project. mapping (bytes32 => uint8) public projectArbiterShareFee; // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMaker(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; require( project.client == msg.sender || project.maker == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMakerOrMilestoneContract(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; DecoRelay relay = DecoRelay(relayContractAddress); require( project.client == msg.sender || project.maker == msg.sender || relay.milestonesContractAddress() == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called by the milestones contract. modifier onlyMilestonesContract(bytes32 _agreementHash) { DecoRelay relay = DecoRelay(relayContractAddress); require( msg.sender == relay.milestonesContractAddress(), "Only milestones contract can perform this operation." ); Project memory project = projects[_agreementHash]; _; } constructor (uint256 _chainId) public { require(_chainId != 0, "You must specify a nonzero chainId"); DOMAIN_SEPARATOR = hash(EIP712Domain({ name: "Deco.Network", version: "1", chainId: _chainId, verifyingContract: address(this) })); } /** * @dev Creates a new milestone-based project with pre-selected maker and owner. All parameters are required. * @param _agreementId A `string` unique id of the agreement document for that project. * @param _client An `address` of the project owner. * @param _arbiter An `address` of the referee to settle all escalated disputes between parties. * @param _maker An `address` of the project`s maker. * @param _makersSignature A `bytes` digital signature of the maker to proof the agreement acceptance. * @param _milestonesCount An `uint8` count of planned milestones for the project. * @param _milestoneStartWindow An `uint8` count of days project`s owner has to start the next milestone. * If this time is exceeded then the maker can terminate the project. * @param _feedbackWindow An `uint8` time in days project`s owner has to provide feedback for the last milestone. * If that time is exceeded then maker can terminate the project and get paid for awaited * milestone. * @param _agreementEncrypted A `bool` flag indicating whether or not the agreement is encrypted. */ function startProject( string _agreementId, address _client, address _arbiter, address _maker, bytes _makersSignature, uint8 _milestonesCount, uint8 _milestoneStartWindow, uint8 _feedbackWindow, bool _agreementEncrypted ) external { require(msg.sender == _client, "Only the client can kick off the project."); require(_client != _maker, "Client can`t be a maker on her own project."); require(_arbiter != _maker && _arbiter != _client, "Arbiter must not be a client nor a maker."); require( isMakersSignatureValid(_maker, _makersSignature, _agreementId, _arbiter), "Maker should sign the hash of immutable agreement doc." ); require(_milestonesCount >= 1 && _milestonesCount <= 24, "Milestones count is not in the allowed 1-24 range."); bytes32 hash = keccak256(_agreementId); require(projects[hash].client == address(0x0), "Project shouldn't exist yet."); saveCurrentArbitrationFees(_arbiter, hash); address newEscrowCloneAddress = deployEscrowClone(msg.sender); projects[hash] = Project( _agreementId, msg.sender, _maker, _arbiter, newEscrowCloneAddress, now, 0, // end date is unknown yet _milestoneStartWindow, _feedbackWindow, _milestonesCount, 0, // CSAT is 0 to indicate that it isn't set by maker yet 0, // MSAT is 0 to indicate that it isn't set by client yet _agreementEncrypted ); makerProjects[_maker].push(hash); clientProjects[_client].push(hash); emit LogProjectStateUpdate(hash, msg.sender, now, ProjectState.Active); } /** * @dev Terminate the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function terminateProject(bytes32 _agreementHash) external eitherClientOrMakerOrMilestoneContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); address milestoneContractAddress = DecoRelay(relayContractAddress).milestonesContractAddress(); if (msg.sender != milestoneContractAddress) { DecoMilestones milestonesContract = DecoMilestones(milestoneContractAddress); milestonesContract.terminateLastMilestone(_agreementHash, msg.sender); } project.endDate = now; emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Terminated); } /** * @dev Complete the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function completeProject( bytes32 _agreementHash ) external onlyMilestonesContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); projects[_agreementHash].endDate = now; DecoMilestones milestonesContract = DecoMilestones( DecoRelay(relayContractAddress).milestonesContractAddress() ); bool isLastMilestoneAccepted; uint8 milestoneNumber; (isLastMilestoneAccepted, milestoneNumber) = milestonesContract.isLastMilestoneAccepted( _agreementHash ); require( milestoneNumber == projects[_agreementHash].milestonesCount, "The last milestone should be the last for that project." ); require(isLastMilestoneAccepted, "Only allowed when all milestones are completed."); emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Completed); } /** * @dev Rate the second party on the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @param _rating An `uint8` satisfaction score of either client or maker. Min value is 1, max is 10. */ function rateProjectSecondParty( bytes32 _agreementHash, uint8 _rating ) external eitherClientOrMaker(_agreementHash) { require(_rating >= 1 && _rating <= 10, "Project rating should be in the range 1-10."); Project storage project = projects[_agreementHash]; require(project.endDate != 0, "Only allowed for active projects."); address ratingTarget; if (msg.sender == project.client) { require(project.customerSatisfaction == 0, "CSAT is allowed to provide only once."); project.customerSatisfaction = _rating; ratingTarget = project.maker; } else { require(project.makerSatisfaction == 0, "MSAT is allowed to provide only once."); project.makerSatisfaction = _rating; ratingTarget = project.client; } emit LogProjectRated(_agreementHash, msg.sender, ratingTarget, _rating, now); } /** * @dev Query for getting the address of Escrow contract clone deployed for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a clone. */ function getProjectEscrowAddress(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].escrowContractAddress; } /** * @dev Query for getting the address of a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a client. */ function getProjectClient(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].client; } /** * @dev Query for getting the address of a maker for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a maker. */ function getProjectMaker(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].maker; } /** * @dev Query for getting the address of an arbiter for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of an arbiter. */ function getProjectArbiter(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].arbiter; } /** * @dev Query for getting the feedback window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` feedback window in days. */ function getProjectFeedbackWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].feedbackWindow; } /** * @dev Query for getting the milestone start window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` milestone start window in days. */ function getProjectMilestoneStartWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestoneStartWindow; } /** * @dev Query for getting the start date for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` start date. */ function getProjectStartDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].startDate; } /** * @dev Calculates sum and number of CSAT scores of ended & rated projects for the given maker`s address. * @param _maker An `address` of the maker to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function makersAverageRating(address _maker) public view returns(uint, uint) { return calculateScore(_maker, ScoreType.CustomerSatisfaction); } /** * @dev Calculates sum and number of MSAT scores of ended & rated projects for the given client`s address. * @param _client An `address` of the client to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function clientsAverageRating(address _client) public view returns(uint, uint) { return calculateScore(_client, ScoreType.MakerSatisfaction); } /** * @dev Returns hashes of all client`s projects * @param _client An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getClientProjects(address _client) public view returns(bytes32[]) { return clientProjects[_client]; } /** @dev Returns hashes of all maker`s projects * @param _maker An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getMakerProjects(address _maker) public view returns(bytes32[]) { return makerProjects[_maker]; } /** * @dev Checks if a project with the given hash exists. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return A `bool` stating for the project`s existence. */ function checkIfProjectExists(bytes32 _agreementHash) public view returns(bool) { return projects[_agreementHash].client != address(0x0); } /** * @dev Query for getting end date of the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` end time of the project */ function getProjectEndDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].endDate; } /** * @dev Returns preconfigured count of milestones for a project with the given hash. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` count of milestones set upon the project creation. */ function getProjectMilestonesCount(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestonesCount; } /** * @dev Returns configured for the given project arbiter fees. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` fixed fee and an `uint8` share fee of the project's arbiter. */ function getProjectArbitrationFees(bytes32 _agreementHash) public view returns(uint, uint8) { return ( projectArbiterFixedFee[_agreementHash], projectArbiterShareFee[_agreementHash] ); } function getInfoForDisputeAndValidate( bytes32 _agreementHash, address _respondent, address _initiator, address _arbiter ) public view returns(uint, uint8, address) { require(checkIfProjectExists(_agreementHash), "Project must exist."); Project memory project = projects[_agreementHash]; address client = project.client; address maker = project.maker; require(project.arbiter == _arbiter, "Arbiter should be same as saved in project."); require( (_initiator == client && _respondent == maker) || (_initiator == maker && _respondent == client), "Initiator and respondent must be different and equal to maker/client addresses." ); (uint fixedFee, uint8 shareFee) = getProjectArbitrationFees(_agreementHash); return (fixedFee, shareFee, project.escrowContractAddress); } /** * @dev Pulls the current arbitration contract fixed & share fees and save them for a project. * @param _arbiter An `address` of arbitration contract. * @param _agreementHash A `bytes32` hash of agreement id. */ function saveCurrentArbitrationFees(address _arbiter, bytes32 _agreementHash) internal { IDecoArbitration arbitration = IDecoArbitration(_arbiter); uint fixedFee; uint8 shareFee; (fixedFee, shareFee) = arbitration.getFixedAndShareFees(); projectArbiterFixedFee[_agreementHash] = fixedFee; projectArbiterShareFee[_agreementHash] = shareFee; } /** * @dev Calculates the sum of scores and the number of ended and rated projects for the given client`s or * maker`s address. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` indicating what score should be calculated. * `CustomerSatisfaction` type means that CSAT score for the given address as a maker should be calculated. * `MakerSatisfaction` type means that MSAT score for the given address as a client should be calculated. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function calculateScore( address _address, ScoreType _scoreType ) internal view returns(uint, uint) { bytes32[] memory allProjectsHashes = getProjectsByScoreType(_address, _scoreType); uint rating = 0; uint endedProjectsCount = 0; for (uint index = 0; index < allProjectsHashes.length; index++) { bytes32 agreementHash = allProjectsHashes[index]; if (projects[agreementHash].endDate == 0) { continue; } uint8 score = getProjectScoreByType(agreementHash, _scoreType); if (score == 0) { continue; } endedProjectsCount++; rating = rating.add(score); } return (rating, endedProjectsCount); } /** * @dev Returns all projects for the given address depending on the provided score type. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` to identify projects source. * @return `bytes32[]` of projects hashes either from `clientProjects` or `makerProjects` storage arrays. */ function getProjectsByScoreType(address _address, ScoreType _scoreType) internal view returns(bytes32[]) { if (_scoreType == ScoreType.CustomerSatisfaction) { return makerProjects[_address]; } else { return clientProjects[_address]; } } /** * @dev Returns project score by the given type. * @param _agreementHash A `bytes32` hash of a project`s agreement id. * @param _scoreType A `ScoreType` to identify what score is requested. * @return An `uint8` score of the given project and of the given type. */ function getProjectScoreByType(bytes32 _agreementHash, ScoreType _scoreType) internal view returns(uint8) { if (_scoreType == ScoreType.CustomerSatisfaction) { return projects[_agreementHash].customerSatisfaction; } else { return projects[_agreementHash].makerSatisfaction; } } /** * @dev Deploy DecoEscrow contract clone for the newly created project. * @param _newContractOwner An `address` of a new contract owner. * @return An `address` of a new deployed escrow contract. */ function deployEscrowClone(address _newContractOwner) internal returns(address) { DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrowFactory factory = DecoEscrowFactory(relay.escrowFactoryContractAddress()); return factory.createEscrow(_newContractOwner, relay.milestonesContractAddress()); } /** * @dev Check validness of maker's signature on project creation. * @param _maker An `address` of a maker. * @param _signature A `bytes` digital signature generated by a maker. * @param _agreementId A unique id of the agreement document for a project * @param _arbiter An `address` of a referee to settle all escalated disputes between parties. * @return A `bool` indicating validity of the signature. */ function isMakersSignatureValid(address _maker, bytes _signature, string _agreementId, address _arbiter) internal view returns (bool) { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(Proposal(_agreementId, _arbiter)) )); address signatureAddress = digest.recover(_signature); return signatureAddress == _maker; } function hash(EIP712Domain eip712Domain) internal view returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } function hash(Proposal proposal) internal view returns (bytes32) { return keccak256(abi.encode( PROPOSAL_TYPEHASH, keccak256(bytes(proposal.agreementId)), proposal.arbiter )); } } /// @title Contract for Milesotone events and actions handling. contract DecoMilestones is IDecoArbitrationTarget, DecoBaseProjectsMarketplace { address public constant ETH_TOKEN_ADDRESS = address(0x0); // struct to describe Milestone struct Milestone { uint8 milestoneNumber; // original duration of a milestone. uint32 duration; // track all adjustments caused by state changes Active <-> Delivered <-> Rejected // `adjustedDuration` time gets increased by the time that is spent by client // to provide a feedback when agreed milestone time is not exceeded yet. // Initial value is the same as duration. uint32 adjustedDuration; uint depositAmount; address tokenAddress; uint startedTime; uint deliveredTime; uint acceptedTime; // indicates that a milestone progress was paused. bool isOnHold; } // enumeration to describe possible milestone states. enum MilestoneState { Active, Delivered, Accepted, Rejected, Terminated, Paused } // map agreement id hash to milestones list. mapping (bytes32 => Milestone[]) public projectMilestones; // Logged when milestone state changes. event LogMilestoneStateUpdated ( bytes32 indexed agreementHash, address indexed sender, uint timestamp, uint8 milestoneNumber, MilestoneState indexed state ); event LogMilestoneDurationAdjusted ( bytes32 indexed agreementHash, address indexed sender, uint32 amountAdded, uint8 milestoneNumber ); /** * @dev Starts a new milestone for the project and deposit ETH in smart contract`s escrow. * @param _agreementHash A `bytes32` hash of the agreement id. * @param _depositAmount An `uint` of wei that are going to be deposited for a new milestone. * @param _duration An `uint` seconds of a milestone duration. */ function startMilestone( bytes32 _agreementHash, uint _depositAmount, address _tokenAddress, uint32 _duration ) external { uint8 completedMilestonesCount = uint8(projectMilestones[_agreementHash].length); if (completedMilestonesCount > 0) { Milestone memory lastMilestone = projectMilestones[_agreementHash][completedMilestonesCount - 1]; require(lastMilestone.acceptedTime > 0, "All milestones must be accepted prior starting a new one."); } DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require( projectsContract.getProjectClient(_agreementHash) == msg.sender, "Only project's client starts a miestone" ); require( projectsContract.getProjectMilestonesCount(_agreementHash) > completedMilestonesCount, "Milestones count should not exceed the number configured in the project." ); require( projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active." ); blockFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), _depositAmount, _tokenAddress ); uint nowTimestamp = now; projectMilestones[_agreementHash].push( Milestone( completedMilestonesCount + 1, _duration, _duration, _depositAmount, _tokenAddress, nowTimestamp, 0, 0, false ) ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, completedMilestonesCount + 1, MilestoneState.Active ); } /** * @dev Maker delivers the current active milestone. * @param _agreementHash Project`s unique hash. */ function deliverLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectMaker(_agreementHash) == msg.sender, "Sender must be a maker."); uint nowTimestamp = now; uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to make a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.deliveredTime == 0 && milestone.acceptedTime == 0, "Milestone must be active, not delivered and not accepted." ); require(!milestone.isOnHold, "Milestone must not be paused."); milestone.deliveredTime = nowTimestamp; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Delivered ); } /** * @dev Project owner accepts the current delivered milestone. * @param _agreementHash Project`s unique hash. */ function acceptLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to accept a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or put on hold." ); uint nowTimestamp = now; milestone.acceptedTime = nowTimestamp; if (projectsContract.getProjectMilestonesCount(_agreementHash) == milestonesCount) { projectsContract.completeProject(_agreementHash); } distributeFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), projectsContract.getProjectMaker(_agreementHash), milestone.depositAmount, milestone.tokenAddress ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Accepted ); } /** * @dev Project owner rejects the current active milestone. * @param _agreementHash Project`s unique hash. */ function rejectLastDeliverable(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to reject a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or on hold." ); uint nowTimestamp = now; if (milestone.startedTime.add(milestone.adjustedDuration) > milestone.deliveredTime) { uint32 timeToAdd = uint32(nowTimestamp.sub(milestone.deliveredTime)); milestone.adjustedDuration += timeToAdd; emit LogMilestoneDurationAdjusted ( _agreementHash, msg.sender, timeToAdd, milestonesCount ); } milestone.deliveredTime = 0; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Rejected ); } /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require( projectsContract.getProjectArbiter(_idHash) == msg.sender, "Freezing upon dispute start can be sent only by arbiter." ); uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be active milestone."); Milestone storage lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; lastMilestone.isOnHold = true; emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Paused ); } /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public { uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be at least one milestone."); Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; require(lastMilestone.isOnHold, "Last milestone must be on hold."); require(uint(_respondentShare).add(uint(_initiatorShare)) == 100, "Shares must be 100% in sum."); DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); ( uint fixedFee, uint8 shareFee, address escrowAddress ) = projectsContract.getInfoForDisputeAndValidate ( _idHash, _respondent, _initiator, msg.sender ); distributeDisputeFunds( escrowAddress, lastMilestone.tokenAddress, _respondent, _initiator, _initiatorShare, _isInternal, _arbiterWithdrawalAddress, lastMilestone.depositAmount, fixedFee, shareFee ); projectsContract.terminateProject(_idHash); emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Check eligibility of a given address to perform operations, * basically the address should be either client or maker. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); return _addressToCheck == projectsContract.getProjectClient(_idHash) || _addressToCheck == projectsContract.getProjectMaker(_idHash); } /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool) { uint milestonesCount = projectMilestones[_idHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; if (lastMilestone.isOnHold || lastMilestone.acceptedTime > 0) return false; address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_idHash)).mul(24 hours); uint nowTimestamp = now; uint plannedDeliveryTime = lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)); if (plannedDeliveryTime < lastMilestone.deliveredTime || plannedDeliveryTime < nowTimestamp) { return false; } if (lastMilestone.deliveredTime > 0 && lastMilestone.deliveredTime.add(feedbackWindow) < nowTimestamp) return false; return true; } /** * @dev Either project owner or maker can terminate the project in certain cases * and the current active milestone must be marked as terminated for records-keeping. * All blocked funds should be distributed in favor of eligible project party. * The termination with this method initiated only by project contract. * @param _agreementHash Project`s unique hash. * @param _initiator An `address` of the termination initiator. */ function terminateLastMilestone(bytes32 _agreementHash, address _initiator) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); require(msg.sender == projectsContractAddress, "Method should be called by Project contract."); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); address projectClient = projectsContract.getProjectClient(_agreementHash); address projectMaker = projectsContract.getProjectMaker(_agreementHash); require( _initiator == projectClient || _initiator == projectMaker, "Initiator should be either maker or client address." ); if (_initiator == projectClient) { require(canClientTerminate(_agreementHash)); } else { require(canMakerTerminate(_agreementHash)); } uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; if (lastMilestone.acceptedTime > 0) return; address projectEscrowContractAddress = projectsContract.getProjectEscrowAddress(_agreementHash); if (_initiator == projectClient) { unblockFundsInEscrow( projectEscrowContractAddress, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } else { distributeFundsInEscrow( projectEscrowContractAddress, _initiator, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } emit LogMilestoneStateUpdated( _agreementHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Returns the last project milestone completion status and number. * @param _agreementHash Project's unique hash. * @return isAccepted A boolean flag for acceptance state, and milestoneNumber for the last milestone. */ function isLastMilestoneAccepted( bytes32 _agreementHash ) public view returns(bool isAccepted, uint8 milestoneNumber) { milestoneNumber = uint8(projectMilestones[_agreementHash].length); if (milestoneNumber > 0) { isAccepted = projectMilestones[_agreementHash][milestoneNumber - 1].acceptedTime > 0; } else { isAccepted = false; } } /** * @dev Client can terminate milestone if the last milestone delivery is overdue and * milestone is not on hold. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by client. */ function canClientTerminate(bytes32 _agreementHash) public view returns(bool) { uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; return lastMilestone.acceptedTime == 0 && !lastMilestone.isOnHold && lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)) < now; } /** * @dev Maker can terminate milestone if delivery review is taking longer than project feedback window and * milestone is not on hold, or if client doesn't start the next milestone for a period longer than * project's milestone start window. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by maker. */ function canMakerTerminate(bytes32 _agreementHash) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_agreementHash)).mul(24 hours); uint milestoneStartWindow = uint(projectsContract.getProjectMilestoneStartWindow( _agreementHash )).mul(24 hours); uint projectStartDate = projectsContract.getProjectStartDate(_agreementHash); uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return now.sub(projectStartDate) > milestoneStartWindow; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; uint nowTimestamp = now; if (!lastMilestone.isOnHold && lastMilestone.acceptedTime > 0 && nowTimestamp.sub(lastMilestone.acceptedTime) > milestoneStartWindow) return true; return !lastMilestone.isOnHold && lastMilestone.acceptedTime == 0 && lastMilestone.deliveredTime > 0 && nowTimestamp.sub(feedbackWindow) > lastMilestone.deliveredTime; } /* * @dev Block funds in escrow from balance to the blocked balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function blockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.blockFunds(_amount); } else { escrow.blockTokenFunds(_tokenAddress, _amount); } } /* * @dev Unblock funds in escrow from blocked balance to the balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function unblockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.unblockFunds(_amount); } else { escrow.unblockTokenFunds(_tokenAddress, _amount); } } /** * @dev Distribute funds in escrow from blocked balance to the target address. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _distributionTargetAddress Target `address`. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function distributeFundsInEscrow( address _projectEscrowContractAddress, address _distributionTargetAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.distributeFunds(_distributionTargetAddress, _amount); } else { escrow.distributeTokenFunds(_distributionTargetAddress, _tokenAddress, _amount); } } /** * @dev Distribute project funds between arbiter and project parties. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _tokenAddress An `address` of a token. * @param _respondent An `address` of a respondent. * @param _initiator An `address` of an initiator. * @param _initiatorShare An `uint8` iniator`s share. * @param _isInternal A `bool` indicating if dispute was settled solely by project parties. * @param _arbiterWithdrawalAddress A withdrawal `address` of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. */ function distributeDisputeFunds( address _projectEscrowContractAddress, address _tokenAddress, address _respondent, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress, uint _amount, uint _fixedFee, uint8 _shareFee ) internal { if (!_isInternal && _arbiterWithdrawalAddress != address(0x0)) { uint arbiterFee = getArbiterFeeAmount(_fixedFee, _shareFee, _amount, _tokenAddress); distributeFundsInEscrow( _projectEscrowContractAddress, _arbiterWithdrawalAddress, arbiterFee, _tokenAddress ); _amount = _amount.sub(arbiterFee); } uint initiatorAmount = _amount.mul(_initiatorShare).div(100); distributeFundsInEscrow( _projectEscrowContractAddress, _initiator, initiatorAmount, _tokenAddress ); distributeFundsInEscrow( _projectEscrowContractAddress, _respondent, _amount.sub(initiatorAmount), _tokenAddress ); } /** * @dev Calculates arbiter`s fee. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _tokenAddress An `address` of a token. * @return An `uint` amount allotted to the arbiter. */ function getArbiterFeeAmount(uint _fixedFee, uint8 _shareFee, uint _amount, address _tokenAddress) internal pure returns(uint) { if (_tokenAddress != ETH_TOKEN_ADDRESS) { _fixedFee = 0; } return _amount.sub(_fixedFee).mul(uint(_shareFee)).div(100).add(_fixedFee); } } contract DecoProxy { using ECDSA for bytes32; /// Emitted when incoming ETH funds land into account. event Received (address indexed sender, uint value); /// Emitted when transaction forwarded to the next destination. event Forwarded ( bytes signature, address indexed signer, address indexed destination, uint value, bytes data, bytes32 _hash ); /// Emitted when owner is changed event OwnerChanged ( address indexed newOwner ); bool internal isInitialized; // Keep track to avoid replay attack. uint public nonce; /// Proxy owner. address public owner; /** * @dev Initialize the Proxy clone with default values. * @param _owner An address that orders forwarding of transactions. */ function initialize(address _owner) public { require(!isInitialized, "Clone must be initialized only once."); isInitialized = true; owner = _owner; } /** * @dev Payable fallback to accept incoming payments. */ function () external payable { emit Received(msg.sender, msg.value); } /** * @dev Change the owner of this proxy. Used when the user forgets their key, and we can recover it via SSSS split key. This will be the final txn of the forgotten key as it transfers ownership of the proxy to the new replacement key. Note that this is also callable by the contract itself, which would be used in the case that a user is changing their owner address via a metatxn * @param _newOwner An `address` of the new proxy owner. */ function changeOwner(address _newOwner) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can change owner"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Forward a regular (non meta) transaction to the destination address. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forwardFromOwner(address _destination, uint _value, bytes memory _data) public { require(owner == msg.sender, "Only owner can use forwardFromOwner method"); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded("", owner, _destination, _value, _data, ""); } /** * @dev Returns hash for the given transaction. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. * @return A `bytes32` hash calculated for all incoming parameters. */ function getHash( address _signer, address _destination, uint _value, bytes memory _data ) public view returns(bytes32) { return keccak256(abi.encodePacked(address(this), _signer, _destination, _value, _data, nonce)); } /** * @dev Forward a meta transaction to the destination address. * @param _signature A `bytes` array cotaining signature generated by owner. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forward(bytes memory _signature, address _signer, address _destination, uint _value, bytes memory _data) public { bytes32 hash = getHash(_signer, _destination, _value, _data); nonce++; require(owner == hash.toEthSignedMessageHash().recover(_signature), "Signer must be owner."); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded(_signature, _signer, _destination, _value, _data, hash); } /** * @dev Withdraw given amount of wei to the specified address. * @param _to An `address` of where to send the wei. * @param _value An `uint` amount to withdraw from the contract balance. */ function withdraw(address _to, uint _value) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); _to.transfer(_value); } /** * @dev Withdraw any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _to An `address` of where to send the tokens. * @param _tokens An `uint` tokens amount. */ function withdrawERC20Token(address _tokenAddress, address _to, uint _tokens) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); IERC20 token = IERC20(_tokenAddress); require(token.transfer(_to, _tokens), "Tokens transfer must complete successfully."); } /** * @dev Forward txn by executing a call. * @param _to Destination `address`. * @param _value An `uint256` Wei value to be sent out. * @param _data A `bytes` array with txn data. * @return A `bool` completion status. */ function executeCall(address _to, uint256 _value, bytes memory _data) internal returns (bool success) { assembly { let x := mload(0x40) success := call(gas, _to, _value, add(_data, 0x20), mload(_data), 0, 0) } } } contract DecoProxyFactory is DecoBaseProjectsMarketplace, CloneFactory { // Proxy master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event ProxyCreated(address newProxyAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Proxy master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Proxy clone. * @param _ownerAddress An address of the Proxy contract owner. */ function createProxy( address _ownerAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoProxy(clone).initialize( _ownerAddress ); emit ProxyCreated(clone); return clone; } }
* @dev Initialize the Escrow clone with default values. @param _newOwner An address of a new escrow owner. @param _authorizedAddress An address that will be stored as authorized./
function initialize( address _newOwner, address _authorizedAddress, uint8 _shareFee, address _relayContractAddress ) external { require(!isInitialized, "Only uninitialized contracts allowed."); isInitialized = true; authorizedAddress = _authorizedAddress; emit FundsDistributionAuthorization(_authorizedAddress, true); _transferOwnership(_newOwner); shareFee = _shareFee; relayContractAddress = _relayContractAddress; }
1,084,619
[ 1, 7520, 326, 512, 1017, 492, 3236, 598, 805, 924, 18, 225, 389, 2704, 5541, 1922, 1758, 434, 279, 394, 2904, 492, 3410, 18, 225, 389, 8434, 1887, 1922, 1758, 716, 903, 506, 4041, 487, 10799, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4046, 12, 203, 3639, 1758, 389, 2704, 5541, 16, 203, 3639, 1758, 389, 8434, 1887, 16, 203, 3639, 2254, 28, 389, 14419, 14667, 16, 203, 3639, 1758, 389, 2878, 528, 8924, 1887, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 5, 291, 11459, 16, 315, 3386, 640, 13227, 20092, 2935, 1199, 1769, 203, 3639, 25359, 273, 638, 31, 203, 3639, 10799, 1887, 273, 389, 8434, 1887, 31, 203, 3639, 3626, 478, 19156, 9003, 6063, 24899, 8434, 1887, 16, 638, 1769, 203, 3639, 389, 13866, 5460, 12565, 24899, 2704, 5541, 1769, 203, 3639, 7433, 14667, 273, 389, 14419, 14667, 31, 203, 3639, 18874, 8924, 1887, 273, 389, 2878, 528, 8924, 1887, 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 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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&#39;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; } } /** * @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 * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == 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(0)); 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); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // 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 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; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @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 totalTokens; } /** * @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) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner 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)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for 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(_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); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ 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); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga&#39;s cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero&#39;s type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero&#39;s name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero&#39;s stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class&#39;s entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class&#39;s name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class&#39;s rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero&#39;s entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero&#39;s class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero&#39;s name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero&#39;s level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero&#39;s location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero&#39;s BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero&#39;s required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero&#39;s required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player&#39;s #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero&#39;s name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero&#39;s class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don&#39;t overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero&#39;s class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn&#39;t level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender&#39;s Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCardSwapVer2 * @dev This directly summons hero. */ contract CryptoSagaCardSwapVer2 is CryptoSagaCardSwap, Pausable{ // Eth will be sent to this wallet. address public wallet; // The hero contract. CryptoSagaHero public heroContract; // Gold contract. Gold public goldContract; // Eth-Summon price. uint256 public ethPrice = 20000000000000000; // 0.02 eth. // Gold-Summon price. uint256 public goldPrice = 100000000000000000000; // 100 G. Should worth around 0.00004 eth at launch. // Mileage Point Summon price. uint256 public mileagePointPrice = 100; // Blacklisted heroes. // This is needed in order to protect players, in case there exists any hero with critical issues. // We promise we will use this function carefully, and this won&#39;t be used for balancing the OP heroes. mapping(uint32 => bool) public blackList; // Mileage points of each player. mapping(address => uint256) public addressToMileagePoint; // Last timestamp of summoning a free hero. mapping(address => uint256) public addressToFreeSummonTimestamp; // Random seed. uint32 private seed = 0; // @dev Get the mileage points of given address. function getMileagePoint(address _address) public view returns (uint256) { return addressToMileagePoint[_address]; } // @dev Get the summon timestamp of given address. function getFreeSummonTimestamp(address _address) public view returns (uint256) { return addressToFreeSummonTimestamp[_address]; } // @dev Set the price of summoning a hero with Eth. function setEthPrice(uint256 _value) onlyOwner public { ethPrice = _value; } // @dev Set the price of summoning a hero with Gold. function setGoldPrice(uint256 _value) onlyOwner public { goldPrice = _value; } // @dev Set the price of summong a hero with Mileage Points. function setMileagePointPrice(uint256 _value) onlyOwner public { mileagePointPrice = _value; } // @dev Set blacklist. function setBlacklist(uint32 _classId, bool _value) onlyOwner public { blackList[_classId] = _value; } // @dev Increment mileage points. function addMileagePoint(address _beneficiary, uint256 _point) onlyOwner public { require(_beneficiary != address(0)); addressToMileagePoint[_beneficiary] += _point; } // @dev Contructor. function CryptoSagaCardSwapVer2(address _heroAddress, address _goldAddress, address _cardAddress, address _walletAddress) public { require(_heroAddress != address(0)); require(_goldAddress != address(0)); require(_cardAddress != address(0)); require(_walletAddress != address(0)); wallet = _walletAddress; heroContract = CryptoSagaHero(_heroAddress); goldContract = Gold(_goldAddress); setCardContract(_cardAddress); } // @dev Swap a card for a hero. function swapCardForReward(address _by, uint8 _rank) onlyCard whenNotPaused public returns (uint256) { // This is becaue we need to use tx.origin here. // _by should be the beneficiary, but due to the bug that is already exist with CryptoSagaCard.sol, // tx.origin is used instead of _by. require(tx.origin != _by && tx.origin != msg.sender); // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_rank == 0) { // Origin Card. 85% Heroic, 15% Legendary. if (_randomValue < 8500) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } } else if (_rank == 3) { // Dungeon Chest card. if (_randomValue < 6500) { _heroRankToMint = 1; } else if (_randomValue < 9945) { _heroRankToMint = 2; } else if (_randomValue < 9995) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } } else { // Do nothing here. _heroRankToMint = 0; } // Summon the hero. return summonHero(tx.origin, _heroRankToMint); } // @dev Pay with Eth. function payWithEth(uint256 _amount, address _referralAddress) whenNotPaused public payable { require(msg.sender != address(0)); // Referral address shouldn&#39;t be the same address. require(msg.sender != _referralAddress); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = ethPrice * _amount; require(msg.value >= _priceOfBundle); // Send the raised eth to the wallet. wallet.transfer(_priceOfBundle); for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9550) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); // In case there exists referral address... if (_referralAddress != address(0)) { // Add mileage to the referral address. addressToMileagePoint[_referralAddress] += 5; addressToMileagePoint[msg.sender] += 3; } } } // @dev Pay with Gold. function payWithGold(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = goldPrice * _amount; require(goldContract.allowance(msg.sender, this) >= _priceOfBundle); if (goldContract.transferFrom(msg.sender, this, _priceOfBundle)) { for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 3000) { _heroRankToMint = 0; } else if (_randomValue < 7500) { _heroRankToMint = 1; } else if (_randomValue < 9945) { _heroRankToMint = 2; } else if (_randomValue < 9995) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } } // @dev Pay with Mileage. function payWithMileagePoint(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = mileagePointPrice * _amount; require(addressToMileagePoint[msg.sender] >= _priceOfBundle); // Decrement mileage point. addressToMileagePoint[msg.sender] -= _priceOfBundle; for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9050) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } // @dev Free daily summon. function payWithDailyFreePoint() whenNotPaused public { require(msg.sender != address(0)); // Only once a day. require(now > addressToFreeSummonTimestamp[msg.sender] + 1 days); addressToFreeSummonTimestamp[msg.sender] = now; // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5500) { _heroRankToMint = 0; } else if (_randomValue < 9850) { _heroRankToMint = 1; } else { _heroRankToMint = 2; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } // @dev Summon a hero. // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256) { // Get the list of hero classes. uint32 _numberOfClasses = heroContract.numberOfHeroClasses(); uint32[] memory _candidates = new uint32[](_numberOfClasses); uint32 _count = 0; for (uint32 i = 0; i < _numberOfClasses; i ++) { if (heroContract.getClassRank(i) == _heroRankToMint && blackList[i] != true) { _candidates[_count] = i; _count++; } } require(_count != 0); return heroContract.mint(_to, _candidates[random(_count, 0)]); } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } }
@dev Set the price of summoning a hero with Eth.
function setEthPrice(uint256 _value) onlyOwner public { ethPrice = _value; }
2,391,196
[ 1, 694, 326, 6205, 434, 2142, 2586, 310, 279, 366, 2439, 598, 512, 451, 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 ]
[ 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, 445, 444, 41, 451, 5147, 12, 11890, 5034, 389, 1132, 13, 203, 565, 1338, 5541, 203, 565, 1071, 203, 225, 288, 203, 565, 13750, 5147, 273, 389, 1132, 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, -100, -100 ]
// File: ERC20.sol pragma solidity ^0.5.10; /// @title ERC20 interface is a subset of the ERC20 specification. /// @notice see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function allowance(address _owner, address _spender) external view returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function balanceOf(address _who) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } // File: 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) { 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; } } // File: Address.sol pragma solidity ^0.5.0; /** * @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. * * > 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: SafeERC20.sol /** * The MIT License (MIT) * * Copyright (c) 2016-2019 zOS Global Limited * * 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.5.0; /** * @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 ERC20;` 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(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 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(ERC20 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(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(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(ERC20 token, bytes memory data) internal { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length 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"); } } } // File: transferrable.sol /** * Transferrable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself contract Transferrable { using SafeERC20 for ERC20; /// @dev This function is used to move tokens sent accidentally to this contract method. /// @dev The owner can chose the new destination address /// @param _to is the recipient's address. /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @param _amount is the amount to be transferred in base units. function _safeTransfer(address payable _to, address _asset, uint _amount) internal { // address(0) is used to denote ETH if (_asset == address(0)) { _to.transfer(_amount); } else { ERC20(_asset).safeTransfer(_to, _amount); } } } // File: balanceable.sol /** * Balanceable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Balanceable - This is a contract used to get a balance contract Balanceable { /// @dev This function is used to get a balance /// @param _address of which balance we are trying to ascertain /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @return balance associated with an address, for any token, in the wei equivalent function _balance(address _address, address _asset) internal view returns (uint) { if (_asset != address(0)) { return ERC20(_asset).balanceOf(_address); } else { return _address.balance; } } } // File: burner.sol /** * IBurner - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; // The BurnerToken interface is the interface to a token contract which // provides the total burnable supply for the TokenHolder contract. interface IBurner { function currentSupply() external view returns (uint); } // File: ownable.sol /** * Ownable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Ownable has an owner address and provides basic authorization control functions. /// This contract is modified version of the MIT OpenZepplin Ownable contract /// This contract allows for the transferOwnership operation to be made impossible /// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol contract Ownable { event TransferredOwnership(address _from, address _to); event LockedOwnership(address _locked); address payable private _owner; bool private _isTransferable; /// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable. constructor(address payable _account_, bool _transferable_) internal { _owner = _account_; _isTransferable = _transferable_; // Emit the LockedOwnership event if no longer transferable. if (!_isTransferable) { emit LockedOwnership(_account_); } emit TransferredOwnership(address(0), _account_); } /// @notice Reverts if called by any account other than the owner. modifier onlyOwner() { require(_isOwner(msg.sender), "sender is not an owner"); _; } /// @notice Allows the current owner to transfer control of the contract to a new address. /// @param _account address to transfer ownership to. /// @param _transferable indicates whether to keep the ownership transferable. function transferOwnership(address payable _account, bool _transferable) external onlyOwner { // Require that the ownership is transferable. require(_isTransferable, "ownership is not transferable"); // Require that the new owner is not the zero address. require(_account != address(0), "owner cannot be set to zero address"); // Set the transferable flag to the value _transferable passed in. _isTransferable = _transferable; // Emit the LockedOwnership event if no longer transferable. if (!_transferable) { emit LockedOwnership(_account); } // Emit the ownership transfer event. emit TransferredOwnership(_owner, _account); // Set the owner to the provided address. _owner = _account; } /// @notice check if the ownership is transferable. /// @return true if the ownership is transferable. function isTransferable() external view returns (bool) { return _isTransferable; } /// @notice Allows the current owner to relinquish control of the contract. /// @dev Renouncing to ownership will leave the contract without an owner and unusable. /// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore. function renounceOwnership() external onlyOwner { // Require that the ownership is transferable. require(_isTransferable, "ownership is not transferable"); // note that this could be terminal _owner = address(0); emit TransferredOwnership(_owner, address(0)); } /// @notice Find out owner address /// @return address of the owner. function owner() public view returns (address payable) { return _owner; } /// @notice Check if owner address /// @return true if sender is the owner of the contract. function _isOwner(address _address) internal view returns (bool) { return _address == _owner; } } // File: controller.sol /** * Controller - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title The IController interface provides access to the isController and isAdmin checks. interface IController { function isController(address) external view returns (bool); function isAdmin(address) external view returns (bool); } /// @title Controller stores a list of controller addresses that can be used for authentication in other contracts. /// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers. /// @dev Owner can change the Admins /// @dev Admins and can the Controllers /// @dev Controllers are used by the application. contract Controller is IController, Ownable, Transferrable { event AddedController(address _sender, address _controller); event RemovedController(address _sender, address _controller); event AddedAdmin(address _sender, address _admin); event RemovedAdmin(address _sender, address _admin); event Claimed(address _to, address _asset, uint _amount); event Stopped(address _sender); event Started(address _sender); mapping (address => bool) private _isAdmin; uint private _adminCount; mapping (address => bool) private _isController; uint private _controllerCount; bool private _stopped; /// @notice Constructor initializes the owner with the provided address. /// @param _ownerAddress_ address of the owner. constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {} /// @notice Checks if message sender is an admin. modifier onlyAdmin() { require(isAdmin(msg.sender), "sender is not an admin"); _; } /// @notice Check if Owner or Admin modifier onlyAdminOrOwner() { require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin"); _; } /// @notice Check if controller is stopped modifier notStopped() { require(!isStopped(), "controller is stopped"); _; } /// @notice Add a new admin to the list of admins. /// @param _account address to add to the list of admins. function addAdmin(address _account) external onlyOwner notStopped { _addAdmin(_account); } /// @notice Remove a admin from the list of admins. /// @param _account address to remove from the list of admins. function removeAdmin(address _account) external onlyOwner { _removeAdmin(_account); } /// @return the current number of admins. function adminCount() external view returns (uint) { return _adminCount; } /// @notice Add a new controller to the list of controllers. /// @param _account address to add to the list of controllers. function addController(address _account) external onlyAdminOrOwner notStopped { _addController(_account); } /// @notice Remove a controller from the list of controllers. /// @param _account address to remove from the list of controllers. function removeController(address _account) external onlyAdminOrOwner { _removeController(_account); } /// @notice count the Controllers /// @return the current number of controllers. function controllerCount() external view returns (uint) { return _controllerCount; } /// @notice is an address an Admin? /// @return true if the provided account is an admin. function isAdmin(address _account) public view notStopped returns (bool) { return _isAdmin[_account]; } /// @notice is an address a Controller? /// @return true if the provided account is a controller. function isController(address _account) public view notStopped returns (bool) { return _isController[_account]; } /// @notice this function can be used to see if the controller has been stopped /// @return true is the Controller has been stopped function isStopped() public view returns (bool) { return _stopped; } /// @notice Internal-only function that adds a new admin. function _addAdmin(address _account) private { require(!_isAdmin[_account], "provided account is already an admin"); require(!_isController[_account], "provided account is already a controller"); require(!_isOwner(_account), "provided account is already the owner"); require(_account != address(0), "provided account is the zero address"); _isAdmin[_account] = true; _adminCount++; emit AddedAdmin(msg.sender, _account); } /// @notice Internal-only function that removes an existing admin. function _removeAdmin(address _account) private { require(_isAdmin[_account], "provided account is not an admin"); _isAdmin[_account] = false; _adminCount--; emit RemovedAdmin(msg.sender, _account); } /// @notice Internal-only function that adds a new controller. function _addController(address _account) private { require(!_isAdmin[_account], "provided account is already an admin"); require(!_isController[_account], "provided account is already a controller"); require(!_isOwner(_account), "provided account is already the owner"); require(_account != address(0), "provided account is the zero address"); _isController[_account] = true; _controllerCount++; emit AddedController(msg.sender, _account); } /// @notice Internal-only function that removes an existing controller. function _removeController(address _account) private { require(_isController[_account], "provided account is not a controller"); _isController[_account] = false; _controllerCount--; emit RemovedController(msg.sender, _account); } /// @notice stop our controllers and admins from being useable function stop() external onlyAdminOrOwner { _stopped = true; emit Stopped(msg.sender); } /// @notice start our controller again function start() external onlyOwner { _stopped = false; emit Started(msg.sender); } //// @notice Withdraw tokens from the smart contract to the specified account. function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped { _safeTransfer(_to, _asset, _amount); emit Claimed(_to, _asset, _amount); } } // File: ENS.sol /** * BSD 2-Clause License * * Copyright (c) 2018, True Names Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } // File: ResolverBase.sol pragma solidity ^0.5.0; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } } // File: ABIResolver.sol pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: AddrResolver.sol pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; event AddrChanged(bytes32 indexed node, address a); mapping(bytes32=>address) addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) external authorised(node) { addresses[node] = addr; emit AddrChanged(node, addr); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return addresses[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: ContentHashResolver.sol pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: InterfaceResolver.sol pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 168 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP168 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 168 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 168 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: NameResolver.sol pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: PubkeyResolver.sol pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: TextResolver.sol pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: PublicResolver.sol /** * BSD 2-Clause License * * Copyright (c) 2018, True Names Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } } // File: ensResolvable.sol /** * ENSResolvable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; ///@title ENSResolvable - Ethereum Name Service Resolver ///@notice contract should be used to get an address for an ENS node contract ENSResolvable { /// @notice _ens is an instance of ENS ENS private _ens; /// @notice _ensRegistry points to the ENS registry smart contract. address private _ensRegistry; /// @param _ensReg_ is the ENS registry used constructor(address _ensReg_) internal { _ensRegistry = _ensReg_; _ens = ENS(_ensRegistry); } /// @notice this is used to that one can observe which ENS registry is being used function ensRegistry() external view returns (address) { return _ensRegistry; } /// @notice helper function used to get the address of a node /// @param _node of the ENS entry that needs resolving /// @return the address of the said node function _ensResolve(bytes32 _node) internal view returns (address) { return PublicResolver(_ens.resolver(_node)).addr(_node); } } // File: controllable.sol /** * Controllable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Controllable implements access control functionality of the Controller found via ENS. contract Controllable is ENSResolvable { /// @dev Is the registered ENS node identifying the controller contract. bytes32 private _controllerNode; /// @notice Constructor initializes the controller contract object. /// @param _controllerNode_ is the ENS node of the Controller. constructor(bytes32 _controllerNode_) internal { _controllerNode = _controllerNode_; } /// @notice Checks if message sender is a controller. modifier onlyController() { require(_isController(msg.sender), "sender is not a controller"); _; } /// @notice Checks if message sender is an admin. modifier onlyAdmin() { require(_isAdmin(msg.sender), "sender is not an admin"); _; } /// @return the controller node registered in ENS. function controllerNode() external view returns (bytes32) { return _controllerNode; } /// @return true if the provided account is a controller. function _isController(address _account) internal view returns (bool) { return IController(_ensResolve(_controllerNode)).isController(_account); } /// @return true if the provided account is an admin. function _isAdmin(address _account) internal view returns (bool) { return IController(_ensResolve(_controllerNode)).isAdmin(_account); } } // File: bytesUtils.sol /** * BytesUtils - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title BytesUtils provides basic byte slicing and casting functionality. library BytesUtils { using SafeMath for uint256; /// @dev This function converts to an address /// @param _bts bytes /// @param _from start position function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) { require(_bts.length >= _from.add(20), "slicing out of range"); bytes20 convertedAddress; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { convertedAddress := mload(add(_bts, startByte)) } return address(convertedAddress); } /// @dev This function slices bytes into bytes4 /// @param _bts some bytes /// @param _from start position function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) { require(_bts.length >= _from.add(4), "slicing out of range"); bytes4 slicedBytes4; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { slicedBytes4 := mload(add(_bts, startByte)) } return slicedBytes4; } /// @dev This function slices a uint /// @param _bts some bytes /// @param _from start position // credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity // and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177 function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) { require(_bts.length >= _from.add(32), "slicing out of range"); uint convertedUint256; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { convertedUint256 := mload(add(_bts, startByte)) } return convertedUint256; } } // File: strings.sol /* * Copyright 2016 Nick Johnson * * 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 String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.5.0; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if (b < 0xE0) { ptr += 2; } else if (b < 0xF0) { ptr += 3; } else if (b < 0xF8) { ptr += 4; } else if (b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if (shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if (b < 0xE0) { l = 2; } else if (b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if (b < 0xE0) { ret = b & 0x1F; length = 2; } else if (b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for (uint i = 0; i < parts.length; i++) { length += parts[i]._len; } string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for (uint i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: tokenWhitelist.sol /** * TokenWhitelist - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title The ITokenWhitelist interface provides access to a whitelist of tokens. interface ITokenWhitelist { function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256); function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256); function tokenAddressArray() external view returns (address[] memory); function redeemableTokens() external view returns (address[] memory); function methodIdWhitelist(bytes4) external view returns (bool); function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint); function stablecoin() external view returns (address); function updateTokenRate(address, uint, uint) external; } /// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract contract TokenWhitelist is ENSResolvable, Controllable, Transferrable { using strings for *; using SafeMath for uint256; using BytesUtils for bytes; event UpdatedTokenRate(address _sender, address _token, uint _rate); event UpdatedTokenLoadable(address _sender, address _token, bool _loadable); event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable); event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable); event RemovedToken(address _sender, address _token); event AddedMethodId(bytes4 _methodId); event RemovedMethodId(bytes4 _methodId); event AddedExclusiveMethod(address _token, bytes4 _methodId); event RemovedExclusiveMethod(address _token, bytes4 _methodId); event Claimed(address _to, address _asset, uint _amount); /// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3 bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68 bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd struct Token { string symbol; // Token symbol uint magnitude; // 10^decimals uint rate; // Token exchange rate in wei bool available; // Flags if the token is available or not bool loadable; // Flags if token is loadable to the TokenCard bool redeemable; // Flags if token is redeemable in the TKN Holder contract uint lastUpdate; // Time of the last rate update } mapping(address => Token) private _tokenInfoMap; // @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb mapping(bytes4 => bool) private _methodIdWhitelist; address[] private _tokenAddressArray; /// @notice keeping track of how many redeemable tokens are in the tokenWhitelist uint private _redeemableCounter; /// @notice Address of the stablecoin. address private _stablecoin; /// @notice is registered ENS node identifying the oracle contract. bytes32 private _oracleNode; /// @notice Constructor initializes ENSResolvable, and Controllable. /// @param _ens_ is the ENS registry address. /// @param _oracleNode_ is the ENS node of the Oracle. /// @param _controllerNode_ is our Controllers node. /// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit. constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public { _oracleNode = _oracleNode_; _stablecoin = _stablecoinAddress_; //a priori ERC20 whitelisted methods _methodIdWhitelist[_APPROVE] = true; _methodIdWhitelist[_BURN] = true; _methodIdWhitelist[_TRANSFER] = true; _methodIdWhitelist[_TRANSFER_FROM] = true; } modifier onlyAdminOrOracle() { address oracleAddress = _ensResolve(_oracleNode); require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin"); _; } /// @notice Add ERC20 tokens to the list of whitelisted tokens. /// @param _tokens ERC20 token contract addresses. /// @param _symbols ERC20 token names. /// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token. /// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard. /// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract. /// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211. function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin { // Require that all parameters have the same length. require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match"); // Add each token to the list of supported tokens. for (uint i = 0; i < _tokens.length; i++) { // Require that the token isn't already available. require(!_tokenInfoMap[_tokens[i]].available, "token already available"); // Store the intermediate values. string memory symbol = _symbols[i].toSliceB32().toString(); // Add the token to the token list. _tokenInfoMap[_tokens[i]] = Token({ symbol : symbol, magnitude : _magnitude[i], rate : 0, available : true, loadable : _loadable[i], redeemable: _redeemable[i], lastUpdate : _lastUpdate }); // Add the token address to the address list. _tokenAddressArray.push(_tokens[i]); //if the token is redeemable increase the redeemableCounter if (_redeemable[i]){ _redeemableCounter = _redeemableCounter.add(1); } // Emit token addition event. emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]); } } /// @notice Remove ERC20 tokens from the whitelist of tokens. /// @param _tokens ERC20 token contract addresses. function removeTokens(address[] calldata _tokens) external onlyAdmin { // Delete each token object from the list of supported tokens based on the addresses provided. for (uint i = 0; i < _tokens.length; i++) { // Store the token address. address token = _tokens[i]; //token must be available, reverts on duplicates as well require(_tokenInfoMap[token].available, "token is not available"); //if the token is redeemable decrease the redeemableCounter if (_tokenInfoMap[token].redeemable){ _redeemableCounter = _redeemableCounter.sub(1); } // Delete the token object. delete _tokenInfoMap[token]; // Remove the token address from the address list. for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) { if (_tokenAddressArray[j] == token) { _tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)]; break; } } _tokenAddressArray.length--; // Emit token removal event. emit RemovedToken(msg.sender, token); } } /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific. /// @param _data is the transaction payload. function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) { // Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload: // 4 (signature) + 32(address or uint256) require(_data.length >= 4 + 32, "not enough method-encoding bytes"); // Get the method signature bytes4 signature = _data._bytesToBytes4(0); // Check if method Id is supported require(isERC20MethodSupported(_token, signature), "unsupported method"); // returns the recipient's address and amount is the value to be transferred if (signature == _BURN) { // 4 (signature) + 32(uint256) return (_token, _data._bytesToUint256(4)); } else if (signature == _TRANSFER_FROM) { // 4 (signature) + 32(address) + 32(address) + 32(uint256) require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom"); return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32)); } else { //transfer or approve // 4 (signature) + 32(address) + 32(uint) require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove"); return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32)); } } /// @notice Toggles whether or not a token is loadable or not. function setTokenLoadable(address _token, bool _loadable) external onlyAdmin { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // this sets the loadable flag to the value passed in _tokenInfoMap[_token].loadable = _loadable; emit UpdatedTokenLoadable(msg.sender, _token, _loadable); } /// @notice Toggles whether or not a token is redeemable or not. function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // this sets the redeemable flag to the value passed in _tokenInfoMap[_token].redeemable = _redeemable; emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable); } /// @notice Update ERC20 token exchange rate. /// @param _token ERC20 token contract address. /// @param _rate ERC20 token exchange rate in wei. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // Update the token's rate. _tokenInfoMap[_token].rate = _rate; // Update the token's last update timestamp. _tokenInfoMap[_token].lastUpdate = _updateDate; // Emit the rate update event. emit UpdatedTokenRate(msg.sender, _token, _rate); } //// @notice Withdraw tokens from the smart contract to the specified account. function claim(address payable _to, address _asset, uint _amount) external onlyAdmin { _safeTransfer(_to, _asset, _amount); emit Claimed(_to, _asset, _amount); } /// @notice This returns all of the fields for a given token. /// @param _a is the address of a given token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { Token storage tokenInfo = _tokenInfoMap[_a]; return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate); } /// @notice This returns all of the fields for our StableCoin. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { Token storage stablecoinInfo = _tokenInfoMap[_stablecoin]; return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate); } /// @notice This returns an array of all whitelisted token addresses. /// @return address[] of whitelisted tokens. function tokenAddressArray() external view returns (address[] memory) { return _tokenAddressArray; } /// @notice This returns an array of all redeemable token addresses. /// @return address[] of redeemable tokens. function redeemableTokens() external view returns (address[] memory) { address[] memory redeemableAddresses = new address[](_redeemableCounter); uint redeemableIndex = 0; for (uint i = 0; i < _tokenAddressArray.length; i++) { address token = _tokenAddressArray[i]; if (_tokenInfoMap[token].redeemable){ redeemableAddresses[redeemableIndex] = token; redeemableIndex += 1; } } return redeemableAddresses; } /// @notice This returns true if a method Id is supported for the specific token. /// @return true if _methodId is supported in general or just for the specific token. function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) { require(_tokenInfoMap[_token].available, "non-existing token"); return (_methodIdWhitelist[_methodId]); } /// @notice This returns true if the method is supported for all protected tokens. /// @return true if _methodId is in the method whitelist. function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) { return (_methodIdWhitelist[_methodId]); } /// @notice This returns the number of redeemable tokens. /// @return current # of redeemables. function redeemableCounter() external view returns (uint) { return _redeemableCounter; } /// @notice This returns the address of our stablecoin of choice. /// @return the address of the stablecoin contract. function stablecoin() external view returns (address) { return _stablecoin; } /// @notice this returns the node hash of our Oracle. /// @return the oracle node registered in ENS. function oracleNode() external view returns (bytes32) { return _oracleNode; } } // File: tokenWhitelistable.sol /** * TokenWhitelistable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS. contract TokenWhitelistable is ENSResolvable { /// @notice Is the registered ENS node identifying the tokenWhitelist contract bytes32 private _tokenWhitelistNode; /// @notice Constructor initializes the TokenWhitelistable object. /// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist. constructor(bytes32 _tokenWhitelistNode_) internal { _tokenWhitelistNode = _tokenWhitelistNode_; } /// @notice This shows what TokenWhitelist is being used /// @return TokenWhitelist's node registered in ENS. function tokenWhitelistNode() external view returns (bytes32) { return _tokenWhitelistNode; } /// @notice This returns all of the fields for a given token. /// @param _a is the address of a given token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a); } /// @notice This returns all of the fields for our stablecoin token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo(); } /// @notice This returns an array of our whitelisted addresses. /// @return address[] of our whitelisted tokens. function _tokenAddressArray() internal view returns (address[] memory) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray(); } /// @notice This returns an array of all redeemable token addresses. /// @return address[] of redeemable tokens. function _redeemableTokens() internal view returns (address[] memory) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens(); } /// @notice Update ERC20 token exchange rate. /// @param _token ERC20 token contract address. /// @param _rate ERC20 token exchange rate in wei. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal { ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate); } /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific. /// @param _data is the transaction payload. function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data); } /// @notice Checks whether a token is available. /// @return bool available or not. function _isTokenAvailable(address _a) internal view returns (bool) { ( , , , bool available, , , ) = _getTokenInfo(_a); return available; } /// @notice Checks whether a token is redeemable. /// @return bool redeemable or not. function _isTokenRedeemable(address _a) internal view returns (bool) { ( , , , , , bool redeemable, ) = _getTokenInfo(_a); return redeemable; } /// @notice Checks whether a token is loadable. /// @return bool loadable or not. function _isTokenLoadable(address _a) internal view returns (bool) { ( , , , , bool loadable, , ) = _getTokenInfo(_a); return loadable; } /// @notice This gets the address of the stablecoin. /// @return the address of the stablecoin contract. function _stablecoin() internal view returns (address) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin(); } } // File: holder.sol /** * Holder (aka Asset Contract) - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * 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 <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Holder - The TKN Asset Contract /// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner. contract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable { using SafeMath for uint256; event Received(address _from, uint _amount); event CashAndBurned(address _to, address _asset, uint _amount); event Claimed(address _to, address _asset, uint _amount); /// @dev Check if the sender is the burner contract modifier onlyBurner() { require (msg.sender == _burner, "burner contract is not the sender"); _; } // Burner token which can be burned to redeem shares. address private _burner; /// @notice Constructor initializes the holder contract. /// @param _burnerContract_ is the address of the token contract TKN with burning functionality. /// @param _ens_ is the address of the ENS registry. /// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist. /// @param _controllerNode_ is the ENS node of the Controller constructor (address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public { _burner = _burnerContract_; } /// @notice Ether may be sent from anywhere. function() external payable { emit Received(msg.sender, msg.value); } /// @notice Burn handles disbursing a share of tokens in this contract to a given address. /// @param _to The address to disburse to /// @param _amount The amount of TKN that will be burned if this succeeds function burn(address payable _to, uint _amount) external onlyBurner returns (bool) { if (_amount == 0) { return true; } // The burner token deducts from the supply before calling. uint supply = IBurner(_burner).currentSupply().add(_amount); address[] memory redeemableAddresses = _redeemableTokens(); for (uint i = 0; i < redeemableAddresses.length; i++) { uint redeemableBalance = _balance(address(this), redeemableAddresses[i]); if (redeemableBalance > 0) { uint redeemableAmount = redeemableBalance.mul(_amount).div(supply); _safeTransfer(_to, redeemableAddresses[i], redeemableAmount); emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount); } } return true; } /// @notice This allows for the admin to reclaim the non-redeemableTokens /// @param _to this is the address which the reclaimed tokens will be sent to /// @param _nonRedeemableAddresses this is the array of tokens to be claimed function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) { for (uint i = 0; i < _nonRedeemableAddresses.length; i++) { //revert if token is redeemable require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed"); uint claimBalance = _balance(address(this), _nonRedeemableAddresses[i]); if (claimBalance > 0) { _safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance); emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance); } } return true; } /// @notice Returned the address of the burner contract /// @return the TKN address function burner() external view returns (address) { return _burner; } }
@title ENSResolvable - Ethereum Name Service Resolver@notice contract should be used to get an address for an ENS node
contract ENSResolvable { ENS private _ens; address private _ensRegistry; constructor(address _ensReg_) internal { _ensRegistry = _ensReg_; _ens = ENS(_ensRegistry); } function ensRegistry() external view returns (address) { return _ensRegistry; } function _ensResolve(bytes32 _node) internal view returns (address) { return PublicResolver(_ens.resolver(_node)).addr(_node); } }
913,629
[ 1, 21951, 2903, 16845, 300, 512, 18664, 379, 1770, 1956, 17183, 6835, 1410, 506, 1399, 358, 336, 392, 1758, 364, 392, 512, 3156, 756, 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 ]
[ 1, 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 ]
[ 1, 16351, 512, 3156, 2903, 16845, 288, 203, 565, 512, 3156, 3238, 389, 773, 31, 203, 203, 565, 1758, 3238, 389, 773, 4243, 31, 203, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 773, 1617, 67, 13, 2713, 288, 203, 3639, 389, 773, 4243, 273, 389, 773, 1617, 67, 31, 203, 3639, 389, 773, 273, 512, 3156, 24899, 773, 4243, 1769, 203, 565, 289, 203, 203, 565, 445, 19670, 4243, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 773, 4243, 31, 203, 565, 289, 203, 203, 565, 445, 389, 773, 8460, 12, 3890, 1578, 389, 2159, 13, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 7224, 4301, 24899, 773, 18, 14122, 24899, 2159, 13, 2934, 4793, 24899, 2159, 1769, 203, 565, 289, 203, 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 ]
./full_match/3/0xC8f4bb1153689a34a83BfBF25865504481746B3A/sources/browser/BinanceswapFactory.sol
this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) { uint balance0 = IBEP20Finance0x1(token0).balanceOf(address(this)); uint balance1 = IBEP20Finance0x1(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Finance0x1: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); }
8,236,511
[ 1, 2211, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 225, 10802, 24179, 4271, 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, 312, 474, 12, 2867, 358, 13, 3903, 2176, 1135, 261, 11890, 4501, 372, 24237, 13, 288, 203, 3639, 2254, 11013, 20, 273, 467, 5948, 52, 3462, 6187, 1359, 20, 92, 21, 12, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 11013, 21, 273, 467, 5948, 52, 3462, 6187, 1359, 20, 92, 21, 12, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 3844, 20, 273, 11013, 20, 18, 1717, 24899, 455, 6527, 20, 1769, 203, 3639, 2254, 3844, 21, 273, 11013, 21, 18, 1717, 24899, 455, 6527, 21, 1769, 203, 203, 3639, 1426, 14036, 1398, 273, 389, 81, 474, 14667, 24899, 455, 6527, 20, 16, 389, 455, 6527, 21, 1769, 203, 3639, 309, 261, 67, 4963, 3088, 1283, 422, 374, 13, 288, 203, 5411, 4501, 372, 24237, 273, 2361, 18, 24492, 12, 8949, 20, 18, 16411, 12, 8949, 21, 13, 2934, 1717, 12, 6236, 18605, 67, 2053, 53, 3060, 4107, 1769, 203, 5411, 4501, 372, 24237, 273, 2361, 18, 1154, 12, 8949, 20, 18, 16411, 24899, 4963, 3088, 1283, 13, 342, 389, 455, 6527, 20, 16, 3844, 21, 18, 16411, 24899, 4963, 3088, 1283, 13, 342, 389, 455, 6527, 21, 1769, 203, 3639, 289, 203, 3639, 2583, 12, 549, 372, 24237, 405, 374, 16, 296, 6187, 1359, 20, 92, 21, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 67, 6236, 6404, 8284, 203, 3639, 389, 81, 474, 12, 869, 16, 4501, 372, 24237, 1769, 203, 203, 3639, 389, 2725, 2 ]
./full_match/80001/0xEc14c01136e0E1e815C9fBf369276397d0804fc3/sources/src/protocol-lite/Lopo.sol
for foundry testing purpose
function getLoanableDetails(address _buyer, UD60x18 faceAmount, uint256 repaymentTimestamp) public view returns (uint256 repaymentDay, UD60x18 interestRateDaily, UD60x18 interestDaily, UD60x18 totalLoanableAmount) { Buyer storage buyer = buyers[_buyer]; require(buyer.owner == _buyer, "Caller is not buyer"); require(!buyer.isDisabled, "Buyer is disabled"); require(buyer.creditExpiryTimestamp > block.timestamp, "Buyer credit expired"); return _getLoanableDetails( buyer.riskPremium, buyer.creditLimit, buyer.currentTotalLoan, faceAmount, repaymentTimestamp ); }
9,493,216
[ 1, 1884, 1392, 1176, 7769, 13115, 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, 336, 1504, 304, 429, 3790, 12, 2867, 389, 70, 16213, 16, 587, 40, 4848, 92, 2643, 7945, 6275, 16, 2254, 5034, 2071, 2955, 4921, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 2071, 2955, 4245, 16, 587, 40, 4848, 92, 2643, 16513, 4727, 40, 12857, 16, 587, 40, 4848, 92, 2643, 16513, 40, 12857, 16, 587, 40, 4848, 92, 2643, 2078, 1504, 304, 429, 6275, 13, 203, 565, 288, 203, 3639, 605, 16213, 2502, 27037, 273, 30143, 414, 63, 67, 70, 16213, 15533, 203, 3639, 2583, 12, 70, 16213, 18, 8443, 422, 389, 70, 16213, 16, 315, 11095, 353, 486, 27037, 8863, 203, 3639, 2583, 12, 5, 70, 16213, 18, 291, 8853, 16, 315, 38, 16213, 353, 5673, 8863, 203, 3639, 2583, 12, 70, 16213, 18, 20688, 14633, 4921, 405, 1203, 18, 5508, 16, 315, 38, 16213, 12896, 7708, 8863, 203, 3639, 327, 389, 588, 1504, 304, 429, 3790, 12, 203, 5411, 27037, 18, 86, 10175, 23890, 5077, 16, 27037, 18, 20688, 3039, 16, 27037, 18, 2972, 5269, 1504, 304, 16, 7945, 6275, 16, 2071, 2955, 4921, 203, 3639, 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 ]
./full_match/42161/0xaDB8c61Da2C62D81D35122275F4623D02fad45fe/sources/project_/src/active/MemepadStakingV2.sol
The precision factor
uint256 private constant _PRECISION_FACTOR = 1e36;
16,299,449
[ 1, 1986, 6039, 5578, 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, 0 ]
[ 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, 0 ]
[ 1, 225, 2254, 5034, 3238, 5381, 389, 3670, 26913, 67, 26835, 273, 404, 73, 5718, 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 ]
pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; contract MogulMarketplace is ERC1155Holder, AccessControl, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; using SafeERC20 for IERC20; using SafeMath for uint256; AggregatorV3Interface priceOracle; bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); address payable public treasuryWallet; IERC20 stars; uint256 nextListingId = 0; uint256 listingFee = 0; //4 decimals address mogulNFTAddress; struct Listing { address payable seller; string label; string description; address tokenAddress; uint256 tokenId; uint256 numTokens; uint256 price; bool isStarsListing; } struct Auction { string label; address tokenAddress; uint256 tokenId; uint256 numTokens; uint256 startingStarsPrice; uint256 startingEthPrice; uint256 startTime; uint256 endTime; bool allowStarsBids; bool allowEthBids; Bid highestStarsBid; Bid highestEthBid; } struct Bid { address payable bidder; uint256 amount; } mapping(uint256 => Listing) public listings; EnumerableSet.UintSet private listingIds; mapping(uint256 => Auction) public auctions; EnumerableSet.UintSet private auctionIds; event ListingCreated( string label, string description, address tokenAddress, uint256 tokenId, uint256 numTokens, uint256 price, bool isStarsListing ); event Sale(address buyer, uint256 listingId, uint256 amount); event AuctionEnded(address winner, uint256 auctionId); event AuctionCancelled(uint256 auctionId); modifier onlyAdmin { require(hasRole(ROLE_ADMIN, msg.sender), "Sender is not admin"); _; } /** * @dev Stores the Stars contract, and allows users with the admin role to * grant/revoke the admin role from other users. Stores treasury wallet. * * Params: * starsAddress: the address of the Stars contract * _admin: address of the first admin * _treasuryWallet: address of treasury wallet */ constructor( address starsAddress, address _admin, address payable _treasuryWallet, address _mogulNFTAddress ) public ReentrancyGuard() { require( _treasuryWallet != address(0), "Treasury wallet cannot be 0 address" ); _setupRole(ROLE_ADMIN, _admin); _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); treasuryWallet = _treasuryWallet; stars = IERC20(starsAddress); mogulNFTAddress = _mogulNFTAddress; } /** * @dev Sets the price oracle for Stars/eth * * Params: * priceOracleAddress: address of oracle */ function setPriceOracle(address priceOracleAddress) external onlyAdmin { priceOracle = AggregatorV3Interface(priceOracleAddress); } /** * @dev Gets Stars/eth price * * Requirements: * Price oralce has been set */ function getStarsPrice() public view returns (uint256) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceOracle.latestRoundData(); return uint256(price); } //Allows contract to inherit both ERC1155Receiver and AccessControl function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Receiver, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } //Get number of listings function getNumListings() external view returns (uint256) { return listingIds.length(); } /** * @dev Get listing ID at index * * Params: * index: index of ID */ function getListingIds(uint256 index) external view returns (uint256) { return listingIds.at(index); } /** * @dev Get listing correlated to index * * Params: * index: index of ID */ function getListingAtIndex(uint256 index) external view returns (Listing memory) { return listings[listingIds.at(index)]; } //Get number of auctions function getNumAuctions() external view returns (uint256) { return auctionIds.length(); } /** * @dev Get auction ID at index * * Params: * index: index of ID */ function getAuctionIds(uint256 index) external view returns (uint256) { return auctionIds.at(index); } /** * @dev Get auction correlated to index * * Params: * index: index of ID */ function getAuctionAtIndex(uint256 index) external view returns (Auction memory) { return auctions[auctionIds.at(index)]; } /** * @dev Create a new listing * * Params: * label: listing label * tokenAddress: address of token to list * tokenId: id of token * numTokens: number of tokens * price: listing price * isStarsListing: whether or not the listing is sold for Stars */ function listTokens( string memory label, string memory description, address tokenAddress, uint256 tokenId, uint256 numTokens, uint256 price, bool isStarsListing ) external nonReentrant() { require( tokenAddress == mogulNFTAddress, "Only Mogul NFTs can be listed" ); IERC1155 token = IERC1155(tokenAddress); token.safeTransferFrom( msg.sender, address(this), tokenId, numTokens, "" ); uint256 listingId = generateListingId(); listings[listingId] = Listing( payable(msg.sender), label, description, tokenAddress, tokenId, numTokens, price, isStarsListing ); listingIds.add(listingId); emit ListingCreated( label, description, tokenAddress, tokenId, numTokens, price, isStarsListing ); } /** * @dev Remove a listing * * Params: * listingId: listing ID */ function removeListing(uint256 listingId) external { Listing storage listing = listings[listingId]; require( msg.sender == listing.seller || hasRole(ROLE_ADMIN, msg.sender), "Sender is not seller or admin" ); IERC1155 token = IERC1155(listing.tokenAddress); token.safeTransferFrom( address(this), treasuryWallet, listing.tokenId, listing.numTokens, "" ); listingIds.remove(listingId); } /** * @dev Buy a token * * Params: * listingId: listing ID * amount: amount tokens to buy */ function buyTokens(uint256 listingId, uint256 amount) external payable nonReentrant() { require(listingIds.contains(listingId), "Listing does not exist."); Listing storage listing = listings[listingId]; require(listing.numTokens >= amount, "Not enough tokens remaining"); uint256 fullAmount = listing.price.mul(amount); uint256 fee = fullAmount.mul(listingFee).div(10000); if (listing.isStarsListing) { if (fee > 0) { stars.safeTransferFrom(msg.sender, address(this), fee); } stars.safeTransferFrom( msg.sender, listing.seller, fullAmount.sub(fee) ); } else { require(msg.value == fullAmount, "Incorrect transaction value"); listing.seller.transfer(fullAmount.sub(fee)); } listing.numTokens -= amount; if (listing.numTokens == 0) { listingIds.remove(listingId); } IERC1155 token = IERC1155(listing.tokenAddress); token.safeTransferFrom( address(this), msg.sender, listing.tokenId, amount, "" ); emit Sale(msg.sender, listingId, amount); } /** * @dev Start an auction * * Params: * label: auction label * tokenAddress: address of token * tokenId: token ID * numTokens: number of tokens the winner will get * startingStarsPrice: starting price for Stars bids * startingEthPrice: starting mprice for eth bids * startTime: auction start time * endTime: auction end time * allowStarsBids: whether or not Stars bids are allowed * allowEthBids: whether or not Eth bids are allowed * * Requirements: * allowStarsBids or allowEthBids is true */ function startAuction( string memory label, address tokenAddress, uint256 tokenId, uint256 numTokens, uint256 startingStarsPrice, uint256 startingEthPrice, uint256 startTime, uint256 endTime, bool allowStarsBids, bool allowEthBids ) external onlyAdmin nonReentrant() { require( allowStarsBids || allowEthBids, "One of ETH bids or Stars bids must be allowed" ); IERC1155 token = IERC1155(tokenAddress); token.safeTransferFrom( msg.sender, address(this), tokenId, numTokens, "" ); uint256 auctionId = generateAuctionId(); auctions[auctionId] = Auction( label, tokenAddress, tokenId, numTokens, startingStarsPrice, startingEthPrice, startTime, endTime, allowStarsBids, allowEthBids, Bid(payable(address(msg.sender)), 0), Bid(payable(address(msg.sender)), 0) ); auctionIds.add(auctionId); } /** * @dev Send in a bid and refund the previous highest bidder * * Params: * auctionId: auction ID * isStarsBid: true if bid is in Stars, false if it's in eth * amount: amount of bid * * Requirements: * Bid is higher than the previous highest bid of the same type */ function bid( uint256 auctionId, bool isStarsBid, uint256 amount ) external payable nonReentrant() { Auction storage auction = auctions[auctionId]; require( block.timestamp >= auction.startTime && block.timestamp <= auction.endTime, "Cannot place bids at this time" ); if (isStarsBid) { require(auction.allowStarsBids, "Auction does not accept Stars"); require( amount > auction.highestStarsBid.amount && amount > auction.startingStarsPrice, "Bid is too low" ); stars.safeTransferFrom(msg.sender, address(this), amount); stars.safeTransfer( auction.highestStarsBid.bidder, auction.highestStarsBid.amount ); auction.highestStarsBid = Bid(payable(address(msg.sender)), amount); } else { require(auction.allowEthBids, "Auction does not accept ether"); require( amount > auction.highestEthBid.amount && amount > auction.startingEthPrice, "Bid is too low" ); require(amount == msg.value, "Amount does not match message value"); auction.highestEthBid.bidder.transfer(auction.highestEthBid.amount); auction.highestEthBid = Bid(payable(address(msg.sender)), amount); } } /** * @dev End auctions and reward the winner without needing a price Oracle. * The caller chooses whether the Stars bid or Ether bid was higher. * * Params: * auctionId: auction ID * didStarsBidWin: whether or not the Stars bid won * * Requirements: * Auction is over * The auction supports bids of the winning bid type */ function endAuctionWithoutOracle(uint256 auctionId, bool didStarsBidWin) external onlyAdmin nonReentrant() { require(auctionIds.contains(auctionId), "Auction does not exist"); Auction memory auction = auctions[auctionId]; require(block.timestamp >= auction.endTime, "Auction is ongoing"); address winner; if (didStarsBidWin) { require( auction.allowStarsBids, "Auction did not support Stars bids" ); winner = auction.highestStarsBid.bidder; } else { require(auction.allowEthBids, "Auction did not support Stars bids"); winner = auction.highestEthBid.bidder; } IERC1155(auction.tokenAddress).safeTransferFrom( address(this), winner, auction.tokenId, auction.numTokens, "" ); auctionIds.remove(auctionId); emit AuctionEnded(winner, auctionId); } /** * @dev End auctions and reward the winner. If the auction supported both * Stars and eth bids, uses the oracle to determine who won * * Params: * auctionId: auction ID * * Requirements: * Price oracle is set if auction supports both Stars and Eth bids */ function endAuction(uint256 auctionId) external onlyAdmin nonReentrant() { require(auctionIds.contains(auctionId), "Auction does not exist"); Auction memory auction = auctions[auctionId]; require(block.timestamp >= auction.endTime, "Auction is ongoing"); address winner; if (auction.allowEthBids && auction.allowStarsBids) { uint256 ethToStars = auction.highestEthBid.amount.mul(getStarsPrice()).div(1e8); if (ethToStars > auction.highestStarsBid.amount) { winner = auction.highestEthBid.bidder; stars.safeTransfer( auction.highestStarsBid.bidder, auction.highestStarsBid.amount ); } else { winner = auction.highestStarsBid.bidder; auction.highestEthBid.bidder.transfer( auction.highestEthBid.amount ); } } else if (auction.allowEthBids) { winner = auction.highestEthBid.bidder; } else { winner = auction.highestStarsBid.bidder; } IERC1155(auction.tokenAddress).safeTransferFrom( address(this), winner, auction.tokenId, auction.numTokens, "" ); auctionIds.remove(auctionId); emit AuctionEnded(winner, auctionId); } /** * @dev Cancel auction and refund bidders * * Params: * auctionId: auction ID */ function cancelAuction(uint256 auctionId) external onlyAdmin nonReentrant() { require(auctionIds.contains(auctionId), "Auction does not exist"); Auction memory auction = auctions[auctionId]; auction.highestEthBid.bidder.transfer(auction.highestEthBid.amount); stars.safeTransfer( auction.highestStarsBid.bidder, auction.highestStarsBid.amount ); auctionIds.remove(auctionId); emit AuctionCancelled(auctionId); } //Generate ID for next listing function generateListingId() internal returns (uint256) { return nextListingId++; } //Generate ID for next auction function generateAuctionId() internal returns (uint256) { return nextListingId++; } //Withdraw ETH to treasury wallet function withdrawETH() external onlyAdmin { require(auctionIds.length() == 0, "Auctions are ongoing"); treasuryWallet.transfer(address(this).balance); } //Withdraw Stars to treasury wallet function withdrawStars() external onlyAdmin { require(auctionIds.length() == 0, "Auctions are ongoing"); stars.safeTransfer(treasuryWallet, stars.balanceOf(address(this))); } function setMogulNFTAddress(address _mogulNFTAddress) external onlyAdmin { mogulNFTAddress = _mogulNFTAddress; } } // 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; /** * @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' // 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) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { 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 AccessControl is Context, IAccessControl, 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(IAccessControl).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()); } } } // 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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 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] = valueIndex; // Replace lastvalue's index to valueIndex // 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.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 () { _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; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // 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; /** * @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.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // 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 "./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 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) { 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; /** * @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); } }
* @dev Get listing correlated to index Params: index: index of ID/
function getListingAtIndex(uint256 index) external view returns (Listing memory) { return listings[listingIds.at(index)]; }
11,958,945
[ 1, 967, 11591, 1858, 9243, 358, 770, 8861, 30, 770, 30, 770, 434, 1599, 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 ]
[ 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, 565, 445, 10033, 310, 24499, 12, 11890, 5034, 770, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 19081, 3778, 13, 203, 565, 288, 203, 3639, 327, 666, 899, 63, 21228, 2673, 18, 270, 12, 1615, 13, 15533, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ /** *Submitted for verification at Etherscan.io on 2021-04-13 */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT 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 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)); } } /** * @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); } } } } /* * @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; } } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * 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 AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet 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 Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _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 { 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, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } /** * @notice Access Controls contract for the Digitalax Platform * @author BlockRocket.tech */ contract DigitalaxAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant VERIFIED_MINTER_ROLE = keccak256("VERIFIED_MINTER_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleGranted( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the verified minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasVerifiedMinterRole(address _address) external view returns (bool) { return hasRole(VERIFIED_MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the verified minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addVerifiedMinterRole(address _address) external { grantRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the verified minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeVerifiedMinterRole(address _address) external { revokeRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } } interface IStateSender { function syncState(address receiver, bytes calldata data) external; } library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } abstract contract BaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; DigitalaxAccessControls public accessControls; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IStateSender public stateSender; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public childTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(DigitalaxAccessControls _accessControls, address _stateSender) public { // _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // _setupContractId("RootTunnel"); accessControls = _accessControls; stateSender = IStateSender(_stateSender); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setStateSender: Sender must have the admin role" ); stateSender = IStateSender(newStateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setCheckpointManager: Sender must have the admin role" ); checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Set the child chain tunnel, callable only by admins * @dev This should be the contract responsible to receive data bytes on child chain * @param newChildTunnel address of child tunnel contract */ function setChildTunnel(address newChildTunnel) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setChildTunnel: Sender must have the admin role" ); require(newChildTunnel != address(0x0), "RootTunnel: INVALID_CHILD_TUNNEL_ADDRESS"); childTunnel = newChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { stateSender.syncState(childTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "RootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); // check child tunnel require(childTunnel == RLPReader.toAddress(logRLPList[0]), "RootTunnel: INVALID_CHILD_TUNNEL"); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "RootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory receivedData = logRLPList[2].toBytes(); (bytes memory message) = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) virtual internal; } /** * @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 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 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); } /** * @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 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; } } /** * @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. */ /** * @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)))); } } /** * @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); } } /** * @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 { } } /** * _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); } /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } /** * @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; } /** * @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); } // Contract based from the following: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155.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._ * * @notice Modifications to uri logic made by BlockRocket.tech */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; 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; // Token ID to its URI mapping (uint256 => string) internal tokenUris; // Token ID to its total supply mapping(uint256 => uint256) public tokenTotalSupply; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; constructor () public { // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. */ function uri(uint256 tokenId) external view override returns (string memory) { return tokenUris[tokenId]; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view 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 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) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external 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 override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for a given token ID */ function _setURI(uint256 tokenId, string memory newuri) internal virtual { tokenUris[tokenId] = newuri; emit URI(newuri, tokenId); } /** * @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 `to` 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] = _balances[id][account].add(amount); tokenTotalSupply[id] = tokenTotalSupply[id].add(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 (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][to] = amount.add(_balances[id][to]); tokenTotalSupply[id] = tokenTotalSupply[id].add(amount); } 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), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(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 (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(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(to).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(to).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; } } // Based on: https://github.com/rocksideio/ERC998-ERC1155-TopDown/blob/695963195606304374015c49d166ab2fbeb42ea9/contracts/IERC998ERC1155TopDown.sol interface IERC998ERC1155TopDown is IERC1155Receiver { event ReceivedChild(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount); event TransferBatchChild(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts); function childContractsFor(uint256 tokenId) external view returns (address[] memory childContracts); function childIdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds); function childBalance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns (uint256); } /** * @notice Mock child tunnel contract to receive and send message from L2 */ abstract contract BaseChildTunnel { modifier onlyStateSyncer() { require( msg.sender == 0x0000000000000000000000000000000000001001, "Child tunnel: caller is not the state syncer" ); _; } // MessageTunnel on L1 will get data from this event event MessageSent(bytes message); /** * @notice Receive state sync from matic contracts * @dev This method will be called by Matic chain internally. * This is executed without transaction using a system call. */ function onStateReceive(uint256, bytes memory message) public onlyStateSyncer{ _processMessageFromRoot(message); } /** * @notice Emit message that can be received on Root Tunnel * @dev Call the internal function when need to emit message * @param message bytes message that will be sent to Root Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToRoot(bytes memory message) internal { emit MessageSent(message); } /** * @notice Process message received from Root Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Root Tunnel */ function _processMessageFromRoot(bytes memory message) virtual internal; } /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function msgSender() internal virtual view returns (address payable); function versionRecipient() external virtual view returns (string memory); } /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder"); _; } function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function msgSender() internal override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } } /** * @title Digitalax Garment NFT a.k.a. parent NFTs * @dev Issues ERC-721 tokens as well as being able to hold child 1155 tokens */ contract DigitalaxGarmentNFT is ERC721("DigitalaxNFT", "DTX"), ERC1155Receiver, IERC998ERC1155TopDown, BaseChildTunnel, BaseRelayRecipient { // @notice event emitted upon construction of this contract, used to bootstrap external indexers event DigitalaxGarmentNFTContractDeployed(); // @notice event emitted when token URI is updated event DigitalaxGarmentTokenUriUpdate( uint256 indexed _tokenId, string _tokenUri ); // @notice event emitted when a tokens primary sale occurs event TokenPrimarySalePriceSet( uint256 indexed _tokenId, uint256 _salePrice ); event WithdrawnBatch( address indexed user, uint256[] tokenIds ); /// @dev Child ERC1155 contract address ERC1155 public childContract; /// @dev current max tokenId uint256 public tokenIdPointer; /// @dev TokenID -> Designer address mapping(uint256 => address) public garmentDesigners; /// @dev TokenID -> Primary Ether Sale Price in Wei mapping(uint256 => uint256) public primarySalePrice; /// @dev ERC721 Token ID -> ERC1155 ID -> Balance mapping(uint256 => mapping(uint256 => uint256)) private balances; /// @dev ERC1155 ID -> ERC721 Token IDs that have a balance mapping(uint256 => EnumerableSet.UintSet) private childToParentMapping; /// @dev ERC721 Token ID -> ERC1155 child IDs owned by the token ID mapping(uint256 => EnumerableSet.UintSet) private parentToChildMapping; /// @dev max children NFTs a single 721 can hold uint256 public maxChildrenPerToken = 10; /// @dev limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; mapping (uint256 => bool) public withdrawnTokens; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } /// Required to govern who can call certain functions DigitalaxAccessControls public accessControls; /** @param _accessControls Address of the Digitalax access control contract @param _childContract ERC1155 the Digitalax child NFT contract 0xb5505a6d998549090530911180f38aC5130101c6 */ constructor(DigitalaxAccessControls _accessControls, ERC1155 _childContract, address _childChain, address _trustedForwarder) public { accessControls = _accessControls; childContract = _childContract; childChain = _childChain; trustedForwarder = _trustedForwarder; emit DigitalaxGarmentNFTContractDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /** @notice Mints a DigitalaxGarmentNFT AND when minting to a contract checks if the beneficiary is a 721 compatible @dev Only senders with either the minter or smart contract role can invoke this method @param _beneficiary Recipient of the NFT @param _tokenUri URI for the token being minted @param _designer Garment designer - will be required for issuing royalties from secondary sales @return uint256 The token ID of the token that was minted */ function mint(address _beneficiary, string calldata _tokenUri, address _designer) external returns (uint256) { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasMinterRole(_msgSender()), "DigitalaxGarmentNFT.mint: Sender must have the minter or contract role" ); // Valid args _assertMintingParamsValid(_tokenUri, _designer); tokenIdPointer = tokenIdPointer.add(1); uint256 tokenId = tokenIdPointer; // MATIC guard, to catch tokens minted on chain require(!withdrawnTokens[tokenId], "ChildMintableERC721: TOKEN_EXISTS_ON_ROOT_CHAIN"); // Mint token and set token URI _safeMint(_beneficiary, tokenId); _setTokenURI(tokenId, _tokenUri); // Associate garment designer garmentDesigners[tokenId] = _designer; return tokenId; } /** @notice Burns a DigitalaxGarmentNFT, releasing any composed 1155 tokens held by the token itself @dev Only the owner or an approved sender can call this method @param _tokenId the token ID to burn */ function burn(uint256 _tokenId) public { address operator = _msgSender(); require( ownerOf(_tokenId) == operator || isApproved(_tokenId, operator), "DigitalaxGarmentNFT.burn: Only garment owner or approved" ); // If there are any children tokens then send them as part of the burn if (parentToChildMapping[_tokenId].length() > 0) { // Transfer children to the burner _extractAndTransferChildrenFromParent(_tokenId, _msgSender()); } // Destroy token mappings _burn(_tokenId); // Clean up designer mapping delete garmentDesigners[_tokenId]; delete primarySalePrice[_tokenId]; } /** @notice Single ERC1155 receiver callback hook, used to enforce children token binding to a given parent token */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); _receiveChild(_receiverTokenId, _msgSender(), _id, _amount); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _id, _amount); // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155Received.selector; } /** @notice Batch ERC1155 receiver callback hook, used to enforce child token bindings to a given parent token ID */ function onERC1155BatchReceived(address _operator, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); // Note: be mindful of GAS limits for (uint256 i = 0; i < _ids.length; i++) { _receiveChild(_receiverTokenId, _msgSender(), _ids[i], _values[i]); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _ids[i], _values[i]); } // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155BatchReceived.selector; } function _extractIncomingTokenId() internal pure returns (uint256) { // Extract out the embedded token ID from the sender uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} return _receiverTokenId; } function _validateReceiverParams(uint256 _receiverTokenId, address _operator, address _from) internal view { require(_exists(_receiverTokenId), "Token does not exist"); // We only accept children from the Digitalax child contract require(_msgSender() == address(childContract), "Invalid child token contract"); // check the sender is the owner of the token or its just been birthed to this token if (_from != address(0)) { require( ownerOf(_receiverTokenId) == _from, "Cannot add children to tokens you dont own" ); // Check the operator is also the owner, preventing an approved address adding tokens on the holders behalf require(_operator == _from, "Operator is not owner"); } } ////////// // Admin / ////////// /** @notice Updates the token URI of a given token @dev Only admin or smart contract @param _tokenId The ID of the token being updated @param _tokenUri The new URI */ function setTokenURI(uint256 _tokenId, string calldata _tokenUri) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTokenURI: Sender must be an authorised contract or admin" ); _setTokenURI(_tokenId, _tokenUri); emit DigitalaxGarmentTokenUriUpdate(_tokenId, _tokenUri); } /** @notice Records the Ether price that a given token was sold for (in WEI) @dev Only admin or a smart contract can call this method @param _tokenId The ID of the token being updated @param _salePrice The primary Ether sale price in WEI */ function setPrimarySalePrice(uint256 _tokenId, uint256 _salePrice) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setPrimarySalePrice: Sender must be an authorised contract or admin" ); require(_exists(_tokenId), "DigitalaxGarmentNFT.setPrimarySalePrice: Token does not exist"); require(_salePrice > 0, "DigitalaxGarmentNFT.setPrimarySalePrice: Invalid sale price"); // Only set it once if (primarySalePrice[_tokenId] == 0) { primarySalePrice[_tokenId] = _salePrice; emit TokenPrimarySalePriceSet(_tokenId, _salePrice); } } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateAccessControls: Sender must be admin"); accessControls = _accessControls; } /** @notice Method for updating max children a token can hold @dev Only admin @param _maxChildrenPerToken uint256 the max children a token can hold */ function updateMaxChildrenPerToken(uint256 _maxChildrenPerToken) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateMaxChildrenPerToken: Sender must be admin"); maxChildrenPerToken = _maxChildrenPerToken; } ///////////////// // View Methods / ///////////////// /** @notice View method for checking whether a token has been minted @param _tokenId ID of the token being checked */ function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /** @dev Get the child token balances held by the contract, assumes caller knows the correct child contract */ function childBalance(uint256 _tokenId, address _childContract, uint256 _childTokenId) public view override returns (uint256) { return _childContract == address(childContract) ? balances[_tokenId][_childTokenId] : 0; } /** @dev Get list of supported child contracts, always a list of 0 or 1 in our case */ function childContractsFor(uint256 _tokenId) override external view returns (address[] memory) { if (!_exists(_tokenId)) { return new address[](0); } address[] memory childContracts = new address[](1); childContracts[0] = address(childContract); return childContracts; } /** @dev Gets mapped IDs for child tokens */ function childIdsForOn(uint256 _tokenId, address _childContract) override public view returns (uint256[] memory) { if (!_exists(_tokenId) || _childContract != address(childContract)) { return new uint256[](0); } uint256[] memory childTokenIds = new uint256[](parentToChildMapping[_tokenId].length()); for (uint256 i = 0; i < parentToChildMapping[_tokenId].length(); i++) { childTokenIds[i] = parentToChildMapping[_tokenId].at(i); } return childTokenIds; } /** @dev Get total number of children mapped to the token */ function totalChildrenMapped(uint256 _tokenId) external view returns (uint256) { return parentToChildMapping[_tokenId].length(); } /** * @dev checks the given token ID is approved either for all or the single token ID */ function isApproved(uint256 _tokenId, address _operator) public view returns (bool) { return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator; } ///////////////////////// // Internal and Private / ///////////////////////// function _extractAndTransferChildrenFromParent(uint256 _fromTokenId, address _to) internal { uint256[] memory _childTokenIds = childIdsForOn(_fromTokenId, address(childContract)); uint256[] memory _amounts = new uint256[](_childTokenIds.length); for (uint256 i = 0; i < _childTokenIds.length; ++i) { uint256 _childTokenId = _childTokenIds[i]; uint256 amount = childBalance(_fromTokenId, address(childContract), _childTokenId); _amounts[i] = amount; _removeChild(_fromTokenId, address(childContract), _childTokenId, amount); } childContract.safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, abi.encodePacked("")); emit TransferBatchChild(_fromTokenId, _to, address(childContract), _childTokenIds, _amounts); } function _receiveChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { if (balances[_tokenId][_childTokenId] == 0) { parentToChildMapping[_tokenId].add(_childTokenId); } balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].add(_amount); } function _removeChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { require(_amount != 0 || balances[_tokenId][_childTokenId] >= _amount, "ERC998: insufficient child balance for transfer"); balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].sub(_amount); if (balances[_tokenId][_childTokenId] == 0) { childToParentMapping[_childTokenId].remove(_tokenId); parentToChildMapping[_tokenId].remove(_childTokenId); } } /** @notice Checks that the URI is not empty and the designer is a real address @param _tokenUri URI supplied on minting @param _designer Address supplied on minting */ function _assertMintingParamsValid(string calldata _tokenUri, address _designer) pure internal { require(bytes(_tokenUri).length > 0, "DigitalaxGarmentNFT._assertMintingParamsValid: Token URI is empty"); require(_designer != address(0), "DigitalaxGarmentNFT._assertMintingParamsValid: Designer is zero address"); } /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokenId for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded tokenId */ function deposit(address user, bytes calldata depositData) external onlyChildChain { // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); withdrawnTokens[tokenId] = false; _safeMint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { withdrawnTokens[tokenIds[i]] = false; _safeMint(user, tokenIds[i]); } } } /** * @notice called when user wants to withdraw token back to root chain * @dev Should burn user's token. This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdraw(uint256 tokenId) external { withdrawnTokens[tokenId] = true; burn(tokenId); } /** * @notice called when user wants to withdraw multiple tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds tokenId list to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT"); for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; withdrawnTokens[tokenIds[i]] = true; burn(tokenId); } emit WithdrawnBatch(_msgSender(), tokenIds); } function _processMessageFromRoot(bytes memory message) internal override { uint256 _tokenId; uint256 _primarySalePrice; address _garmentDesigner; string memory _tokenUri; uint256[] memory _children; uint256[] memory _childrenBalances; (_tokenId, _primarySalePrice, _garmentDesigner, _tokenUri, _children, _childrenBalances) = abi.decode(message, (uint256, uint256, address, string, uint256[], uint256[])); // With the information above, rebuild the 721 token in matic! primarySalePrice[_tokenId] = _primarySalePrice; garmentDesigners[_tokenId] = _garmentDesigner; _setTokenURI(_tokenId, _tokenUri); for (uint256 i = 0; i< _children.length; i++) { _receiveChild(_tokenId, _msgSender(), _children[i], _childrenBalances[i]); } } // Send the nft to root - if it does not exist then we can handle it on that side function sendNFTToRoot(uint256 tokenId) external { uint256 _primarySalePrice = primarySalePrice[tokenId]; address _garmentDesigner= garmentDesigners[tokenId]; string memory _tokenUri = tokenURI(tokenId); uint256[] memory _children = childIdsForOn(tokenId, address(childContract)); uint256 len = _children.length; uint256[] memory childBalances = new uint256[](len); for( uint256 i; i< _children.length; i++){ childBalances[i] = childBalance(tokenId, address(childContract), _children[i]); } _sendMessageToRoot(abi.encode(tokenId, ownerOf(tokenId), _primarySalePrice, _garmentDesigner, _tokenUri, _children, childBalances)); } } //imported from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155Burnable.sol /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 amount) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, amount); } function burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, amounts); } } /** * @title Digitalax Materials NFT a.k.a. child NFTs * @dev Issues ERC-1155 tokens which can be held by the parent ERC-721 contract */ contract DigitalaxMaterials is ERC1155Burnable, BaseRelayRecipient { // @notice event emitted on contract creation event DigitalaxMaterialsDeployed(); // @notice a single child has been created event ChildCreated( uint256 indexed childId ); // @notice a batch of children have been created event ChildrenCreated( uint256[] childIds ); string public name; string public symbol; // @notice current token ID pointer uint256 public tokenIdPointer; // @notice enforcing access controls DigitalaxAccessControls public accessControls; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } constructor( string memory _name, string memory _symbol, DigitalaxAccessControls _accessControls, address _childChain, address _trustedForwarder ) public { name = _name; symbol = _symbol; accessControls = _accessControls; trustedForwarder = _trustedForwarder; childChain = _childChain; emit DigitalaxMaterialsDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /////////////////////////// // Creating new children // /////////////////////////// /** @notice Creates a single child ERC1155 token @dev Only callable with smart contact role @return id the generated child Token ID */ function createChild(string calldata _uri) external returns (uint256 id) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.createChild: Sender must be smart contract" ); require(bytes(_uri).length > 0, "DigitalaxMaterials.createChild: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); id = tokenIdPointer; _setURI(id, _uri); emit ChildCreated(id); } /** @notice Creates a batch of child ERC1155 tokens @dev Only callable with smart contact role @return tokenIds the generated child Token IDs */ function batchCreateChildren(string[] calldata _uris) external returns (uint256[] memory tokenIds) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchCreateChildren: Sender must be smart contract" ); require(_uris.length > 0, "DigitalaxMaterials.batchCreateChildren: No data supplied in array"); uint256 urisLength = _uris.length; tokenIds = new uint256[](urisLength); for (uint256 i = 0; i < urisLength; i++) { string memory uri = _uris[i]; require(bytes(uri).length > 0, "DigitalaxMaterials.batchCreateChildren: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); _setURI(tokenIdPointer, uri); tokenIds[i] = tokenIdPointer; } // Batched event for GAS savings emit ChildrenCreated(tokenIds); } ////////////////////////////////// // Minting of existing children // ////////////////////////////////// /** @notice Mints a single child ERC1155 tokens, increasing its supply by the _amount specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function mintChild(uint256 _childTokenId, uint256 _amount, address _beneficiary, bytes calldata _data) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.mintChild: Sender must be smart contract" ); require(bytes(tokenUris[_childTokenId]).length > 0, "DigitalaxMaterials.mintChild: Strand does not exist"); require(_amount > 0, "DigitalaxMaterials.mintChild: No amount specified"); _mint(_beneficiary, _childTokenId, _amount, _data); } /** @notice Mints a batch of child ERC1155 tokens, increasing its supply by the _amounts specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function batchMintChildren( uint256[] calldata _childTokenIds, uint256[] calldata _amounts, address _beneficiary, bytes calldata _data ) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchMintChildren: Sender must be smart contract" ); require(_childTokenIds.length == _amounts.length, "DigitalaxMaterials.batchMintChildren: Array lengths are invalid"); require(_childTokenIds.length > 0, "DigitalaxMaterials.batchMintChildren: No data supplied in arrays"); // Check the strands exist and no zero amounts for (uint256 i = 0; i < _childTokenIds.length; i++) { uint256 strandId = _childTokenIds[i]; require(bytes(tokenUris[strandId]).length > 0, "DigitalaxMaterials.batchMintChildren: Strand does not exist"); uint256 amount = _amounts[i]; require(amount > 0, "DigitalaxMaterials.batchMintChildren: Invalid amount"); } _mintBatch(_beneficiary, _childTokenIds, _amounts, _data); } function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.updateAccessControls: Sender must be admin" ); require( address(_accessControls) != address(0), "DigitalaxMaterials.updateAccessControls: New access controls cannot be ZERO address" ); accessControls = _accessControls; } /** * @notice called when tokens are deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokens for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded ids array and amounts array */ function deposit(address user, bytes calldata depositData) external onlyChildChain { ( uint256[] memory ids, uint256[] memory amounts, bytes memory data ) = abi.decode(depositData, (uint256[], uint256[], bytes)); require(user != address(0x0), "DigitalaxMaterials: INVALID_DEPOSIT_USER"); _mintBatch(user, ids, amounts, data); } /** * @notice called when user wants to withdraw single token back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param id id to withdraw * @param amount amount to withdraw */ function withdrawSingle(uint256 id, uint256 amount) external { _burn(_msgSender(), id, amount); } /** * @notice called when user wants to batch withdraw tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param ids ids to withdraw * @param amounts amounts to withdraw */ function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts) external { _burnBatch(_msgSender(), ids, amounts); } } contract DigitalaxRootTunnel is BaseRootTunnel { DigitalaxGarmentNFT public nft; DigitalaxMaterials public materials; /** @param _accessControls Address of the Digitalax access control contract */ constructor(DigitalaxAccessControls _accessControls, DigitalaxGarmentNFT _nft, DigitalaxMaterials _materials, address _stateSender) BaseRootTunnel(_accessControls, _stateSender) public { nft = _nft; materials = _materials; } function _processMessageFromChild(bytes memory message) internal override { address[] memory _owners; uint256[] memory _tokenIds; uint256[] memory _primarySalePrices; address[] memory _garmentDesigners; string[] memory _tokenUris; uint256[][] memory _children; string[][] memory _childrenURIs; uint256[][] memory _childrenBalances; ( _tokenIds, _owners, _primarySalePrices, _garmentDesigners, _tokenUris, _children, _childrenURIs, _childrenBalances) = abi.decode(message, (uint256[], address[], uint256[], address[], string[], uint256[][], string[][], uint256[][])); for( uint256 i; i< _tokenIds.length; i++){ // With the information above, rebuild the 721 token on mainnet if(!nft.exists(_tokenIds[i])){ uint256 newTokenId = nft.mint(_owners[i], _tokenUris[i], _garmentDesigners[i]); if(_primarySalePrices[i] > 0) { nft.setPrimarySalePrice(newTokenId, _primarySalePrices[i]); } if(_children[i].length > 0){ for( uint256 j; j< _children[i].length; j++){ uint256 newChildId = materials.createChild(_childrenURIs[i][j]); materials.mintChild(newChildId, _childrenBalances[i][j], address(nft), abi.encodePacked(newTokenId)); } } } } } // Send the nft to matic uint256[][] childNftIdArray; string[][] childNftURIArray; uint256[][] childNftBalanceArray; // For children nfts, these should be setup on the matic network before the 721 if there are any // This should be done before doing a classic matic deposit, that is why anyone can call it for now function transferNFTsDataToMatic(uint256[] memory _tokenIds) external { uint256 length = _tokenIds.length; uint256[] memory _salePrices = new uint256[](length); address[] memory _designers = new address[](length); string[] memory _tokenUris = new string[](length); for( uint256 i; i< _tokenIds.length; i++){ _salePrices[i] = nft.primarySalePrice(_tokenIds[i]); _designers[i] = nft.garmentDesigners(_tokenIds[i]); _tokenUris[i] = nft.tokenURI(_tokenIds[i]); } _sendMessageToChild(abi.encode(_tokenIds, _salePrices, _designers, _tokenUris)); } }
* @notice Used to check whether an address has the minter role @param _address EOA or contract being checked @return bool True if the account has the role or false if it does not/
function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); }
520,279
[ 1, 6668, 358, 866, 2856, 392, 1758, 711, 326, 1131, 387, 2478, 225, 389, 2867, 512, 28202, 578, 6835, 3832, 5950, 327, 1426, 1053, 309, 326, 2236, 711, 326, 2478, 578, 629, 309, 518, 1552, 486, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 711, 49, 2761, 2996, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 6236, 2560, 67, 16256, 16, 389, 2867, 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 ]
./full_match/5/0x62DD4D016481d1969bE6095f43597eC47E3d2fb5/sources/contracts/L1/deployment/AddressDictator.sol
* Transfers ownership of this contract to the finalOwner. Only callable by the Final Owner, which is intended to be our multisig. This function shouldn't be necessary, but it gives a sense of reassurance that we can recover if something really surprising goes wrong./
function returnOwnership() external { require(msg.sender == finalOwner, "AddressDictator: only callable by finalOwner"); manager.transferOwnership(finalOwner); }
1,888,320
[ 1, 1429, 18881, 23178, 434, 333, 6835, 358, 326, 727, 5541, 18, 5098, 4140, 635, 326, 16269, 16837, 16, 1492, 353, 12613, 358, 506, 3134, 22945, 360, 18, 1220, 445, 12044, 1404, 506, 4573, 16, 1496, 518, 14758, 279, 12764, 434, 283, 428, 295, 1359, 716, 732, 848, 5910, 309, 5943, 8654, 5056, 683, 13734, 13998, 7194, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 327, 5460, 12565, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 727, 5541, 16, 315, 1887, 5014, 639, 30, 1338, 4140, 635, 727, 5541, 8863, 203, 3639, 3301, 18, 13866, 5460, 12565, 12, 6385, 5541, 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 ]
./full_match/1/0xaCC970deDc4b7720a1255Da0aC5a7A5f115Aa218/sources/Cheemishinu.sol
manually converts contract token to LP and staking BNB
function TeamCreateLPandBNB() public onlyOwner{ _swapContractToken(); }
16,482,676
[ 1, 4728, 3452, 7759, 6835, 1147, 358, 511, 52, 471, 384, 6159, 605, 20626, 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, 10434, 1684, 14461, 464, 15388, 38, 1435, 1071, 1338, 5541, 95, 203, 565, 389, 22270, 8924, 1345, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xC511FFbdB30D05e3801A14bD2a5E51dfd386D2a6/sources/arb.sol
sets uniswap approval for new token
function addToken(address _newToken) external onlyOwner { IERC20(_newToken).safeApprove(address(router), MAX_INT); }
8,343,718
[ 1, 4424, 640, 291, 91, 438, 23556, 364, 394, 1147, 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, 527, 1345, 12, 2867, 389, 2704, 1345, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 654, 39, 3462, 24899, 2704, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 10717, 3631, 4552, 67, 3217, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.4.9 <0.9.0; library HederaResponseCodes { // response codes int32 public constant OK = 0; // The transaction passed the precheck validations. int32 public constant INVALID_TRANSACTION = 1; // For any error not handled by specific error codes listed below. int32 public constant PAYER_ACCOUNT_NOT_FOUND = 2; //Payer account does not exist. int32 public constant INVALID_NODE_ACCOUNT = 3; //Node Account provided does not match the node account of the node the transaction was submitted to. int32 public constant TRANSACTION_EXPIRED = 4; // Pre-Check error when TransactionValidStart + transactionValidDuration is less than current consensus time. int32 public constant INVALID_TRANSACTION_START = 5; // Transaction start time is greater than current consensus time int32 public constant INVALID_TRANSACTION_DURATION = 6; //valid transaction duration is a positive non zero number that does not exceed 120 seconds int32 public constant INVALID_SIGNATURE = 7; // The transaction signature is not valid int32 public constant MEMO_TOO_LONG = 8; //Transaction memo size exceeded 100 bytes int32 public constant INSUFFICIENT_TX_FEE = 9; // The fee provided in the transaction is insufficient for this type of transaction int32 public constant INSUFFICIENT_PAYER_BALANCE = 10; // The payer account has insufficient cryptocurrency to pay the transaction fee int32 public constant DUPLICATE_TRANSACTION = 11; // This transaction ID is a duplicate of one that was submitted to this node or reached consensus in the last 180 seconds (receipt period) int32 public constant BUSY = 12; //If API is throttled out int32 public constant NOT_SUPPORTED = 13; //The API is not currently supported int32 public constant INVALID_FILE_ID = 14; //The file id is invalid or does not exist int32 public constant INVALID_ACCOUNT_ID = 15; //The account id is invalid or does not exist int32 public constant INVALID_CONTRACT_ID = 16; //The contract id is invalid or does not exist int32 public constant INVALID_TRANSACTION_ID = 17; //Transaction id is not valid int32 public constant RECEIPT_NOT_FOUND = 18; //Receipt for given transaction id does not exist int32 public constant RECORD_NOT_FOUND = 19; //Record for given transaction id does not exist int32 public constant INVALID_SOLIDITY_ID = 20; //The solidity id is invalid or entity with this solidity id does not exist int32 public constant UNKNOWN = 21; // The responding node has submitted the transaction to the network. Its final status is still unknown. int32 public constant SUCCESS = 22; // The transaction succeeded int32 public constant FAIL_INVALID = 23; // There was a system error and the transaction failed because of invalid request parameters. int32 public constant FAIL_FEE = 24; // There was a system error while performing fee calculation, reserved for future. int32 public constant FAIL_BALANCE = 25; // There was a system error while performing balance checks, reserved for future. int32 public constant KEY_REQUIRED = 26; //Key not provided in the transaction body int32 public constant BAD_ENCODING = 27; //Unsupported algorithm/encoding used for keys in the transaction int32 public constant INSUFFICIENT_ACCOUNT_BALANCE = 28; //When the account balance is not sufficient for the transfer int32 public constant INVALID_SOLIDITY_ADDRESS = 29; //During an update transaction when the system is not able to find the Users Solidity address int32 public constant INSUFFICIENT_GAS = 30; //Not enough gas was supplied to execute transaction int32 public constant CONTRACT_SIZE_LIMIT_EXCEEDED = 31; //contract byte code size is over the limit int32 public constant LOCAL_CALL_MODIFICATION_EXCEPTION = 32; //local execution (query) is requested for a function which changes state int32 public constant CONTRACT_REVERT_EXECUTED = 33; //Contract REVERT OPCODE executed int32 public constant CONTRACT_EXECUTION_EXCEPTION = 34; //For any contract execution related error not handled by specific error codes listed above. int32 public constant INVALID_RECEIVING_NODE_ACCOUNT = 35; //In Query validation, account with +ve(amount) value should be Receiving node account, the receiver account should be only one account in the list int32 public constant MISSING_QUERY_HEADER = 36; // Header is missing in Query request int32 public constant ACCOUNT_UPDATE_FAILED = 37; // The update of the account failed int32 public constant INVALID_KEY_ENCODING = 38; // Provided key encoding was not supported by the system int32 public constant NULL_SOLIDITY_ADDRESS = 39; // null solidity address int32 public constant CONTRACT_UPDATE_FAILED = 40; // update of the contract failed int32 public constant INVALID_QUERY_HEADER = 41; // the query header is invalid int32 public constant INVALID_FEE_SUBMITTED = 42; // Invalid fee submitted int32 public constant INVALID_PAYER_SIGNATURE = 43; // Payer signature is invalid int32 public constant KEY_NOT_PROVIDED = 44; // The keys were not provided in the request. int32 public constant INVALID_EXPIRATION_TIME = 45; // Expiration time provided in the transaction was invalid. int32 public constant NO_WACL_KEY = 46; //WriteAccess Control Keys are not provided for the file int32 public constant FILE_CONTENT_EMPTY = 47; //The contents of file are provided as empty. int32 public constant INVALID_ACCOUNT_AMOUNTS = 48; // The crypto transfer credit and debit do not sum equal to 0 int32 public constant EMPTY_TRANSACTION_BODY = 49; // Transaction body provided is empty int32 public constant INVALID_TRANSACTION_BODY = 50; // Invalid transaction body provided int32 public constant INVALID_SIGNATURE_TYPE_MISMATCHING_KEY = 51; // the type of key (base ed25519 key, KeyList, or ThresholdKey) does not match the type of signature (base ed25519 signature, SignatureList, or ThresholdKeySignature) int32 public constant INVALID_SIGNATURE_COUNT_MISMATCHING_KEY = 52; // the number of key (KeyList, or ThresholdKey) does not match that of signature (SignatureList, or ThresholdKeySignature). e.g. if a keyList has 3 base keys, then the corresponding signatureList should also have 3 base signatures. int32 public constant EMPTY_LIVE_HASH_BODY = 53; // the livehash body is empty int32 public constant EMPTY_LIVE_HASH = 54; // the livehash data is missing int32 public constant EMPTY_LIVE_HASH_KEYS = 55; // the keys for a livehash are missing int32 public constant INVALID_LIVE_HASH_SIZE = 56; // the livehash data is not the output of a SHA-384 digest int32 public constant EMPTY_QUERY_BODY = 57; // the query body is empty int32 public constant EMPTY_LIVE_HASH_QUERY = 58; // the crypto livehash query is empty int32 public constant LIVE_HASH_NOT_FOUND = 59; // the livehash is not present int32 public constant ACCOUNT_ID_DOES_NOT_EXIST = 60; // the account id passed has not yet been created. int32 public constant LIVE_HASH_ALREADY_EXISTS = 61; // the livehash already exists for a given account int32 public constant INVALID_FILE_WACL = 62; // File WACL keys are invalid int32 public constant SERIALIZATION_FAILED = 63; // Serialization failure int32 public constant TRANSACTION_OVERSIZE = 64; // The size of the Transaction is greater than transactionMaxBytes int32 public constant TRANSACTION_TOO_MANY_LAYERS = 65; // The Transaction has more than 50 levels int32 public constant CONTRACT_DELETED = 66; //Contract is marked as deleted int32 public constant PLATFORM_NOT_ACTIVE = 67; // the platform node is either disconnected or lagging behind. int32 public constant KEY_PREFIX_MISMATCH = 68; // one public key matches more than one prefixes on the signature map int32 public constant PLATFORM_TRANSACTION_NOT_CREATED = 69; // transaction not created by platform due to large backlog int32 public constant INVALID_RENEWAL_PERIOD = 70; // auto renewal period is not a positive number of seconds int32 public constant INVALID_PAYER_ACCOUNT_ID = 71; // the response code when a smart contract id is passed for a crypto API request int32 public constant ACCOUNT_DELETED = 72; // the account has been marked as deleted int32 public constant FILE_DELETED = 73; // the file has been marked as deleted int32 public constant ACCOUNT_REPEATED_IN_ACCOUNT_AMOUNTS = 74; // same accounts repeated in the transfer account list int32 public constant SETTING_NEGATIVE_ACCOUNT_BALANCE = 75; // attempting to set negative balance value for crypto account int32 public constant OBTAINER_REQUIRED = 76; // when deleting smart contract that has crypto balance either transfer account or transfer smart contract is required int32 public constant OBTAINER_SAME_CONTRACT_ID = 77; //when deleting smart contract that has crypto balance you can not use the same contract id as transferContractId as the one being deleted int32 public constant OBTAINER_DOES_NOT_EXIST = 78; //transferAccountId or transferContractId specified for contract delete does not exist int32 public constant MODIFYING_IMMUTABLE_CONTRACT = 79; //attempting to modify (update or delete a immutable smart contract, i.e. one created without a admin key) int32 public constant FILE_SYSTEM_EXCEPTION = 80; //Unexpected exception thrown by file system functions int32 public constant AUTORENEW_DURATION_NOT_IN_RANGE = 81; // the duration is not a subset of [MINIMUM_AUTORENEW_DURATION,MAXIMUM_AUTORENEW_DURATION] int32 public constant ERROR_DECODING_BYTESTRING = 82; // Decoding the smart contract binary to a byte array failed. Check that the input is a valid hex string. int32 public constant CONTRACT_FILE_EMPTY = 83; // File to create a smart contract was of length zero int32 public constant CONTRACT_BYTECODE_EMPTY = 84; // Bytecode for smart contract is of length zero int32 public constant INVALID_INITIAL_BALANCE = 85; // Attempt to set negative initial balance int32 public constant INVALID_RECEIVE_RECORD_THRESHOLD = 86; // [Deprecated]. attempt to set negative receive record threshold int32 public constant INVALID_SEND_RECORD_THRESHOLD = 87; // [Deprecated]. attempt to set negative send record threshold int32 public constant ACCOUNT_IS_NOT_GENESIS_ACCOUNT = 88; // Special Account Operations should be performed by only Genesis account, return this code if it is not Genesis Account int32 public constant PAYER_ACCOUNT_UNAUTHORIZED = 89; // The fee payer account doesn't have permission to submit such Transaction int32 public constant INVALID_FREEZE_TRANSACTION_BODY = 90; // FreezeTransactionBody is invalid int32 public constant FREEZE_TRANSACTION_BODY_NOT_FOUND = 91; // FreezeTransactionBody does not exist int32 public constant TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 92; //Exceeded the number of accounts (both from and to) allowed for crypto transfer list int32 public constant RESULT_SIZE_LIMIT_EXCEEDED = 93; // Smart contract result size greater than specified maxResultSize int32 public constant NOT_SPECIAL_ACCOUNT = 94; //The payer account is not a special account(account 0.0.55) int32 public constant CONTRACT_NEGATIVE_GAS = 95; // Negative gas was offered in smart contract call int32 public constant CONTRACT_NEGATIVE_VALUE = 96; // Negative value / initial balance was specified in a smart contract call / create int32 public constant INVALID_FEE_FILE = 97; // Failed to update fee file int32 public constant INVALID_EXCHANGE_RATE_FILE = 98; // Failed to update exchange rate file int32 public constant INSUFFICIENT_LOCAL_CALL_GAS = 99; // Payment tendered for contract local call cannot cover both the fee and the gas int32 public constant ENTITY_NOT_ALLOWED_TO_DELETE = 100; // Entities with Entity ID below 1000 are not allowed to be deleted int32 public constant AUTHORIZATION_FAILED = 101; // Violating one of these rules: 1) treasury account can update all entities below 0.0.1000, 2) account 0.0.50 can update all entities from 0.0.51 - 0.0.80, 3) Network Function Master Account A/c 0.0.50 - Update all Network Function accounts & perform all the Network Functions listed below, 4) Network Function Accounts: i) A/c 0.0.55 - Update Address Book files (0.0.101/102), ii) A/c 0.0.56 - Update Fee schedule (0.0.111), iii) A/c 0.0.57 - Update Exchange Rate (0.0.112). int32 public constant FILE_UPLOADED_PROTO_INVALID = 102; // Fee Schedule Proto uploaded but not valid (append or update is required) int32 public constant FILE_UPLOADED_PROTO_NOT_SAVED_TO_DISK = 103; // Fee Schedule Proto uploaded but not valid (append or update is required) int32 public constant FEE_SCHEDULE_FILE_PART_UPLOADED = 104; // Fee Schedule Proto File Part uploaded int32 public constant EXCHANGE_RATE_CHANGE_LIMIT_EXCEEDED = 105; // The change on Exchange Rate exceeds Exchange_Rate_Allowed_Percentage int32 public constant MAX_CONTRACT_STORAGE_EXCEEDED = 106; // Contract permanent storage exceeded the currently allowable limit int32 public constant TRANSFER_ACCOUNT_SAME_AS_DELETE_ACCOUNT = 107; // Transfer Account should not be same as Account to be deleted int32 public constant TOTAL_LEDGER_BALANCE_INVALID = 108; int32 public constant EXPIRATION_REDUCTION_NOT_ALLOWED = 110; // The expiration date/time on a smart contract may not be reduced int32 public constant MAX_GAS_LIMIT_EXCEEDED = 111; //Gas exceeded currently allowable gas limit per transaction int32 public constant MAX_FILE_SIZE_EXCEEDED = 112; // File size exceeded the currently allowable limit int32 public constant INVALID_TOPIC_ID = 150; // The Topic ID specified is not in the system. int32 public constant INVALID_ADMIN_KEY = 155; // A provided admin key was invalid. int32 public constant INVALID_SUBMIT_KEY = 156; // A provided submit key was invalid. int32 public constant UNAUTHORIZED = 157; // An attempted operation was not authorized (ie - a deleteTopic for a topic with no adminKey). int32 public constant INVALID_TOPIC_MESSAGE = 158; // A ConsensusService message is empty. int32 public constant INVALID_AUTORENEW_ACCOUNT = 159; // The autoRenewAccount specified is not a valid, active account. int32 public constant AUTORENEW_ACCOUNT_NOT_ALLOWED = 160; // An adminKey was not specified on the topic, so there must not be an autoRenewAccount. // The topic has expired, was not automatically renewed, and is in a 7 day grace period before the topic will be // deleted unrecoverably. This error response code will not be returned until autoRenew functionality is supported // by HAPI. int32 public constant TOPIC_EXPIRED = 162; int32 public constant INVALID_CHUNK_NUMBER = 163; // chunk number must be from 1 to total (chunks) inclusive. int32 public constant INVALID_CHUNK_TRANSACTION_ID = 164; // For every chunk, the payer account that is part of initialTransactionID must match the Payer Account of this transaction. The entire initialTransactionID should match the transactionID of the first chunk, but this is not checked or enforced by Hedera except when the chunk number is 1. int32 public constant ACCOUNT_FROZEN_FOR_TOKEN = 165; // Account is frozen and cannot transact with the token int32 public constant TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED = 166; // An involved account already has more than <tt>tokens.maxPerAccount</tt> associations with non-deleted tokens. int32 public constant INVALID_TOKEN_ID = 167; // The token is invalid or does not exist int32 public constant INVALID_TOKEN_DECIMALS = 168; // Invalid token decimals int32 public constant INVALID_TOKEN_INITIAL_SUPPLY = 169; // Invalid token initial supply int32 public constant INVALID_TREASURY_ACCOUNT_FOR_TOKEN = 170; // Treasury Account does not exist or is deleted int32 public constant INVALID_TOKEN_SYMBOL = 171; // Token Symbol is not UTF-8 capitalized alphabetical string int32 public constant TOKEN_HAS_NO_FREEZE_KEY = 172; // Freeze key is not set on token int32 public constant TRANSFERS_NOT_ZERO_SUM_FOR_TOKEN = 173; // Amounts in transfer list are not net zero int32 public constant MISSING_TOKEN_SYMBOL = 174; // A token symbol was not provided int32 public constant TOKEN_SYMBOL_TOO_LONG = 175; // The provided token symbol was too long int32 public constant ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN = 176; // KYC must be granted and account does not have KYC granted int32 public constant TOKEN_HAS_NO_KYC_KEY = 177; // KYC key is not set on token int32 public constant INSUFFICIENT_TOKEN_BALANCE = 178; // Token balance is not sufficient for the transaction int32 public constant TOKEN_WAS_DELETED = 179; // Token transactions cannot be executed on deleted token int32 public constant TOKEN_HAS_NO_SUPPLY_KEY = 180; // Supply key is not set on token int32 public constant TOKEN_HAS_NO_WIPE_KEY = 181; // Wipe key is not set on token int32 public constant INVALID_TOKEN_MINT_AMOUNT = 182; // The requested token mint amount would cause an invalid total supply int32 public constant INVALID_TOKEN_BURN_AMOUNT = 183; // The requested token burn amount would cause an invalid total supply int32 public constant TOKEN_NOT_ASSOCIATED_TO_ACCOUNT = 184; // A required token-account relationship is missing int32 public constant CANNOT_WIPE_TOKEN_TREASURY_ACCOUNT = 185; // The target of a wipe operation was the token treasury account int32 public constant INVALID_KYC_KEY = 186; // The provided KYC key was invalid. int32 public constant INVALID_WIPE_KEY = 187; // The provided wipe key was invalid. int32 public constant INVALID_FREEZE_KEY = 188; // The provided freeze key was invalid. int32 public constant INVALID_SUPPLY_KEY = 189; // The provided supply key was invalid. int32 public constant MISSING_TOKEN_NAME = 190; // Token Name is not provided int32 public constant TOKEN_NAME_TOO_LONG = 191; // Token Name is too long int32 public constant INVALID_WIPING_AMOUNT = 192; // The provided wipe amount must not be negative, zero or bigger than the token holder balance int32 public constant TOKEN_IS_IMMUTABLE = 193; // Token does not have Admin key set, thus update/delete transactions cannot be performed int32 public constant TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT = 194; // An <tt>associateToken</tt> operation specified a token already associated to the account int32 public constant TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES = 195; // An attempted operation is invalid until all token balances for the target account are zero int32 public constant ACCOUNT_IS_TREASURY = 196; // An attempted operation is invalid because the account is a treasury int32 public constant TOKEN_ID_REPEATED_IN_TOKEN_LIST = 197; // Same TokenIDs present in the token list int32 public constant TOKEN_TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 198; // Exceeded the number of token transfers (both from and to) allowed for token transfer list int32 public constant EMPTY_TOKEN_TRANSFER_BODY = 199; // TokenTransfersTransactionBody has no TokenTransferList int32 public constant EMPTY_TOKEN_TRANSFER_ACCOUNT_AMOUNTS = 200; // TokenTransfersTransactionBody has a TokenTransferList with no AccountAmounts int32 public constant INVALID_SCHEDULE_ID = 201; // The Scheduled entity does not exist; or has now expired, been deleted, or been executed int32 public constant SCHEDULE_IS_IMMUTABLE = 202; // The Scheduled entity cannot be modified. Admin key not set int32 public constant INVALID_SCHEDULE_PAYER_ID = 203; // The provided Scheduled Payer does not exist int32 public constant INVALID_SCHEDULE_ACCOUNT_ID = 204; // The Schedule Create Transaction TransactionID account does not exist int32 public constant NO_NEW_VALID_SIGNATURES = 205; // The provided sig map did not contain any new valid signatures from required signers of the scheduled transaction int32 public constant UNRESOLVABLE_REQUIRED_SIGNERS = 206; // The required signers for a scheduled transaction cannot be resolved, for example because they do not exist or have been deleted int32 public constant SCHEDULED_TRANSACTION_NOT_IN_WHITELIST = 207; // Only whitelisted transaction types may be scheduled int32 public constant SOME_SIGNATURES_WERE_INVALID = 208; // At least one of the signatures in the provided sig map did not represent a valid signature for any required signer int32 public constant TRANSACTION_ID_FIELD_NOT_ALLOWED = 209; // The scheduled field in the TransactionID may not be set to true int32 public constant IDENTICAL_SCHEDULE_ALREADY_CREATED = 210; // A schedule already exists with the same identifying fields of an attempted ScheduleCreate (that is, all fields other than scheduledPayerAccountID) int32 public constant INVALID_ZERO_BYTE_IN_STRING = 211; // A string field in the transaction has a UTF-8 encoding with the prohibited zero byte int32 public constant SCHEDULE_ALREADY_DELETED = 212; // A schedule being signed or deleted has already been deleted int32 public constant SCHEDULE_ALREADY_EXECUTED = 213; // A schedule being signed or deleted has already been executed int32 public constant MESSAGE_SIZE_TOO_LARGE = 214; // ConsensusSubmitMessage request's message size is larger than allowed. }
The payer account has insufficient cryptocurrency to pay the transaction fee
int32 public constant INSUFFICIENT_PAYER_BALANCE = 10;
14,068,792
[ 1, 1986, 293, 1773, 2236, 711, 2763, 11339, 13231, 504, 295, 3040, 358, 8843, 326, 2492, 14036, 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 ]
[ 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, 0 ]
[ 1, 565, 509, 1578, 1071, 5381, 2120, 6639, 42, 1653, 7266, 2222, 67, 11389, 654, 67, 38, 1013, 4722, 273, 1728, 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 ]
pragma solidity ^0.5.0; // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- 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); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- 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; } } contract Baros is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Baros"; symbol = "BRO"; decimals = 18; _totalSupply = 525000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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; } 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; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "Baros"; symbol = "BRO"; decimals = 18; _totalSupply = 525000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
13,436,840
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 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 ]
[ 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, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 5190, 538, 14432, 203, 3639, 3273, 273, 315, 38, 1457, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 1381, 2947, 12648, 12648, 12648, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 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 ]
./partial_match/42/0xE0Df94523C3CC81b8818ea97bcd326aA466A91dF/sources/GovernanceProxy.sol
* @notice Remove a token from the pool @dev Logic in the CRP controls when ths can be called. There are two related permissions: AddRemoveTokens - which allows removing down to the underlying BPool limit of two RemoveAllTokens - which allows completely draining the pool by removing all tokens This can result in a non-viable pool with 0 or 1 tokens (by design), meaning all swapping or binding operations would fail in this state @param self - ConfigurableRightsPool instance calling the library @param bPool - Core BPool the CRP is wrapping @param token - token to remove/ poolShares = totalSupply * tokenWeight / totalWeight this is what will be unbound from the pool Have to get it before unbinding Unbind and get the tokens out of balancer pool Now with the tokens this contract can send them to msg.sender
function removeToken( IConfigurableRightsPool self, IBPool bPool, address token ) external { uint totalSupply = self.totalSupply(); uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, bPool.getDenormalizedWeight(token)), bPool.getTotalDenormalizedWeight()); uint balance = bPool.getBalance(token); bPool.unbind(token); bool xfer = IERC20(token).transfer(self.getController(), balance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(self.getController(), poolShares); self.burnPoolShareFromLib(poolShares); }
3,358,230
[ 1, 3288, 279, 1147, 628, 326, 2845, 225, 10287, 316, 326, 6732, 52, 11022, 1347, 286, 87, 848, 506, 2566, 18, 6149, 854, 2795, 3746, 4371, 30, 1377, 1436, 3288, 5157, 300, 1492, 5360, 9427, 2588, 358, 326, 6808, 605, 2864, 1800, 434, 2795, 1377, 25023, 5157, 300, 1492, 5360, 14416, 15427, 310, 326, 2845, 635, 9427, 777, 2430, 13491, 1220, 848, 563, 316, 279, 1661, 17, 522, 429, 2845, 598, 374, 578, 404, 2430, 261, 1637, 8281, 3631, 13491, 12256, 777, 7720, 1382, 578, 5085, 5295, 4102, 2321, 316, 333, 919, 225, 365, 300, 29312, 18464, 2864, 791, 4440, 326, 5313, 225, 324, 2864, 300, 4586, 605, 2864, 326, 6732, 52, 353, 14702, 225, 1147, 300, 1147, 358, 1206, 19, 2845, 24051, 273, 2078, 3088, 1283, 225, 1147, 6544, 342, 2078, 6544, 333, 353, 4121, 903, 506, 30177, 628, 326, 2845, 21940, 358, 336, 518, 1865, 640, 7374, 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, 1206, 1345, 12, 203, 3639, 467, 31660, 18464, 2864, 365, 16, 203, 3639, 23450, 2864, 324, 2864, 16, 203, 3639, 1758, 1147, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2254, 2078, 3088, 1283, 273, 365, 18, 4963, 3088, 1283, 5621, 203, 203, 3639, 2254, 2845, 24051, 273, 605, 5191, 9890, 10477, 18, 70, 2892, 12, 6444, 9890, 10477, 18, 70, 16411, 12, 4963, 3088, 1283, 16, 203, 28524, 1377, 324, 2864, 18, 588, 8517, 1687, 1235, 6544, 12, 2316, 13, 3631, 203, 4766, 7734, 324, 2864, 18, 588, 5269, 8517, 1687, 1235, 6544, 10663, 203, 203, 3639, 2254, 11013, 273, 324, 2864, 18, 588, 13937, 12, 2316, 1769, 203, 203, 3639, 324, 2864, 18, 318, 4376, 12, 2316, 1769, 203, 203, 3639, 1426, 619, 586, 273, 467, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 2890, 18, 588, 2933, 9334, 11013, 1769, 203, 3639, 2583, 12, 23168, 16, 315, 9712, 67, 654, 39, 3462, 67, 21053, 8863, 203, 203, 3639, 365, 18, 13469, 2864, 9535, 1265, 5664, 12, 2890, 18, 588, 2933, 9334, 2845, 24051, 1769, 203, 3639, 365, 18, 70, 321, 2864, 9535, 1265, 5664, 12, 6011, 24051, 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 ]
/* pragma solidity ^0.4.14; import './TESTToken.sol'; import './SafeMath.sol'; contract Crowdsale { using SafeMath for uint256; // The token being sold TESTToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { // To be defined } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (TESTToken) { // To be defined } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { // To be defined } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = block.number >= startTime && block.number <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return block.number > endTime; } } */
@return true if crowdsale event has ended
function hasEnded() public constant returns (bool) { return block.number > endTime; }
15,793,977
[ 1, 2463, 638, 309, 276, 492, 2377, 5349, 871, 711, 16926, 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, 225, 445, 711, 28362, 1435, 1071, 5381, 1135, 261, 6430, 13, 288, 203, 565, 327, 1203, 18, 2696, 405, 13859, 31, 203, 225, 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, -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/0xb1a828EE90Dc19Ad1bE977576D1524523F46bfCb/sources/MutualFriends.sol
bool public isPaused = true; Name
contract MutualFriends is ERC721B, Ownable { using Strings for uint; uint public constant MAX_PER_WALLET = 10; uint public maxSupply = 8000; string private _baseURL = ""; mapping(address => uint) private _walletMintedCount; constructor() ERC721B("Mutual Friends", "MF") { } function contractURI() public pure returns (string memory) { return ""; } function mintedCount(address owner) external view returns (uint) { return _walletMintedCount[owner]; } function setBaseUri(string memory url) external onlyOwner { _baseURL = url; } function withdraw() external onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } function withdraw() external onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } function devMint(address to, uint count) external onlyOwner { require( totalSupply() + count <= maxSupply, "Exceeds max supply" ); _safeMint(to, count); } function setMaxSupply(uint newMaxSupply) external onlyOwner { maxSupply = newMaxSupply; } function tokenURI(uint tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(_baseURL).length > 0 ? string(abi.encodePacked(_baseURL, tokenId.toString(), ".json")) : ""; } function mint() external payable { uint count=MAX_PER_WALLET; require(totalSupply() + count <= maxSupply,"Exceeds max supply"); require(Whitelist(address(0xDf690436BD045040faD518cA2f41a7891ac8d5e3)).whiteList(msg.sender) ,"You are not on the whitelist!"); _safeMint(msg.sender, count); } }
3,633,838
[ 1, 6430, 1071, 353, 28590, 273, 638, 31, 1770, 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, 16351, 14138, 1462, 42, 22259, 353, 4232, 39, 27, 5340, 38, 16, 14223, 6914, 288, 203, 202, 9940, 8139, 364, 2254, 31, 203, 203, 565, 2254, 1071, 5381, 4552, 67, 3194, 67, 59, 1013, 15146, 273, 1728, 31, 203, 202, 11890, 1071, 943, 3088, 1283, 273, 1725, 3784, 31, 203, 203, 565, 533, 3238, 389, 1969, 1785, 273, 1408, 31, 203, 202, 6770, 12, 2867, 516, 2254, 13, 3238, 389, 19177, 49, 474, 329, 1380, 31, 203, 203, 202, 12316, 1435, 203, 202, 654, 39, 27, 5340, 38, 2932, 7420, 1462, 478, 22259, 3113, 315, 13542, 7923, 288, 203, 565, 289, 203, 203, 202, 915, 6835, 3098, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 202, 202, 2463, 1408, 31, 203, 202, 97, 203, 203, 565, 445, 312, 474, 329, 1380, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 19177, 49, 474, 329, 1380, 63, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 26435, 3006, 12, 1080, 3778, 880, 13, 3903, 1338, 5541, 288, 203, 202, 565, 389, 1969, 1785, 273, 880, 31, 203, 202, 97, 203, 203, 203, 202, 915, 598, 9446, 1435, 3903, 1338, 5541, 288, 203, 202, 202, 12, 6430, 2216, 16, 262, 273, 8843, 429, 12, 3576, 18, 15330, 2934, 1991, 95, 203, 5411, 460, 30, 1758, 12, 2211, 2934, 12296, 203, 3639, 289, 2932, 8863, 203, 3639, 2583, 12, 4768, 1769, 203, 202, 97, 203, 203, 202, 915, 598, 9446, 1435, 3903, 1338, 5541, 288, 203, 202, 202, 12, 2 ]
./full_match/1/0xB3c0bB87e192095280742F97cA917935B1c04Cf7/sources/contracts/Avril15SeasonThree.sol
Change Base URI functions
function _baseURI() internal view override returns (string memory) { return baseURI; }
9,792,904
[ 1, 3043, 3360, 3699, 4186, 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, 565, 445, 389, 1969, 3098, 1435, 2713, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 202, 202, 2463, 1026, 3098, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xB5B234261e461C3Fe97a7dd676251262064671AB/sources/ProofofLife.sol
require(token.allowance(msg.sender, address(this)) >= _amount, "Insufficient allowance.");
function updateDeed(uint256 _deedId, uint256 _maturity, beneficiaries[] memory _array) external { require(deedDetails[_deedId].spender == msg.sender, "Not the owner of deed."); deedDetails[deedId].maturity = _maturity; for(uint i=0; i<_array.length; i++) { beneficiaryList[deedId][i] = _array[i]; } }
3,802,352
[ 1, 6528, 12, 2316, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 389, 8949, 16, 315, 5048, 11339, 1699, 1359, 1199, 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, 0, 0, 0, 0, 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, 1089, 758, 329, 12, 11890, 5034, 389, 323, 329, 548, 16, 2254, 5034, 389, 7373, 2336, 16, 27641, 74, 14463, 5646, 8526, 3778, 389, 1126, 13, 3903, 288, 203, 3639, 2583, 12, 323, 329, 3790, 63, 67, 323, 329, 548, 8009, 87, 1302, 264, 422, 1234, 18, 15330, 16, 315, 1248, 326, 3410, 434, 443, 329, 1199, 1769, 203, 3639, 443, 329, 3790, 63, 323, 329, 548, 8009, 7373, 2336, 273, 389, 7373, 2336, 31, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 277, 32, 67, 1126, 18, 2469, 31, 277, 27245, 288, 203, 5411, 27641, 74, 14463, 814, 682, 63, 323, 329, 548, 6362, 77, 65, 273, 389, 1126, 63, 77, 15533, 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 ]
./full_match/100/0x44Ea041bb0FB996ae76a5F8323a63d61DEdF7675/sources/contracts/FreeBetV2.sol
@title Azuro free bet contract
contract FreeBetV2 is ERC721Upgradeable, OwnableUpgradeable { pragma solidity ^0.8.4; struct Bet { uint128 amount; uint64 minOdds; uint64 durationTime; } struct AzuroBet { address owner; uint256 freeBetId; uint128 amount; uint128 payout; } ILP public LP; string public baseURI; address public token; uint256 public lockedReserve; mapping(uint256 => Bet) public freeBets; mapping(uint256 => AzuroBet) public azuroBets; mapping(uint256 => uint64) public expirationTime; uint256 public lastTokenId; mapping(address => bool) public maintainers; event LpChanged(address indexed newLp); event FreeBetMinted(address indexed receiver, uint256 indexed id, Bet bet); event FreeBetMintedBatch(address[] receivers, uint256[] ids, Bet[] bets); event FreeBetRedeemed( address indexed bettor, uint256 indexed id, uint256 indexed azurobetId, uint128 amount ); event FreeBetReissue(address indexed receiver, uint256 indexed id, Bet bet); event MaintainerUpdated(address maintainer, bool active); error NotBetOwner(); error InsufficientAmount(); error DifferentArraysLength(); error WrongToken(); error InsufficientContractBalance(); error NonTransferable(); error BetExpired(); error OddsTooSmall(); error ZeroAmount(); error ZeroDuration(); error OnlyMaintainer(); modifier onlyMaintainer() { if (!maintainers[msg.sender]) revert OnlyMaintainer(); _; } function initialize(address token_) external initializer { __ERC721_init("FreeBetV2", "FBTV2"); __Ownable_init(); if (token_ == address(0)) revert WrongToken(); token = token_; } function setLp(address lp) external onlyOwner { LP = ILP(lp); emit LpChanged(lp); } function setBaseURI(string calldata uri) external onlyOwner { baseURI = uri; } function updateMaintainer(address maintainer, bool active) external onlyOwner { maintainers[maintainer] = active; emit MaintainerUpdated(maintainer, active); } function getExpiredUnburned(uint256 start, uint256 count) external view returns (uint256[] memory, uint256) { uint256[] memory ids = new uint256[](count); uint256 index; uint256 end = start + count; Bet storage bet; for (uint256 id = start; id < end; id++) { bet = freeBets[id]; if (bet.amount > 0 && expirationTime[id] <= block.timestamp) { ids[index++] = id; } } return (ids, index); } function getExpiredUnburned(uint256 start, uint256 count) external view returns (uint256[] memory, uint256) { uint256[] memory ids = new uint256[](count); uint256 index; uint256 end = start + count; Bet storage bet; for (uint256 id = start; id < end; id++) { bet = freeBets[id]; if (bet.amount > 0 && expirationTime[id] <= block.timestamp) { ids[index++] = id; } } return (ids, index); } function getExpiredUnburned(uint256 start, uint256 count) external view returns (uint256[] memory, uint256) { uint256[] memory ids = new uint256[](count); uint256 index; uint256 end = start + count; Bet storage bet; for (uint256 id = start; id < end; id++) { bet = freeBets[id]; if (bet.amount > 0 && expirationTime[id] <= block.timestamp) { ids[index++] = id; } } return (ids, index); } function burnExpired(uint256[] calldata ids) external { uint256 burnedAmount; uint256 len = ids.length; uint256 id; Bet storage bet; uint128 amount; for (uint256 i = 0; i < len; i++) { id = ids[i]; bet = freeBets[id]; amount = bet.amount; if (amount > 0 && expirationTime[id] <= block.timestamp) { burnedAmount += amount; bet.amount = 0; _burn(id); } } lockedReserve -= burnedAmount; } function burnExpired(uint256[] calldata ids) external { uint256 burnedAmount; uint256 len = ids.length; uint256 id; Bet storage bet; uint128 amount; for (uint256 i = 0; i < len; i++) { id = ids[i]; bet = freeBets[id]; amount = bet.amount; if (amount > 0 && expirationTime[id] <= block.timestamp) { burnedAmount += amount; bet.amount = 0; _burn(id); } } lockedReserve -= burnedAmount; } function burnExpired(uint256[] calldata ids) external { uint256 burnedAmount; uint256 len = ids.length; uint256 id; Bet storage bet; uint128 amount; for (uint256 i = 0; i < len; i++) { id = ids[i]; bet = freeBets[id]; amount = bet.amount; if (amount > 0 && expirationTime[id] <= block.timestamp) { burnedAmount += amount; bet.amount = 0; _burn(id); } } lockedReserve -= burnedAmount; } function withdrawReserve(uint128 amount) external onlyMaintainer { _checkInsufficient(amount); TransferHelper.safeTransfer(token, msg.sender, amount); } function mintBatch(address[] calldata receivers, Bet[] calldata bets) external onlyMaintainer { uint256 receiversLength = receivers.length; if (receiversLength != bets.length) revert DifferentArraysLength(); uint256[] memory ids = new uint256[](receiversLength); uint256 lastId = lastTokenId; uint128 amountsSum; for (uint256 i = 0; i < receiversLength; i++) { ids[i] = ++lastId; amountsSum += bets[i].amount; _safeMint(receivers[i], lastId, bets[i]); } _checkInsufficient(amountsSum); lastTokenId = lastId; lockedReserve += amountsSum; emit FreeBetMintedBatch(receivers, ids, bets); } function mintBatch(address[] calldata receivers, Bet[] calldata bets) external onlyMaintainer { uint256 receiversLength = receivers.length; if (receiversLength != bets.length) revert DifferentArraysLength(); uint256[] memory ids = new uint256[](receiversLength); uint256 lastId = lastTokenId; uint128 amountsSum; for (uint256 i = 0; i < receiversLength; i++) { ids[i] = ++lastId; amountsSum += bets[i].amount; _safeMint(receivers[i], lastId, bets[i]); } _checkInsufficient(amountsSum); lastTokenId = lastId; lockedReserve += amountsSum; emit FreeBetMintedBatch(receivers, ids, bets); } function mint(address to, Bet calldata bet) external onlyMaintainer { _checkInsufficient(bet.amount); lockedReserve += bet.amount; uint256 newId = ++lastTokenId; _safeMint(to, newId, bet); emit FreeBetMinted(to, newId, bet); } function redeem( uint256 id, uint256 conditionId, uint128 amount, uint64 outcomeId, uint64 deadline, uint64 minOdds ) external returns (uint256) { if (ownerOf(id) != msg.sender) revert NotBetOwner(); Bet storage bet = freeBets[id]; if (bet.amount < amount) revert InsufficientAmount(); if (expirationTime[id] <= block.timestamp) revert BetExpired(); if (bet.minOdds > minOdds) revert OddsTooSmall(); lockedReserve -= amount; bet.amount -= amount; TransferHelper.safeApprove(token, address(LP), amount); uint256 azuroBetId = LP.bet( conditionId, amount, outcomeId, deadline, minOdds ); azuroBets[azuroBetId] = AzuroBet(msg.sender, id, amount, 0); emit FreeBetRedeemed(msg.sender, id, azuroBetId, amount); return azuroBetId; } function resolvePayout(uint256 azuroBetId) external { azuroBets[azuroBetId].payout = _resolvePayout(azuroBetId); } function withdrawPayout(uint256 azuroBetId) external { AzuroBet storage azuroBet = azuroBets[azuroBetId]; if (azuroBet.owner != msg.sender) revert NotBetOwner(); uint128 payout = azuroBet.payout; if (payout == 0) payout = _resolvePayout(azuroBetId); uint128 winPayout = payout - azuroBet.amount; azuroBet.payout = 0; if (winPayout > 0) { TransferHelper.safeTransfer(token, msg.sender, winPayout); } } function withdrawPayout(uint256 azuroBetId) external { AzuroBet storage azuroBet = azuroBets[azuroBetId]; if (azuroBet.owner != msg.sender) revert NotBetOwner(); uint128 payout = azuroBet.payout; if (payout == 0) payout = _resolvePayout(azuroBetId); uint128 winPayout = payout - azuroBet.amount; azuroBet.payout = 0; if (winPayout > 0) { TransferHelper.safeTransfer(token, msg.sender, winPayout); } } function _resolvePayout(uint256 azuroBetId) internal returns (uint128) { AzuroBet storage azuroBet = azuroBets[azuroBetId]; (, uint128 fullPayout) = LP.viewPayout(azuroBetId); LP.withdrawPayout(azuroBetId); uint128 betAmount = azuroBet.amount; uint256 freeBetId = azuroBet.freeBetId; if (fullPayout - betAmount > 0) { if (freeBets[freeBetId].amount == 0) { _burn(freeBetId); } bet.amount += betAmount; lockedReserve += betAmount; expirationTime[freeBetId] = uint64(block.timestamp) + bet.durationTime; emit FreeBetReissue(azuroBet.owner, azuroBet.freeBetId, bet); } return fullPayout; } function _resolvePayout(uint256 azuroBetId) internal returns (uint128) { AzuroBet storage azuroBet = azuroBets[azuroBetId]; (, uint128 fullPayout) = LP.viewPayout(azuroBetId); LP.withdrawPayout(azuroBetId); uint128 betAmount = azuroBet.amount; uint256 freeBetId = azuroBet.freeBetId; if (fullPayout - betAmount > 0) { if (freeBets[freeBetId].amount == 0) { _burn(freeBetId); } bet.amount += betAmount; lockedReserve += betAmount; expirationTime[freeBetId] = uint64(block.timestamp) + bet.durationTime; emit FreeBetReissue(azuroBet.owner, azuroBet.freeBetId, bet); } return fullPayout; } function _resolvePayout(uint256 azuroBetId) internal returns (uint128) { AzuroBet storage azuroBet = azuroBets[azuroBetId]; (, uint128 fullPayout) = LP.viewPayout(azuroBetId); LP.withdrawPayout(azuroBetId); uint128 betAmount = azuroBet.amount; uint256 freeBetId = azuroBet.freeBetId; if (fullPayout - betAmount > 0) { if (freeBets[freeBetId].amount == 0) { _burn(freeBetId); } bet.amount += betAmount; lockedReserve += betAmount; expirationTime[freeBetId] = uint64(block.timestamp) + bet.durationTime; emit FreeBetReissue(azuroBet.owner, azuroBet.freeBetId, bet); } return fullPayout; } } else { Bet storage bet = freeBets[freeBetId]; function _safeMint( address to, uint256 id, Bet calldata bet ) internal { if (bet.amount == 0) revert ZeroAmount(); if (bet.durationTime == 0) revert ZeroDuration(); freeBets[id] = bet; expirationTime[id] = uint64(block.timestamp) + bet.durationTime; _safeMint(to, id); } function _transfer( address, address, uint256 ) internal pure override { revert NonTransferable(); } function _baseURI() internal view override returns (string memory) { return baseURI; } function _checkInsufficient(uint128 amount) internal view { if (IERC20(token).balanceOf(address(this)) < lockedReserve + amount) revert InsufficientContractBalance(); } }
14,276,162
[ 1, 37, 94, 19321, 4843, 2701, 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, 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, 16351, 15217, 38, 278, 58, 22, 353, 4232, 39, 27, 5340, 10784, 429, 16, 14223, 6914, 10784, 429, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 605, 278, 288, 203, 3639, 2254, 10392, 3844, 31, 203, 3639, 2254, 1105, 1131, 51, 449, 87, 31, 203, 3639, 2254, 1105, 3734, 950, 31, 203, 565, 289, 203, 203, 565, 1958, 432, 94, 19321, 38, 278, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 5034, 4843, 38, 278, 548, 31, 203, 3639, 2254, 10392, 3844, 31, 203, 3639, 2254, 10392, 293, 2012, 31, 203, 565, 289, 203, 203, 565, 467, 14461, 1071, 511, 52, 31, 203, 565, 533, 1071, 1026, 3098, 31, 203, 565, 1758, 1071, 1147, 31, 203, 565, 2254, 5034, 1071, 8586, 607, 6527, 31, 203, 565, 2874, 12, 11890, 5034, 516, 605, 278, 13, 1071, 4843, 38, 2413, 31, 203, 565, 2874, 12, 11890, 5034, 516, 432, 94, 19321, 38, 278, 13, 1071, 10562, 19321, 38, 2413, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 1105, 13, 1071, 7686, 950, 31, 203, 565, 2254, 5034, 1071, 27231, 548, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 11566, 8234, 31, 203, 203, 565, 871, 511, 84, 5033, 12, 2867, 8808, 394, 48, 84, 1769, 203, 565, 871, 15217, 38, 278, 49, 474, 329, 12, 2867, 8808, 5971, 16, 2254, 5034, 8808, 612, 16, 605, 278, 2701, 1769, 203, 565, 871, 15217, 38, 278, 49, 474, 329, 4497, 12, 2867, 8526, 22686, 16, 2254, 2 ]
pragma solidity 0.5.17; import "../lib/IERC20.sol"; import "../lib/SafeERC20.sol"; import "../elastictokens/iElasticTokenInterface.sol"; contract iTokenReserves { // Token that serves as a reserve for iToken address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public itokenAddress; /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Event emitted when rebaser is changed */ event NewRebaser(address oldRebaser, address newRebaser); modifier onlyGov() { require(msg.sender == gov); _; } constructor( address reserveToken_, address itokenAddress_ ) public { reserveToken = reserveToken_; itokenAddress = itokenAddress_; gov = msg.sender; } function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; iElasticTokenInterface(itokenAddress).decreaseAllowance(oldRebaser, uint256(- 1)); rebaser = rebaser_; iElasticTokenInterface(itokenAddress).approve(rebaser_, uint256(- 1)); emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the gov contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** * @notice lets msg.sender accept governance */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /// @notice Moves all tokens to a new reserve contract function migrateReserves( address newReserve, address[] memory tokens ) public onlyGov { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 bal = token.balanceOf(address(this)); SafeERC20.safeTransfer(token, newReserve, bal); } } /// @notice Gets the current amount of reserves token held by this contract function reserves() public view returns (uint256) { return IERC20(reserveToken).balanceOf(address(this)); } }
@notice Moves all tokens to a new reserve contract
function migrateReserves( address newReserve, address[] memory tokens ) public onlyGov { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 bal = token.balanceOf(address(this)); SafeERC20.safeTransfer(token, newReserve, bal); } }
12,738,304
[ 1, 19297, 777, 2430, 358, 279, 394, 20501, 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, 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, 445, 13187, 607, 264, 3324, 12, 203, 3639, 1758, 394, 607, 6527, 16, 203, 3639, 1758, 8526, 3778, 2430, 203, 565, 262, 203, 565, 1071, 203, 565, 1338, 43, 1527, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2430, 18, 2469, 31, 277, 27245, 288, 203, 5411, 467, 654, 39, 3462, 1147, 273, 467, 654, 39, 3462, 12, 7860, 63, 77, 19226, 203, 5411, 2254, 5034, 324, 287, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 14060, 654, 39, 3462, 18, 4626, 5912, 12, 2316, 16, 394, 607, 6527, 16, 324, 287, 1769, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-02-04 */ // SPDX-License-Identifier: AGPL-3.0-or-later // hevm: flattened sources of src/DssExecLib.sol pragma solidity >=0.6.11 <0.7.0; ////// src/MathLib.sol // // MathLib.sol -- Math Functions // // 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.6.11; */ library MathLib { uint256 constant public WAD = 10 ** 18; uint256 constant public RAY = 10 ** 27; uint256 constant public RAD = 10 ** 45; uint256 constant public THOUSAND = 10 ** 3; uint256 constant public MILLION = 10 ** 6; // --- SafeMath Functions --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } 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; } } ////// src/DssExecLib.sol // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // 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.6.11; */ /* import "./MathLib.sol"; */ interface Initializable { function init(bytes32) external; } interface Authorizable { function rely(address) external; function deny(address) external; } interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface Drippable { function drip() external returns (uint256); function drip(bytes32) external returns (uint256); } interface Pricing { function poke(bytes32) external; } interface ERC20 { function decimals() external returns (uint8); } interface DssVat { function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust); function Line() external view returns (uint256); } interface AuctionLike { function vat() external returns (address); function cat() external returns (address); // Only flip function beg() external returns (uint256); function pad() external returns (uint256); // Only flop function ttl() external returns (uint256); function tau() external returns (uint256); function ilk() external returns (bytes32); // Only flip function gem() external returns (bytes32); // Only flap/flop } interface JoinLike_2 { function vat() external returns (address); function ilk() external returns (bytes32); function gem() external returns (address); function dec() external returns (uint256); } // Includes Median and OSM functions interface OracleLike_2 { function src() external view returns (address); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; } interface MomLike { function setOsm(bytes32, address) external; } interface RegistryLike_2 { function add(address) external; function info(bytes32) external view returns ( string memory, string memory, uint256, address, address, address, address ); } // https://github.com/makerdao/dss-chain-log interface ChainlogLike_2 { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } interface IAMLike { function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } contract DssExecLib { using MathLib for *; /****************************/ /*** Changelog Management ***/ /****************************/ /** @dev Set an address in the MCD on-chain changelog. @param _log Address of the chainlog contract @param _key Access key for the address (e.g. "MCD_VAT") @param _val The address associated with the _key */ function setChangelogAddress(address _log, bytes32 _key, address _val) public { ChainlogLike_2(_log).setAddress(_key, _val); } /** @dev Set version in the MCD on-chain changelog. @param _log Address of the chainlog contract @param _version Changelog version (e.g. "1.1.2") */ function setChangelogVersion(address _log, string memory _version) public { ChainlogLike_2(_log).setVersion(_version); } /** @dev Set IPFS hash of IPFS changelog in MCD on-chain changelog. @param _log Address of the chainlog contract @param _ipfsHash IPFS hash (e.g. "QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW") */ function setChangelogIPFS(address _log, string memory _ipfsHash) public { ChainlogLike_2(_log).setIPFS(_ipfsHash); } /** @dev Set SHA256 hash in MCD on-chain changelog. @param _log Address of the chainlog contract @param _SHA256Sum SHA256 hash (e.g. "e42dc9d043a57705f3f097099e6b2de4230bca9a020c797508da079f9079e35b") */ function setChangelogSHA256(address _log, string memory _SHA256Sum) public { ChainlogLike_2(_log).setSha256sum(_SHA256Sum); } /**********************/ /*** Authorizations ***/ /**********************/ /** @dev Give an address authorization to perform auth actions on the contract. @param _base The address of the contract where the authorization will be set @param _ward Address to be authorized */ function authorize(address _base, address _ward) public { Authorizable(_base).rely(_ward); } /** @dev Revoke contract authorization from an address. @param _base The address of the contract where the authorization will be revoked @param _ward Address to be deauthorized */ function deauthorize(address _base, address _ward) public { Authorizable(_base).deny(_ward); } /**************************/ /*** Accumulating Rates ***/ /**************************/ /** @dev Update rate accumulation for the Dai Savings Rate (DSR). @param _pot Address of the MCD_POT core contract */ function accumulateDSR(address _pot) public { Drippable(_pot).drip(); } /** @dev Update rate accumulation for the stability fees of a given collateral type. @param _jug Address of the MCD_JUG core contract @param _ilk Collateral type */ function accumulateCollateralStabilityFees(address _jug, bytes32 _ilk) public { Drippable(_jug).drip(_ilk); } /*********************/ /*** Price Updates ***/ /*********************/ /** @dev Update price of a given collateral type. @param _spot Spotter contract address @param _ilk Collateral type */ function updateCollateralPrice(address _spot, bytes32 _ilk) public { Pricing(_spot).poke(_ilk); } /****************************/ /*** System Configuration ***/ /****************************/ /** @dev Set a contract in another contract, defining the relationship (ex. set a new Cat contract in the Vat) @param _base The address of the contract where the new contract address will be filed @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _what, address _addr) public { Fileable(_base).file(_what, _addr); } /** @dev Set a contract in another contract, defining the relationship (ex. set a new Cat contract in the Vat) @param _base The address of the contract where the new contract address will be filed @param _ilk Collateral type @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public { Fileable(_base).file(_ilk, _what, _addr); } /******************************/ /*** System Risk Parameters ***/ /******************************/ // function setGlobalDebtCeiling(uint256 _amount) public { setGlobalDebtCeiling(vat(), _amount); } /** @dev Set the global debt ceiling. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setGlobalDebtCeiling(address _vat, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-global-Line-precision" Fileable(_vat).file("Line", _amount * MathLib.RAD); } /** @dev Increase the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _amount The amount to add in DAI (ex. 10m DAI amount == 10000000) */ function increaseGlobalDebtCeiling(address _vat, uint256 _amount) public { setGlobalDebtCeiling(_vat, MathLib.add(DssVat(_vat).Line() / MathLib.RAD, _amount)); } /** @dev Decrease the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _amount The amount to reduce in DAI (ex. 10m DAI amount == 10000000) */ function decreaseGlobalDebtCeiling(address _vat, uint256 _amount) public { setGlobalDebtCeiling(_vat, MathLib.sub(DssVat(_vat).Line() / MathLib.RAD, _amount)); } /** @dev Set the Dai Savings Rate. See: docs/rates.txt @param _pot The address of the Pot core contract @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) */ function setDSR(address _pot, uint256 _rate) public { require((_rate >= MathLib.RAY) && (_rate < 2 * MathLib.RAY)); // "LibDssExec/dsr-out-of-bounds" Fileable(_pot).file("dsr", _rate); } /** @dev Set the DAI amount for system surplus auctions. Amount will be converted to the correct internal precision. @param _vow The address of the Vow core contract @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusAuctionAmount(address _vow, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-vow-bump-precision" Fileable(_vow).file("bump", _amount * MathLib.RAD); } /** @dev Set the DAI amount for system surplus buffer, must be exceeded before surplus auctions start. Amount will be converted to the correct internal precision. @param _vow The address of the Vow core contract @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusBuffer(address _vow, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-vow-hump-precision" Fileable(_vow).file("hump", _amount * MathLib.RAD); } /** @dev Set minimum bid increase for surplus auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _flap The address of the Flapper core contract @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinSurplusAuctionBidIncrease(address _flap, uint256 _pct_bps) public { require(_pct_bps < 10 * MathLib.THOUSAND); // "LibDssExec/incorrect-flap-beg-precision" Fileable(_flap).file("beg", MathLib.add(MathLib.WAD, MathLib.wdiv(_pct_bps, 10 * MathLib.THOUSAND))); } /** @dev Set bid duration for surplus auctions. @param _flap The address of the Flapper core contract @param _duration Amount of time for bids. */ function setSurplusAuctionBidDuration(address _flap, uint256 _duration) public { Fileable(_flap).file("ttl", _duration); } /** @dev Set total auction duration for surplus auctions. @param _flap The address of the Flapper core contract @param _duration Amount of time for auctions. */ function setSurplusAuctionDuration(address _flap, uint256 _duration) public { Fileable(_flap).file("tau", _duration); } /** @dev Set the number of seconds that pass before system debt is auctioned for MKR tokens. @param _vow The address of the Vow core contract @param _duration Duration in seconds */ function setDebtAuctionDelay(address _vow, uint256 _duration) public { Fileable(_vow).file("wait", _duration); } /** @dev Set the DAI amount for system debt to be covered by each debt auction. Amount will be converted to the correct internal precision. @param _vow The address of the Vow core contract @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setDebtAuctionDAIAmount(address _vow, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-vow-sump-precision" Fileable(_vow).file("sump", _amount * MathLib.RAD); } /** @dev Set the starting MKR amount to be auctioned off to cover system debt in debt auctions. Amount will be converted to the correct internal precision. @param _vow The address of the Vow core contract @param _amount The amount to set in MKR (ex. 250 MKR amount == 250) */ function setDebtAuctionMKRAmount(address _vow, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-vow-dump-precision" Fileable(_vow).file("dump", _amount * MathLib.WAD); } /** @dev Set minimum bid increase for debt auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _flop The address of the Flopper core contract @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinDebtAuctionBidIncrease(address _flop, uint256 _pct_bps) public { require(_pct_bps < 10 * MathLib.THOUSAND); // "LibDssExec/incorrect-flap-beg-precision" Fileable(_flop).file("beg", MathLib.add(MathLib.WAD, MathLib.wdiv(_pct_bps, 10 * MathLib.THOUSAND))); } /** @dev Set bid duration for debt auctions. @param _flop The address of the Flopper core contract @param _duration Amount of time for bids. */ function setDebtAuctionBidDuration(address _flop, uint256 _duration) public { Fileable(_flop).file("ttl", _duration); } /** @dev Set total auction duration for debt auctions. @param _flop The address of the Flopper core contract @param _duration Amount of time for auctions. */ function setDebtAuctionDuration(address _flop, uint256 _duration) public { Fileable(_flop).file("tau", _duration); } /** @dev Set the rate of increasing amount of MKR out for auction during debt auctions. Amount will be converted to the correct internal precision. @dev MKR amount is increased by this rate every "tick" (if auction duration has passed and no one has bid on the MKR) @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _flop The address of the Flopper core contract @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setDebtAuctionMKRIncreaseRate(address _flop, uint256 _pct_bps) public { Fileable(_flop).file("pad", MathLib.add(MathLib.WAD, MathLib.wdiv(_pct_bps, 10 * MathLib.THOUSAND))); } /** @dev Set the maximum total DAI amount that can be out for liquidation in the system at any point. Amount will be converted to the correct internal precision. @param _cat The address of the Cat core contract @param _amount The amount to set in DAI (ex. 250,000 DAI amount == 250000) */ function setMaxTotalDAILiquidationAmount(address _cat, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-vow-dump-precision" Fileable(_cat).file("box", _amount * MathLib.RAD); } /** @dev Set the duration of time that has to pass during emergency shutdown before collateral can start being claimed by DAI holders. @param _end The address of the End core contract @param _duration Time in seconds to set for ES processing time */ function setEmergencyShutdownProcessingTime(address _end, uint256 _duration) public { Fileable(_end).file("wait", _duration); } /** @dev Set the global stability fee (is not typically used, currently is 0). 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 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _jug The address of the Jug core accounting contract @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) */ function setGlobalStabilityFee(address _jug, uint256 _rate) public { require((_rate >= MathLib.RAY) && (_rate < 2 * MathLib.RAY)); // "LibDssExec/global-stability-fee-out-of-bounds" Fileable(_jug).file("base", _rate); } /** @dev Set the value of DAI in the reference asset (e.g. $1 per DAI). Value will be converted to the correct internal precision. @dev Equation used for conversion is value * RAY / 1000 @param _spot The address of the Spot core contract @param _value The value to set as integer (x1000) (ex. $1.025 == 1025) */ function setDAIReferenceValue(address _spot, uint256 _value) public { require(_value < MathLib.WAD); // "LibDssExec/incorrect-ilk-dunk-precision" Fileable(_spot).file("par", MathLib.rdiv(_value, 1000)); } /*****************************/ /*** Collateral Management ***/ /*****************************/ /** @dev Set a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkDebtCeiling(address _vat, bytes32 _ilk, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-ilk-line-precision" Fileable(_vat).file(_ilk, "line", _amount * MathLib.RAD); } /** @dev Increase a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to increase in DAI (ex. 10m DAI amount == 10000000) @param _global If true, increases the global debt ceiling by _amount */ function increaseIlkDebtCeiling(address _vat, bytes32 _ilk, uint256 _amount, bool _global) public { (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); setIlkDebtCeiling(_vat, _ilk, MathLib.add(line_ / MathLib.RAD, _amount)); if (_global) { increaseGlobalDebtCeiling(_vat, _amount); } } /** @dev Decrease a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) @param _global If true, decreases the global debt ceiling by _amount */ function decreaseIlkDebtCeiling(address _vat, bytes32 _ilk, uint256 _amount, bool _global) public { (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); setIlkDebtCeiling(_vat, _ilk, MathLib.sub(line_ / MathLib.RAD, _amount)); if (_global) { decreaseGlobalDebtCeiling(_vat, _amount); } } /** @dev Set the parameters for an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _iam The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The Maximum value (ex. 100m DAI amount == 100000000) @param _gap The amount of Dai per step (ex. 5m Dai == 5000000) @param _ttl The amount of time (in seconds) */ function setIlkAutoLineParameters(address _iam, bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-auto-line-amount-precision" require(_gap < MathLib.WAD); // "LibDssExec/incorrect-auto-line-gap-precision" IAMLike(_iam).setIlk(_ilk, _amount * MathLib.RAD, _gap * MathLib.RAD, _ttl); } /** @dev Set the debt ceiling for an ilk in the "MCD_IAM_AUTO_LINE" auto-line without updating the time values @param _iam The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) */ function setIlkAutoLineDebtCeiling(address _iam, bytes32 _ilk, uint256 _amount) public { (, uint256 gap, uint48 ttl,,) = IAMLike(_iam).ilks(_ilk); require(gap != 0 && ttl != 0); // "LibDssExec/auto-line-not-configured" IAMLike(_iam).setIlk(_ilk, _amount * MathLib.RAD, uint256(gap), uint256(ttl)); } /** @dev Remove an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _iam The address of the MCD_IAM_AUTO_LINE core accounting contract @param _ilk The ilk to remove (ex. bytes32("ETH-A")) */ function removeIlkFromAutoLine(address _iam, bytes32 _ilk) public { IAMLike(_iam).remIlk(_ilk); } /** @dev Set a collateral minimum vault amount. Amount will be converted to the correct internal precision. @param _vat The address of the Vat core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMinVaultAmount(address _vat, bytes32 _ilk, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-ilk-dust-precision" Fileable(_vat).file(_ilk, "dust", _amount * MathLib.RAD); } /** @dev Set a collateral liquidation penalty. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _cat The address of the Cat core accounting contract (will need to revisit for LIQ-2.0) @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 10.25% = 10.25 * 100 = 1025) */ function setIlkLiquidationPenalty(address _cat, bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 10 * MathLib.THOUSAND); // "LibDssExec/incorrect-ilk-chop-precision" Fileable(_cat).file(_ilk, "chop", MathLib.add(MathLib.WAD, MathLib.wdiv(_pct_bps, 10 * MathLib.THOUSAND))); } /** @dev Set max DAI amount for liquidation per vault for collateral. Amount will be converted to the correct internal precision. @param _cat The address of the Cat core accounting contract (will need to revisit for LIQ-2.0) @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMaxLiquidationAmount(address _cat, bytes32 _ilk, uint256 _amount) public { require(_amount < MathLib.WAD); // "LibDssExec/incorrect-ilk-dunk-precision" Fileable(_cat).file(_ilk, "dunk", _amount * MathLib.RAD); } /** @dev Set a collateral liquidation ratio. Amount will be converted to the correct internal precision. @dev Equation used for conversion is pct * RAY / 10,000 @param _spot The address of the Spot core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 150% = 150 * 100 = 15000) */ function setIlkLiquidationRatio(address _spot, bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 100 * MathLib.THOUSAND); // "LibDssExec/incorrect-ilk-mat-precision" // Fails if pct >= 1000% require(_pct_bps >= 10 * MathLib.THOUSAND); // the liquidation ratio has to be bigger or equal to 100% Fileable(_spot).file(_ilk, "mat", MathLib.rdiv(_pct_bps, 10 * MathLib.THOUSAND)); } /** @dev Set minimum bid increase for collateral. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _flip The address of the ilk's flip core accounting contract @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setIlkMinAuctionBidIncrease(address _flip, uint256 _pct_bps) public { require(_pct_bps < 10 * MathLib.THOUSAND); // "LibDssExec/incorrect-ilk-chop-precision" Fileable(_flip).file("beg", MathLib.add(MathLib.WAD, MathLib.wdiv(_pct_bps, 10 * MathLib.THOUSAND))); } /** @dev Set bid duration for a collateral type. @param _flip The address of the ilk's flip core accounting contract @param _duration Amount of time for bids. */ function setIlkBidDuration(address _flip, uint256 _duration) public { Fileable(_flip).file("ttl", _duration); } /** @dev Set auction duration for a collateral type. @param _flip The address of the ilk's flip core accounting contract @param _duration Amount of time for auctions. */ function setIlkAuctionDuration(address _flip, uint256 _duration) public { Fileable(_flip).file("tau", _duration); } /** @dev Set the stability fee for a given ilk. 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 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _jug The address of the Jug core accounting contract @param _ilk The ilk to update (ex. bytes32("ETH-A") ) @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) @param _doDrip `true` to accumulate stability fees for the collateral */ function setIlkStabilityFee(address _jug, bytes32 _ilk, uint256 _rate, bool _doDrip) public { require((_rate >= MathLib.RAY) && (_rate < 2 * MathLib.RAY)); // "LibDssExec/ilk-stability-fee-out-of-bounds" if (_doDrip) Drippable(_jug).drip(_ilk); Fileable(_jug).file(_ilk, "duty", _rate); } /***********************/ /*** Core Management ***/ /***********************/ /** @dev Update collateral auction contracts. @param _vat Vat core contract address @param _cat Cat core contract address @param _end End core contract address @param _flipperMom Flipper Mom core contract address @param _ilk The collateral's auction contract to update @param _newFlip New auction contract address @param _oldFlip Old auction contract address */ function updateCollateralAuctionContract( address _vat, address _cat, address _end, address _flipperMom, bytes32 _ilk, address _newFlip, address _oldFlip ) public { // Add new flip address to Cat setContract(_cat, _ilk, "flip", _newFlip); // Authorize MCD contracts from new flip authorize(_newFlip, _cat); authorize(_newFlip, _end); authorize(_newFlip, _flipperMom); // Authorize MCD contracts from old flip deauthorize(_oldFlip, _cat); deauthorize(_oldFlip, _end); deauthorize(_oldFlip, _flipperMom); // Transfer auction params from old flip to new flip Fileable(_newFlip).file("beg", AuctionLike(_oldFlip).beg()); Fileable(_newFlip).file("ttl", AuctionLike(_oldFlip).ttl()); Fileable(_newFlip).file("tau", AuctionLike(_oldFlip).tau()); // Sanity checks require(AuctionLike(_newFlip).ilk() == _ilk); // "non-matching-ilk" require(AuctionLike(_newFlip).vat() == _vat); // "non-matching-vat" } /** @dev Update surplus auction contracts. @param _vat Vat core contract address @param _vow Vow core contract address @param _newFlap New surplus auction contract address @param _oldFlap Old surplus auction contract address */ function updateSurplusAuctionContract(address _vat, address _vow, address _newFlap, address _oldFlap) public { // Add new flap address to Vow setContract(_vow, "flapper", _newFlap); // Authorize MCD contracts from new flap authorize(_newFlap, _vow); // Authorize MCD contracts from old flap deauthorize(_oldFlap, _vow); // Transfer auction params from old flap to new flap Fileable(_newFlap).file("beg", AuctionLike(_oldFlap).beg()); Fileable(_newFlap).file("ttl", AuctionLike(_oldFlap).ttl()); Fileable(_newFlap).file("tau", AuctionLike(_oldFlap).tau()); // Sanity checks require(AuctionLike(_newFlap).gem() == AuctionLike(_oldFlap).gem()); // "non-matching-gem" require(AuctionLike(_newFlap).vat() == _vat); // "non-matching-vat" } /** @dev Update debt auction contracts. @param _vat Vat core contract address @param _vow Vow core contract address @param _mkrAuthority MKRAuthority core contract address @param _newFlop New debt auction contract address @param _oldFlop Old debt auction contract address */ function updateDebtAuctionContract(address _vat, address _vow, address _mkrAuthority, address _newFlop, address _oldFlop) public { // Add new flop address to Vow setContract(_vow, "flopper", _newFlop); // Authorize MCD contracts for new flop authorize(_newFlop, _vow); authorize(_vat, _newFlop); authorize(_mkrAuthority, _newFlop); // Deauthorize MCD contracts for old flop deauthorize(_oldFlop, _vow); deauthorize(_vat, _oldFlop); deauthorize(_mkrAuthority, _oldFlop); // Transfer auction params from old flop to new flop Fileable(_newFlop).file("beg", AuctionLike(_oldFlop).beg()); Fileable(_newFlop).file("pad", AuctionLike(_oldFlop).pad()); Fileable(_newFlop).file("ttl", AuctionLike(_oldFlop).ttl()); Fileable(_newFlop).file("tau", AuctionLike(_oldFlop).tau()); // Sanity checks require(AuctionLike(_newFlop).gem() == AuctionLike(_oldFlop).gem()); // "non-matching-gem" require(AuctionLike(_newFlop).vat() == _vat); // "non-matching-vat" } /*************************/ /*** Oracle Management ***/ /*************************/ /** @dev Adds oracle feeds to the Median's writer whitelist, allowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to add to whitelist */ function addWritersToMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).lift(_feeds); } /** @dev Removes oracle feeds to the Median's writer whitelist, disallowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to remove from whitelist */ function removeWritersFromMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).drop(_feeds); } /** @dev Adds addresses to the Median's reader whitelist, allowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to add to whitelist */ function addReadersToMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).kiss(_readers); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to add to whitelist */ function addReaderToMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).kiss(_reader); } /** @dev Removes addresses from the Median's reader whitelist, disallowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to remove from whitelist */ function removeReadersFromMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).diss(_readers); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to remove from whitelist */ function removeReaderFromMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).diss(_reader); } /** @dev Sets the minimum number of valid messages from whitelisted oracle feeds needed to update median price. @param _median Median core contract address @param _minQuorum Minimum number of valid messages from whitelisted oracle feeds needed to update median price (NOTE: MUST BE ODD NUMBER) */ function setMedianWritersQuorum(address _median, uint256 _minQuorum) public { OracleLike_2(_median).setBar(_minQuorum); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to add to whitelist */ function addReaderToOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).kiss(_reader); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to remove from whitelist */ function removeReaderFromOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).diss(_reader); } /** @dev Add OSM address to OSM mom, allowing it to be frozen by governance. @param _osmMom OSM Mom core contract address @param _osm Oracle Security Module (OSM) core contract address @param _ilk Collateral type using OSM */ function allowOSMFreeze(address _osmMom, address _osm, bytes32 _ilk) public { MomLike(_osmMom).setOsm(_ilk, _osm); } /*****************************/ /*** Collateral Onboarding ***/ /*****************************/ /** @dev Performs basic functions and sanity checks to add a new collateral type to the MCD system @param _vat MCD_VAT @param _cat MCD_CAT @param _jug MCD_JUG @param _end MCD_END @param _spot MCD_SPOT @param _reg ILK_REGISTRY @param _ilk Collateral type key code [Ex. "ETH-A"] @param _gem Address of token contract @param _join Address of join adapter @param _flip Address of flipper @param _pip Address of price feed */ function addCollateralBase( address _vat, address _cat, address _jug, address _end, address _spot, address _reg, bytes32 _ilk, address _gem, address _join, address _flip, address _pip ) public { // Sanity checks require(JoinLike_2(_join).vat() == _vat); // "join-vat-not-match" require(JoinLike_2(_join).ilk() == _ilk); // "join-ilk-not-match" require(JoinLike_2(_join).gem() == _gem); // "join-gem-not-match" require(JoinLike_2(_join).dec() == ERC20(_gem).decimals()); // "join-dec-not-match" require(AuctionLike(_flip).vat() == _vat); // "flip-vat-not-match" require(AuctionLike(_flip).cat() == _cat); // "flip-cat-not-match" require(AuctionLike(_flip).ilk() == _ilk); // "flip-ilk-not-match" // Set the token PIP in the Spotter setContract(_spot, _ilk, "pip", _pip); // Set the ilk Flipper in the Cat setContract(_cat, _ilk, "flip", _flip); // Init ilk in Vat & Jug Initializable(_vat).init(_ilk); // Vat Initializable(_jug).init(_ilk); // Jug // Allow ilk Join to modify Vat registry authorize(_vat, _join); // Allow the ilk Flipper to reduce the Cat litterbox on deal() authorize(_cat, _flip); // Allow Cat to kick auctions in ilk Flipper authorize(_flip, _cat); // Allow End to yank auctions in ilk Flipper authorize(_flip, _end); // Add new ilk to the IlkRegistry RegistryLike_2(_reg).add(_join); } }
--- SafeMath Functions ---
library MathLib { uint256 constant public WAD = 10 ** 18; uint256 constant public RAY = 10 ** 27; uint256 constant public RAD = 10 ** 45; uint256 constant public THOUSAND = 10 ** 3; uint256 constant public MILLION = 10 ** 6; pragma solidity >=0.6.11 <0.7.0; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } 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; } }
2,118,489
[ 1, 6062, 14060, 10477, 15486, 9948, 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, 12083, 2361, 5664, 288, 203, 203, 565, 2254, 5034, 5381, 1071, 678, 1880, 1377, 273, 1728, 2826, 6549, 31, 203, 565, 2254, 5034, 5381, 1071, 534, 5255, 1377, 273, 1728, 2826, 12732, 31, 203, 565, 2254, 5034, 5381, 1071, 534, 1880, 1377, 273, 1728, 2826, 12292, 31, 203, 565, 2254, 5034, 5381, 1071, 7662, 21667, 4307, 273, 1728, 2826, 890, 31, 203, 565, 2254, 5034, 5381, 1071, 490, 15125, 1146, 225, 273, 1728, 2826, 1666, 31, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 2499, 411, 20, 18, 27, 18, 20, 31, 203, 203, 565, 445, 527, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 2583, 12443, 94, 273, 619, 397, 677, 13, 1545, 619, 1769, 203, 565, 289, 203, 565, 445, 720, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 2583, 12443, 94, 273, 619, 300, 677, 13, 1648, 619, 1769, 203, 565, 289, 203, 565, 445, 14064, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 2583, 12, 93, 422, 374, 747, 261, 94, 273, 619, 380, 677, 13, 342, 677, 422, 619, 1769, 203, 565, 289, 203, 565, 445, 341, 16411, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 998, 273, 527, 12, 16411, 12, 92, 16, 677, 3631, 678, 1880, 342, 576, 13, 342, 678, 1880, 31, 203, 565, 289, 203, 2 ]
./full_match/1/0x666E6748db572ebC3AE40e4Ce7748bC9bE7A5AAe/sources/Users/kstasi/Documents/side/dANT/contracts/RewardsType2.sol
@dev Returns user's unclaimed reward. @param _includeDeposit Should the finnished deposits be included into calculations. @return _reward User's reward.
function getPendingReward(address _user, bool _includeDeposit) public override view returns (uint256 _reward) { UserInfo storage user = userInfo[_user]; _reward = now .sub(user.lastUpdate) .mul(user.amount) .mul(rewardPerSec) .div(1e18); if (_includeDeposit) { for ( uint256 requestId = requestHead[_user]; requestId < unstakeRequests[_user].length; requestId++ ) { Request storage request = unstakeRequests[_user][requestId]; if ( request.timelock < now && request.status == Status.PENDING ) { _reward = _reward.add(request.amount); } } } }
4,935,826
[ 1, 1356, 729, 1807, 6301, 80, 4581, 329, 19890, 18, 225, 389, 6702, 758, 1724, 9363, 326, 574, 82, 5992, 443, 917, 1282, 506, 5849, 1368, 20882, 18, 327, 389, 266, 2913, 2177, 1807, 19890, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 1689, 2846, 17631, 1060, 12, 2867, 389, 1355, 16, 1426, 389, 6702, 758, 1724, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 389, 266, 2913, 13, 203, 565, 288, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 1355, 15533, 203, 3639, 389, 266, 2913, 273, 2037, 203, 5411, 263, 1717, 12, 1355, 18, 2722, 1891, 13, 203, 5411, 263, 16411, 12, 1355, 18, 8949, 13, 203, 5411, 263, 16411, 12, 266, 2913, 2173, 2194, 13, 203, 5411, 263, 2892, 12, 21, 73, 2643, 1769, 203, 3639, 309, 261, 67, 6702, 758, 1724, 13, 288, 203, 5411, 364, 261, 203, 7734, 2254, 5034, 14459, 273, 590, 1414, 63, 67, 1355, 15533, 203, 7734, 14459, 411, 640, 334, 911, 6421, 63, 67, 1355, 8009, 2469, 31, 203, 7734, 14459, 9904, 203, 5411, 262, 288, 203, 7734, 1567, 2502, 590, 273, 640, 334, 911, 6421, 63, 67, 1355, 6362, 2293, 548, 15533, 203, 7734, 309, 261, 203, 10792, 590, 18, 8584, 292, 975, 411, 2037, 597, 590, 18, 2327, 422, 2685, 18, 25691, 203, 7734, 262, 288, 203, 10792, 389, 266, 2913, 273, 389, 266, 2913, 18, 1289, 12, 2293, 18, 8949, 1769, 203, 7734, 289, 203, 5411, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./ERC721.sol"; import "./utils/Ownable.sol"; import "./utils/NameUtils.sol"; import "./utils/ReentrancyGuard.sol"; import "./utils/Base64.sol"; import "./chainlink/VRFConsumerBase.sol"; /** * @title The Greats Contract (Codenamed: Canary) * @dev Extends OpenZeppelin's ERC721 implementation */ contract Canary is ERC721, Ownable, ReentrancyGuard, VRFConsumerBase { using Strings for uint256; using Address for address; // Global variables // Constants /// @dev Invariant: MAX_SUPPLY to be an even number uint256 public constant MAX_SUPPLY = 4608; uint256 public constant RESERVE_PRICE = 3 * (10 ** 18); uint256 public constant STEEP_CURVE_PERIOD = 86400; uint256 public constant GENERAL_CURVE_PERIOD = 7 * 86400; uint256 public constant NAME_CHANGE_PRICE = 100000 * (10 ** 18); uint16[18] public DEVMINT_METADATA_INDICES = [5, 618, 814, 2291, 2342, 2410, 3140, 4035, 4372, 4499, 1818, 111, 1274, 2331, 2885, 3369, 4268, 4589]; // Artist Attestation Metadata string public constant ARTIST_ATTESTATION_METADATA = "ipfs://QmVeJyaLh44i2VsePHbwHaQT89SetXGKstZrjx38sjKGhL"; // Metadata Variables /** * @dev There is a predetermined sequence of metadata that 1-1 corresponds to the index on IPFS and Arweave directories * Our randomization mechanism works by assigning the token ID with a certain metadata index in a randomized fashion */ string public imageIPFSURIPrefix = "ipfs://QmWWMp4Srk6CC9nuGw7fJz6BfxNw7xT7QBHTtxFVRjQTzU/"; string public imageArweaveURIPrefix = "ar://placeholder/"; string public galleryIPFSURIPrefix = "ipfs://QmRv3YCXRYx3v36btcKGnuAXKFqjiWQPW7bGUHWKb9GWGv/"; string public physicalSpecificationsIPFSURIPrefix = "ipfs://QmNSsUw8Z3H5z2FroCwVVZ32vye9RF3QJKejiFLEnn4pik/"; mapping(uint256 => bool) public metadataAssigned; mapping(uint256 => uint256) public tokenIdToMetadataIndex; // Sale variables uint256 public immutable STEEP_CURVE_STARTING_PRICE; uint256 public immutable GENERAL_CURVE_STARTING_PRICE; uint256 public immutable HASHMASKS_DISCOUNT; address public immutable HASHMASKS_ADDRESS; uint256 public SALE_START; bool public salePaused = false; uint256 public FINAL_SETTLEMENT_PRICE = 0; uint256 public SETTLEMENT_PRICE_SET_TIMESTAMP = 0; mapping(address => uint256) public addressToBidExcludingDiscount; // Chainlink and Randomization mapping(bytes32 => uint256) public requestIdToFirstMintIdInBatch; bytes32 internal keyHash; uint256 internal fee; uint256[MAX_SUPPLY] internal indices; uint256 internal indicesAssigned = 0; // Naming address public immutable NCT_ADDRESS; mapping(uint256 => string) public tokenName; mapping(string => bool) private nameReserved; /// @dev The era and subera traits are determined based on the index number of the original metadata sequence uint256[7] public eraStartIndices = [0, 6, 814, 1847, 2540, 3518, 4372]; /// @notice Name of the Eras in the same order as eraStartIndices string[7] public eraNames = ["High Renaissance", "Post-Impressionism", "Surrealism", "Cubism", "Pop Art", "Factory Art", "Beltracchi"]; uint256[33] public subEraStartIndices = [ 0, 1, 6, 270, 440, 610, 814, 1847, 2291, 2321, 2342, 2362, 2410, 2539, 2540, 2790, 3040, 3140, 3240, 3518, 3668, 3828, 3956, 4212, 4372, 4410, 4481, 4510, 4537, 4574, 4581, 4594, 4605 ]; /// @notice Name of the Eras in the same order as eraStartIndices string[33] public subEraNames = [ "Rebirth", "Umbra", "Starry", "Wheatfield", "Olive Trees", "The Room", "The Gambit of Salvator Mundi in the Desert Ocean", "Synthetic Vantage", "Synthetic Limited", "Mephisto Voodoo", "Mephisto Plague", "Mephisto Nimbus", "Analytical", "Foundation", "Nubian", "Light", "Moon", "Vietnam", "Far East", "The Guru", "Unicolor", "Duality", "Solitude", "Angelic", "Storming of Jerusalem", "The Witches", "Sieben Schalen der Apokalypse", "Feathers", "Comet", "Gold", "Angel's Hymn", "Fallen Angels", "Crimson Angel" ]; /// Events event NameChange(uint256 indexed tokenId, string newName); event MetadataAssigned(uint256 indexed tokenId, uint256 indexed metadataIndex); event Mint(uint256 indexed tokenId, uint256 price); event RequestedRandomness(bytes32 requestId); constructor( string memory name, string memory symbol, uint256 steepCurveStartingPrice, uint256 generalCurveStartingPrice, address nctAddress, address hashmasksAddress, uint256 hashmasksDiscount, address vrfCoordinator, address linkToken, uint256 chainlinkFee, bytes32 chainlinkKeyHash ) VRFConsumerBase( vrfCoordinator, // VRF Coordinator linkToken // LINK Token ) ERC721(name, symbol) { require(RESERVE_PRICE > hashmasksDiscount, "Reserve price must be higher than the discount"); require(steepCurveStartingPrice > generalCurveStartingPrice, "steepCurveStartingPrice is invalid"); require(generalCurveStartingPrice > RESERVE_PRICE, "generalCurveStartingPrice is invalid"); STEEP_CURVE_STARTING_PRICE = steepCurveStartingPrice; GENERAL_CURVE_STARTING_PRICE = generalCurveStartingPrice; NCT_ADDRESS = nctAddress; HASHMASKS_ADDRESS = hashmasksAddress; HASHMASKS_DISCOUNT = hashmasksDiscount; // Chainlink keyHash = chainlinkKeyHash; fee = chainlinkFee; } // Public Functions /** * @notice Calculates the current bid price * @dev There are basically two price curves. The steep price curve drops from STEEP_CURVE_STARTING_PRICE TO * GENERAL_CURVE_STARTING_PRICE in STEEP_CURVE_PERIOD time. After that period, the other curve immediately starts * and drops from GENERAL_CURVE_STARTING_PRICE to RESERVE_PRICE in GENERAL_CURVE_PERIOD time * @return Current bid price including any discount * @return Current bid price which doesn't include any discount (Ordinary bid price) */ function getCurrentBidPriceDetails() public view returns (uint256, uint256) { uint256 elapsed = block.timestamp - SALE_START; uint256 ordinaryPrice = 0; if (elapsed >= STEEP_CURVE_PERIOD + GENERAL_CURVE_PERIOD) { ordinaryPrice = RESERVE_PRICE; } else { if (elapsed < STEEP_CURVE_PERIOD) { uint256 priceDrop = ((STEEP_CURVE_STARTING_PRICE - GENERAL_CURVE_STARTING_PRICE) * elapsed) / STEEP_CURVE_PERIOD; ordinaryPrice = max(GENERAL_CURVE_STARTING_PRICE, STEEP_CURVE_STARTING_PRICE - priceDrop); } else { // STEEP_CURVE_PERIOD is subtracted from elapsed to account for the former curve period uint256 priceDrop = ((GENERAL_CURVE_STARTING_PRICE - RESERVE_PRICE) * (elapsed - STEEP_CURVE_PERIOD)) / GENERAL_CURVE_PERIOD; ordinaryPrice = max(RESERVE_PRICE, GENERAL_CURVE_STARTING_PRICE - priceDrop); } } uint256 discount = 0; if (ERC721(HASHMASKS_ADDRESS).balanceOf(msg.sender) > 0) { discount = HASHMASKS_DISCOUNT; } // If the discount is greater than or equal to the ordinary price if (discount >= ordinaryPrice) { return (0, ordinaryPrice); } else { return (ordinaryPrice - discount, ordinaryPrice); } } /// @notice Returns integer that represents the era corresponding to the tokenId function getTokenEra(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "Token ID does not exist"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); uint256 metadataIndex = tokenIdToMetadataIndex[tokenId]; for (uint256 i = eraStartIndices.length - 1; i >= 0; i--) { if (metadataIndex >= eraStartIndices[i]) { return i; } } } /// @notice Returns the era name corresponding to the tokenId function getTokenEraName(uint256 tokenId) public view returns (string memory) { uint256 tokenEra = getTokenEra(tokenId); return eraNames[tokenEra]; } /// @notice Returns integer that represents the sub era corresponding to the tokenId function getTokenSubEra(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "Token ID does not exist"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); uint256 metadataIndex = tokenIdToMetadataIndex[tokenId]; for (uint256 i = subEraStartIndices.length - 1; i >= 0; i--) { if (metadataIndex >= subEraStartIndices[i]) { return i; } } } /// @notice Returns the sub era name corresponding to the tokenId function getTokenSubEraName(uint256 tokenId) public view returns (string memory) { uint256 tokenSubEra = getTokenSubEra(tokenId); return subEraNames[tokenSubEra]; } /// @inheritdoc ERC721 /// @notice Returns Base64 encoded JSON metadata for the given tokenId function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); string memory namePostfix = '"'; if (bytes(tokenName[tokenId]).length != 0) { namePostfix = string(abi.encodePacked(': ', tokenName[tokenId], '"')); } // Block scoping to avoid stack too deep error bytes memory uriPartsOfMetadata; { uriPartsOfMetadata = abi.encodePacked( ', "image": "', string(abi.encodePacked(baseURI(), tokenIdToMetadataIndex[tokenId].toString(), '.jpeg')), '", "image_arweave_uri": "', string( abi.encodePacked( imageArweaveURIPrefix, tokenIdToMetadataIndex[tokenId].toString(), '.jpeg' ) ), '", "gallery_glb_uri": "', string(abi.encodePacked(galleryIPFSURIPrefix, getTokenEra(tokenId).toString(), '.glb')) ); } return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name": "Mundi #', tokenId.toString(), namePostfix, ', "description": "The Greats Collection", "attributes": [{ "trait_type": "Era", "value": "', getTokenEraName(tokenId), '"}, { "trait_type": "Sub Era", "value": "', getTokenSubEraName(tokenId), '"}], "physical_specifications_uri": "', string(abi.encodePacked(physicalSpecificationsIPFSURIPrefix, getTokenSubEra(tokenId).toString(), '.json"')), uriPartsOfMetadata, '" }' ) ) ) ); } /// @inheritdoc ERC721 function baseURI() public view virtual override returns (string memory) { return imageIPFSURIPrefix; } /// @notice Returns if the name has been reserved already (Case insensitive) function isNameReserved(string memory name) public view returns (bool) { return nameReserved[NameUtils.toLower(name)]; } // External Functions /// @notice Mints initial tokens for the purpose of auctioning off function devMint() external onlyOwner { require(totalSupply() < DEVMINT_METADATA_INDICES.length, "Dev minting already done"); require(SALE_START == 0, "Sale has already started"); for (uint256 i = 0; i < DEVMINT_METADATA_INDICES.length; i++) { uint256 mintIndex = MAX_SUPPLY - i - 1; _safeMint(msg.sender, mintIndex); emit Mint(mintIndex, 0); assignMetadataIndexToTokenId(mintIndex, assignIndexWithSeed(DEVMINT_METADATA_INDICES[i])); } // Even number post condition (For Chainlink batching consistency) require(totalSupply() % 2 == 0, "Dev mint number must be even"); } /* * @notice Mints a token for a bid at the current price. * A portion of the bid may be refunded based on the final settlement price * @dev Minted token is revealed (assigned metadata) after the chainlink callback (Done in batches of two) * Known: There would be a reveal delay of next token mint + Chainlink callback time if the token id is even * Smart contracts are prevented from minting */ function mint() external payable nonReentrant { require(msg.sender == tx.origin, "Minter cannot be a contract"); require(totalSupply() < MAX_SUPPLY, "Sale ended"); require(addressToBidExcludingDiscount[msg.sender] == 0, "Only one token mintable per address if RESERVE_PRICE is not reached"); require(SALE_START != 0 && block.timestamp >= SALE_START, "Sale has not started"); require(!salePaused, "Sale is paused"); // Transfer any remaining Ether back to the minter (uint256 currentBidPrice, uint256 nonDiscountedBidPrice) = getCurrentBidPriceDetails(); require(msg.value >= currentBidPrice, "Insufficient funds"); uint256 mintIndex = totalSupply() - DEVMINT_METADATA_INDICES.length; // Offset for dev mints _safeMint(msg.sender, mintIndex); if (totalSupply() % 2 == 0) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract"); bytes32 requestId = requestRandomness(keyHash, fee); requestIdToFirstMintIdInBatch[requestId] = mintIndex - 1; emit RequestedRandomness(requestId); } emit Mint(mintIndex, currentBidPrice); if (FINAL_SETTLEMENT_PRICE == 0) { // Set final settlement price if it's last mint or if the price curve period has ended if (totalSupply() == MAX_SUPPLY || nonDiscountedBidPrice == RESERVE_PRICE) { FINAL_SETTLEMENT_PRICE = nonDiscountedBidPrice; SETTLEMENT_PRICE_SET_TIMESTAMP = block.timestamp; } else { // It's only considered a bid if the final settlement price is not reached addressToBidExcludingDiscount[msg.sender] = nonDiscountedBidPrice; } } // Return back the remaining Ether if (msg.value > currentBidPrice) { payable(msg.sender).transfer(msg.value - currentBidPrice); } } /// @notice Change name of the given token ID. Cannot be re-named /// @dev The caller needs to have given sufficient allowance on NCT to this contract function changeName(uint256 tokenId, string memory name) external nonReentrant { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(NameUtils.validateName(name) == true, "Not a valid new name"); require(bytes(tokenName[tokenId]).length == 0, "Token ID is already named"); require(isNameReserved(name) == false, "Name is already reserved"); IERC20(NCT_ADDRESS).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); tokenName[tokenId] = name; nameReserved[NameUtils.toLower(name)] = true; IERC20(NCT_ADDRESS).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, name); } /// @notice Refund the difference between the bid by the given address and the settlement price function refundDifferenceToBidders(address[] memory bidderAddresses) external nonReentrant { require(FINAL_SETTLEMENT_PRICE > 0, "Settlement price not set"); for (uint256 i = 0; i < bidderAddresses.length; i++) { uint256 bidAmountExcludingDiscount = addressToBidExcludingDiscount[bidderAddresses[i]]; if (bidAmountExcludingDiscount != 0) { addressToBidExcludingDiscount[bidderAddresses[i]] = 0; payable(bidderAddresses[i]).transfer( bidAmountExcludingDiscount - FINAL_SETTLEMENT_PRICE ); } } } /* * @dev Withdraw ether from this contract (Callable by owner) * 3 days grace period for anyone to be able to refund difference to the bidders as a way to minimize trust in the contract owner. * Callable 3 days after the settlement price is set or 3 days after the general curve period ends */ function withdraw() external onlyOwner { require( (SETTLEMENT_PRICE_SET_TIMESTAMP != 0 && block.timestamp > SETTLEMENT_PRICE_SET_TIMESTAMP + 3 days) || (block.timestamp > SALE_START + STEEP_CURVE_PERIOD + GENERAL_CURVE_PERIOD + 3 days), "Atleast 3 days must pass after settlement price is set or after the general curve period ends" ); uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /// @notice saleStartTimestamp param is ignored if sale start timestamp is already set /// @dev Starts / resumes / pauses the sale based on the state (Callable by owner) function toggleSale(uint256 saleStartTimestamp) external onlyOwner { require(totalSupply() < MAX_SUPPLY, "Sale has ended"); if (SALE_START == 0) { require(saleStartTimestamp >= block.timestamp, "saleStartTimestamp is in the past"); SALE_START = saleStartTimestamp; } else { salePaused = !salePaused; } } /// @dev Metadata will be frozen once ownership of the contract is renounced function changeURIs( string memory imageURI, string memory imageArweaveURI, string memory galleryURI, string memory physicalSpecsURI ) external onlyOwner { imageIPFSURIPrefix = imageURI; imageArweaveURIPrefix = imageArweaveURI; galleryIPFSURIPrefix = galleryURI; physicalSpecificationsIPFSURIPrefix = physicalSpecsURI; } // Internal Functions /// @dev Callback function used by VRF Coordinator. Assigns metadata to the tokens in a batch of two function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint256 firstMintIdInBatch = requestIdToFirstMintIdInBatch[requestId]; uint256[2] memory mintIdsToAssign = [firstMintIdInBatch, firstMintIdInBatch + 1]; for (uint256 i = 0; i < mintIdsToAssign.length; i++) { require(metadataAssigned[mintIdsToAssign[i]] == false, "Metadata already assigned"); uint256 metadataIndex = assignIndexWithSeed( uint256(keccak256(abi.encode(randomness, i))) ); assignMetadataIndexToTokenId(mintIdsToAssign[i], metadataIndex); } } /// @dev Assigns metadata index to token id function assignMetadataIndexToTokenId(uint256 tokenId, uint256 metadataIndex) internal { tokenIdToMetadataIndex[tokenId] = metadataIndex; metadataAssigned[tokenId] = true; emit MetadataAssigned(tokenId, metadataIndex); } /// @dev Generates a random index using the seed and stores it in a mapping for 0(1) complexity in case of repetition function assignIndexWithSeed(uint256 seed) internal returns (uint256) { uint256 totalSize = MAX_SUPPLY - indicesAssigned; uint256 index = seed % totalSize; // Credits to Meebits for the following snippet uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } // Move last value to selected position if (indices[totalSize - 1] == 0) { // 2 -> indices[2] = 999. indices[1] = 999 // Array position not initialized, so use position indices[index] = totalSize - 1; } else { // Array position holds a value so use that indices[index] = indices[totalSize - 1]; } indicesAssigned++; return value; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.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() { _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; } } pragma solidity ^0.8.0; import "./Context.sol"; contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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.8.0; /** * @dev Collection of utils functions related to on-chain naming */ library NameUtils { /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) internal pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) internal pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // 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; /** * @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; if (lastIndex != toDeleteIndex) { 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] = valueIndex; // Replace lastvalue's index to valueIndex } // 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) { 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.8.0; import "./EnumerableSet.sol"; /** * @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 { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // 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.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 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) { 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 Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 "./SafeMathChainlink.sol"; import "./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 { using SafeMathChainlink for uint256; /** * @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].add(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; /** * @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 SafeMathChainlink { /** * @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; } } // 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; /** * @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; 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/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; /** * @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); /** * TODO: Add comment */ function burn(uint256 burnQuantity) 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 "./utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "./utils/ERC165.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 Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // 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; /** * @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 || interfaceId == type(IERC721Enumerable).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 _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()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _approve(address to, uint256 tokenId) private { _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 { } }
@notice Mints a token for a bid at the current price. A portion of the bid may be refunded based on the final settlement price @dev Minted token is revealed (assigned metadata) after the chainlink callback (Done in batches of two) Known: There would be a reveal delay of next token mint + Chainlink callback time if the token id is even Smart contracts are prevented from minting/ Transfer any remaining Ether back to the minter Set final settlement price if it's last mint or if the price curve period has ended It's only considered a bid if the final settlement price is not reached Return back the remaining Ether
function mint() external payable nonReentrant { require(msg.sender == tx.origin, "Minter cannot be a contract"); require(totalSupply() < MAX_SUPPLY, "Sale ended"); require(addressToBidExcludingDiscount[msg.sender] == 0, "Only one token mintable per address if RESERVE_PRICE is not reached"); require(SALE_START != 0 && block.timestamp >= SALE_START, "Sale has not started"); require(!salePaused, "Sale is paused"); (uint256 currentBidPrice, uint256 nonDiscountedBidPrice) = getCurrentBidPriceDetails(); require(msg.value >= currentBidPrice, "Insufficient funds"); _safeMint(msg.sender, mintIndex); if (totalSupply() % 2 == 0) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract"); bytes32 requestId = requestRandomness(keyHash, fee); requestIdToFirstMintIdInBatch[requestId] = mintIndex - 1; emit RequestedRandomness(requestId); } emit Mint(mintIndex, currentBidPrice); if (FINAL_SETTLEMENT_PRICE == 0) { if (totalSupply() == MAX_SUPPLY || nonDiscountedBidPrice == RESERVE_PRICE) { FINAL_SETTLEMENT_PRICE = nonDiscountedBidPrice; SETTLEMENT_PRICE_SET_TIMESTAMP = block.timestamp; addressToBidExcludingDiscount[msg.sender] = nonDiscountedBidPrice; } } if (msg.value > currentBidPrice) { payable(msg.sender).transfer(msg.value - currentBidPrice); } }
9,976,510
[ 1, 49, 28142, 279, 1147, 364, 279, 9949, 622, 326, 783, 6205, 18, 225, 432, 14769, 434, 326, 9949, 2026, 506, 1278, 12254, 2511, 603, 326, 727, 26319, 806, 6205, 282, 490, 474, 329, 1147, 353, 283, 537, 18931, 261, 15938, 1982, 13, 1839, 326, 2687, 1232, 1348, 261, 7387, 316, 13166, 434, 2795, 13, 225, 30036, 30, 6149, 4102, 506, 279, 283, 24293, 4624, 434, 1024, 1147, 312, 474, 397, 7824, 1232, 1348, 813, 309, 326, 1147, 612, 353, 5456, 225, 19656, 20092, 854, 5309, 329, 628, 312, 474, 310, 19, 12279, 1281, 4463, 512, 1136, 1473, 358, 326, 1131, 387, 1000, 727, 26319, 806, 6205, 309, 518, 1807, 1142, 312, 474, 578, 309, 326, 6205, 8882, 3879, 711, 16926, 2597, 1807, 1338, 7399, 279, 9949, 309, 326, 727, 26319, 806, 6205, 353, 486, 8675, 2000, 1473, 326, 4463, 512, 1136, 2, 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, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 1435, 3903, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2229, 18, 10012, 16, 315, 49, 2761, 2780, 506, 279, 6835, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 4552, 67, 13272, 23893, 16, 315, 30746, 16926, 8863, 203, 3639, 2583, 12, 2867, 774, 17763, 424, 18596, 9866, 63, 3576, 18, 15330, 65, 422, 374, 16, 315, 3386, 1245, 1147, 312, 474, 429, 1534, 1758, 309, 2438, 2123, 3412, 67, 7698, 1441, 353, 486, 8675, 8863, 203, 3639, 2583, 12, 5233, 900, 67, 7570, 480, 374, 597, 1203, 18, 5508, 1545, 17127, 900, 67, 7570, 16, 315, 30746, 711, 486, 5746, 8863, 203, 3639, 2583, 12, 5, 87, 5349, 28590, 16, 315, 30746, 353, 17781, 8863, 203, 203, 3639, 261, 11890, 5034, 783, 17763, 5147, 16, 2254, 5034, 1661, 9866, 329, 17763, 5147, 13, 273, 5175, 17763, 5147, 3790, 5621, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 783, 17763, 5147, 16, 315, 5048, 11339, 284, 19156, 8863, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 312, 474, 1016, 1769, 203, 203, 3639, 309, 261, 4963, 3088, 1283, 1435, 738, 576, 422, 374, 13, 288, 203, 5411, 2583, 12, 10554, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 14036, 16, 315, 1248, 7304, 22926, 300, 3636, 6835, 8863, 203, 5411, 1731, 1578, 14459, 273, 590, 8529, 4496, 12, 856, 2310, 16, 14036, 1769, 203, 5411, 14459, 774, 3759, 49, 474, 548, 382, 4497, 63, 2293, 548, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-20 */ // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.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); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.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. */ 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @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"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @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 ERC20;` 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 { // 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length 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"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @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. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol 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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @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 {ERC20MinterPauser}. * * 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 Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 is 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 { _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; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol pragma solidity ^0.6.0; /** * @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. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.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]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/interface/IKyberNetworkProxy.sol pragma solidity 0.6.2; interface IKyberNetworkProxy { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function swapEtherToToken(ERC20 token, uint minConversionRate) external payable returns(uint); function swapTokenToEther(ERC20 token, uint tokenQty, uint minRate) external payable returns(uint); function swapTokenToToken(ERC20 src, uint srcAmount, ERC20 dest, uint minRate) external returns(uint); } // File: contracts/interface/IKyberStaking.sol pragma solidity 0.6.2; interface IKyberStaking { function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function getLatestStakeBalance(address staker) external view returns(uint); } // File: contracts/interface/IKyberDAO.sol pragma solidity 0.6.2; interface IKyberDAO { function submitVote(uint256 proposalId, uint256 optionBitMask) external; } // File: contracts/interface/IKyberFeeHandler.sol pragma solidity 0.6.2; interface IKyberFeeHandler { function claimStakerReward( address staker, uint256 epoch ) external returns(uint256 amountWei); } // File: contracts/interface/INewKNC.sol pragma solidity 0.6.2; interface INewKNC { function mintWithOldKnc(uint256 amount) external; } // File: contracts/interface/IRewardsDistributor.sol pragma solidity 0.6.2; interface IRewardsDistributor { function claim( uint256 cycle, uint256 index, address user, IERC20[] calldata tokens, uint256[] calldata cumulativeAmounts, bytes32[] calldata merkleProof ) external returns (uint256[] memory claimAmounts); } // File: contracts/xKNC.sol pragma solidity 0.6.2; /* * xKNC KyberDAO Pool Token * Communal Staking Pool with Stated Governance Position */ contract xKNC is Initializable, ERC20, OwnableUpgradeSafe, PausableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for ERC20; address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ERC20 private knc; IKyberDAO private kyberDao; IKyberStaking private kyberStaking; IKyberNetworkProxy private kyberProxy; IKyberFeeHandler[] private kyberFeeHandlers; address[] private kyberFeeTokens; uint256 private constant PERCENT = 100; uint256 private constant MAX_UINT = 2**256 - 1; uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10; uint256 private withdrawableEthFees; uint256 private withdrawableKncFees; string public mandate; address private manager; address private manager2; struct FeeDivisors { uint256 mintFee; uint256 burnFee; uint256 claimFee; } FeeDivisors public feeDivisors; event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee); enum FeeTypes {MINT, BURN, CLAIM} // vars added for v3 bool private v3Initialized; IRewardsDistributor private rewardsDistributor; function initialize( string memory _symbol, string memory _mandate, IKyberStaking _kyberStaking, IKyberNetworkProxy _kyberProxy, ERC20 _knc, IKyberDAO _kyberDao, uint256 mintFee, uint256 burnFee, uint256 claimFee ) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC20_init_unchained("xKNC", _symbol); mandate = _mandate; kyberStaking = _kyberStaking; kyberProxy = _kyberProxy; knc = _knc; kyberDao = _kyberDao; _setFeeDivisors(mintFee, burnFee, claimFee); } /* * @notice Called by users buying with ETH * @dev Swaps ETH for KNC, deposits to Staking contract * @dev: Mints pro rata xKNC tokens * @param: kyberProxy.getExpectedRate(eth => knc) */ function mint(uint256 minRate) external payable whenNotPaused { require(msg.value > 0, "Must send eth with tx"); // ethBalBefore checked in case of eth still waiting for exch to KNC uint256 ethBalBefore = getFundEthBalanceWei().sub(msg.value); uint256 fee = _administerEthFee(FeeTypes.MINT, ethBalBefore); uint256 ethValueForKnc = msg.value.sub(fee); uint256 kncBalanceBefore = getFundKncBalanceTwei(); _swapEtherToKnc(ethValueForKnc, minRate); _deposit(getAvailableKncBalanceTwei()); uint256 mintAmount = _calculateMintAmount(kncBalanceBefore); return super._mint(msg.sender, mintAmount); } /* * @notice Called by users buying with KNC * @notice Users must submit ERC20 approval before calling * @dev Deposits to Staking contract * @dev: Mints pro rata xKNC tokens * @param: Number of KNC to contribue */ function mintWithToken(uint256 kncAmountTwei) external whenNotPaused { require(kncAmountTwei > 0, "Must contribute KNC"); knc.safeTransferFrom(msg.sender, address(this), kncAmountTwei); uint256 kncBalanceBefore = getFundKncBalanceTwei(); _administerKncFee(kncAmountTwei, FeeTypes.MINT); _deposit(getAvailableKncBalanceTwei()); uint256 mintAmount = _calculateMintAmount(kncBalanceBefore); return super._mint(msg.sender, mintAmount); } /* * @notice Called by users burning their xKNC * @dev Calculates pro rata KNC and redeems from Staking contract * @dev: Exchanges for ETH if necessary and pays out to caller * @param tokensToRedeem * @param redeemForKnc bool: if true, redeem for KNC; otherwise ETH * @param kyberProxy.getExpectedRate(knc => eth) */ function burn( uint256 tokensToRedeemTwei, bool redeemForKnc, uint256 minRate ) external nonReentrant { require( balanceOf(msg.sender) >= tokensToRedeemTwei, "Insufficient balance" ); uint256 proRataKnc = getFundKncBalanceTwei().mul(tokensToRedeemTwei).div(totalSupply()); _withdraw(proRataKnc); super._burn(msg.sender, tokensToRedeemTwei); if (redeemForKnc) { uint256 fee = _administerKncFee(proRataKnc, FeeTypes.BURN); knc.safeTransfer(msg.sender, proRataKnc.sub(fee)); } else { // safeguard to not overcompensate _burn sender in case eth still awaiting for exch to KNC uint256 ethBalBefore = getFundEthBalanceWei(); kyberProxy.swapTokenToEther( knc, getAvailableKncBalanceTwei(), minRate ); _administerEthFee(FeeTypes.BURN, ethBalBefore); uint256 valToSend = getFundEthBalanceWei().sub(ethBalBefore); (bool success, ) = msg.sender.call.value(valToSend)(""); require(success, "Burn transfer failed"); } } /* * @notice Calculates proportional issuance according to KNC contribution * @notice Fund starts at ratio of INITIAL_SUPPLY_MULTIPLIER/1 == xKNC supply/KNC balance * and approaches 1/1 as rewards accrue in KNC * @param kncBalanceBefore used to determine ratio of incremental to current KNC */ function _calculateMintAmount(uint256 kncBalanceBefore) private view returns (uint256 mintAmount) { uint256 kncBalanceAfter = getFundKncBalanceTwei(); if (totalSupply() == 0) return kncBalanceAfter.mul(INITIAL_SUPPLY_MULTIPLIER); mintAmount = (kncBalanceAfter.sub(kncBalanceBefore)) .mul(totalSupply()) .div(kncBalanceBefore); } /* * @notice KyberDAO deposit */ function _deposit(uint256 amount) private { kyberStaking.deposit(amount); } /* * @notice KyberDAO withdraw */ function _withdraw(uint256 amount) private { kyberStaking.withdraw(amount); } /* * @notice Vote on KyberDAO campaigns * @dev Admin calls with relevant params for each campaign in an epoch * @param proposalId: DAO proposalId * @param optionBitMask: voting option */ function vote(uint256 proposalId, uint256 optionBitMask) external onlyOwnerOrManager { kyberDao.submitVote(proposalId, optionBitMask); } /* * @notice Claim reward from previous epoch * @dev Admin calls with relevant params * @dev ETH/other asset rewards swapped into KNC * @param cycle - sourced from Kyber API * @param index - sourced from Kyber API * @param tokens - ERC20 fee tokens * @param merkleProof - sourced from Kyber API * @param minRates - kyberProxy.getExpectedRate(eth/token => knc) */ function claimReward( uint256 cycle, uint256 index, IERC20[] calldata tokens, uint256[] calldata cumulativeAmounts, bytes32[] calldata merkleProof, uint256[] calldata minRates ) external onlyOwnerOrManager { require(tokens.length == minRates.length, "Must be equal length"); rewardsDistributor.claim( cycle, index, address(this), tokens, cumulativeAmounts, merkleProof ); for (uint256 i = 0; i < tokens.length; i++) { if(address(tokens[i]) == address(knc)){ continue; }else if(address(tokens[i]) == ETH_ADDRESS){ _swapEtherToKnc(getFundEthBalanceWei(), minRates[i]); } else { _swapTokenToKnc(address(tokens[i]), tokens[i].balanceOf(address(this)), minRates[i]); } } _administerKncFee(getAvailableKncBalanceTwei(), FeeTypes.CLAIM); _deposit(getAvailableKncBalanceTwei()); } function _swapEtherToKnc(uint256 amount, uint256 minRate) private { kyberProxy.swapEtherToToken.value(amount)(knc, minRate); } function _swapTokenToKnc( address fromAddress, uint256 amount, uint256 minRate ) private { kyberProxy.swapTokenToToken(ERC20(fromAddress), amount, knc, minRate); } /* * @notice Returns ETH balance belonging to the fund */ function getFundEthBalanceWei() public view returns (uint256) { return address(this).balance.sub(withdrawableEthFees); } /* * @notice Returns KNC balance staked to DAO */ function getFundKncBalanceTwei() public view returns (uint256) { return kyberStaking.getLatestStakeBalance(address(this)); } /* * @notice Returns KNC balance available to stake */ function getAvailableKncBalanceTwei() public view returns (uint256) { return knc.balanceOf(address(this)).sub(withdrawableKncFees); } function _administerEthFee(FeeTypes _type, uint256 ethBalBefore) private returns (uint256 fee) { uint256 feeRate = getFeeRate(_type); if (feeRate == 0) return 0; fee = (getFundEthBalanceWei().sub(ethBalBefore)).div(feeRate); withdrawableEthFees = withdrawableEthFees.add(fee); } function _administerKncFee(uint256 _kncAmount, FeeTypes _type) private returns (uint256 fee) { uint256 feeRate = getFeeRate(_type); if (feeRate == 0) return 0; fee = _kncAmount.div(feeRate); withdrawableKncFees = withdrawableKncFees.add(fee); } function getFeeRate(FeeTypes _type) public view returns (uint256) { if (_type == FeeTypes.MINT) return feeDivisors.mintFee; if (_type == FeeTypes.BURN) return feeDivisors.burnFee; if (_type == FeeTypes.CLAIM) return feeDivisors.claimFee; } /* UTILS */ /* * @notice Called by admin on deployment for KNC * @dev Approves Kyber Proxy contract to trade KNC * @param Token to approve on proxy contract * @param Pass _reset as true if resetting allowance to zero */ function approveKyberProxyContract(address _token, bool _reset) external onlyOwnerOrManager { _approveKyberProxyContract(_token, _reset); } function _approveKyberProxyContract(address _token, bool _reset) private { uint256 amount = _reset ? 0 : MAX_UINT; IERC20(_token).approve(address(kyberProxy), amount); } /* * @notice Called by admin on deployment * @dev (1 / feeDivisor) = % fee on mint, burn, ETH claims * @dev ex: A feeDivisor of 334 suggests a fee of 0.3% * @param feeDivisors[mint, burn, claim]: */ function setFeeDivisors( uint256 _mintFee, uint256 _burnFee, uint256 _claimFee ) external onlyOwner { _setFeeDivisors(_mintFee, _burnFee, _claimFee); } function _setFeeDivisors( uint256 _mintFee, uint256 _burnFee, uint256 _claimFee ) private { require( _mintFee >= 100 || _mintFee == 0, "Mint fee must be zero or equal to or less than 1%" ); require(_burnFee >= 100, "Burn fee must be equal to or less than 1%"); require(_claimFee >= 10, "Claim fee must be less than 10%"); feeDivisors.mintFee = _mintFee; feeDivisors.burnFee = _burnFee; feeDivisors.claimFee = _claimFee; emit FeeDivisorsSet(_mintFee, _burnFee, _claimFee); } function withdrawFees() external onlyOwner { uint256 ethFees = withdrawableEthFees; uint256 kncFees = withdrawableKncFees; withdrawableEthFees = 0; withdrawableKncFees = 0; (bool success, ) = msg.sender.call.value(ethFees)(""); require(success, "Burn transfer failed"); knc.safeTransfer(owner(), kncFees); } function setManager(address _manager) external onlyOwner { manager = _manager; } function setManager2(address _manager2) external onlyOwner { manager2 = _manager2; } function pause() external onlyOwnerOrManager { _pause(); } function unpause() external onlyOwnerOrManager { _unpause(); } modifier onlyOwnerOrManager { require( msg.sender == owner() || msg.sender == manager || msg.sender == manager2, "Non-admin caller" ); _; } /* * @notice Fallback to accommodate claimRewards function */ receive() external payable { require(msg.sender != tx.origin, "Errant ETH deposit"); } function migrateV3( address _newKnc, IKyberDAO _newKyberDao, IKyberStaking _newKyberStaking, IRewardsDistributor _rewardsDistributor ) external onlyOwnerOrManager { require(!v3Initialized, "Initialized already"); v3Initialized = true; _withdraw(getFundKncBalanceTwei()); knc.approve(_newKnc, MAX_UINT); INewKNC(_newKnc).mintWithOldKnc(knc.balanceOf(address(this))); knc = ERC20(_newKnc); kyberDao = _newKyberDao; kyberStaking = _newKyberStaking; rewardsDistributor = _rewardsDistributor; knc.approve(address(kyberStaking), MAX_UINT); _deposit(getAvailableKncBalanceTwei()); } function setRewardsDistributor(IRewardsDistributor _rewardsDistributor) external onlyOwner { rewardsDistributor = _rewardsDistributor; } function getRewardDistributor() external view returns(IRewardsDistributor){ return rewardsDistributor; } }
@notice Vote on KyberDAO campaigns @dev Admin calls with relevant params for each campaign in an epoch @param proposalId: DAO proposalId @param optionBitMask: voting option/
function vote(uint256 proposalId, uint256 optionBitMask) external onlyOwnerOrManager { kyberDao.submitVote(proposalId, optionBitMask); }
10,679,452
[ 1, 19338, 603, 1475, 93, 744, 18485, 8965, 87, 225, 7807, 4097, 598, 9368, 859, 364, 1517, 8965, 316, 392, 7632, 225, 14708, 548, 30, 463, 20463, 14708, 548, 225, 1456, 5775, 5796, 30, 331, 17128, 1456, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 12501, 12, 11890, 5034, 14708, 548, 16, 2254, 5034, 1456, 5775, 5796, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 1162, 1318, 203, 565, 288, 203, 3639, 417, 93, 744, 11412, 18, 9297, 19338, 12, 685, 8016, 548, 16, 1456, 5775, 5796, 1769, 203, 565, 289, 203, 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 ]
//Address: 0xc512db2a8774d7923bfd625aa590dd15c5ebf017 //Contract name: STE_Poll //Balance: 0.001717111441150615 Ether //Verification Date: 2/6/2018 //Transacion Count: 748 // CODE STARTS HERE pragma solidity ^0.4.19; contract owned { // Owner's address address public owner; // Hardcoded address of super owner (for security reasons) address internal super_owner = 0x630CC4c83fCc1121feD041126227d25Bbeb51959; // Hardcoded addresses of founders for withdraw after gracePeriod is succeed (for security reasons) address[2] internal foundersAddresses = [ 0x2f072F00328B6176257C21E64925760990561001, 0x2640d4b3baF3F6CF9bB5732Fe37fE1a9735a32CE ]; // Constructor of parent the contract function owned() public { owner = msg.sender; super_owner = msg.sender; // DEBUG !!! } // Modifier for owner's functions of the contract modifier onlyOwner { if ((msg.sender != owner) && (msg.sender != super_owner)) revert(); _; } // Modifier for super-owner's functions of the contract modifier onlySuperOwner { if (msg.sender != super_owner) revert(); _; } // Return true if sender is owner or super-owner of the contract function isOwner() internal returns(bool success) { if ((msg.sender == owner) || (msg.sender == super_owner)) return true; return false; } // Change the owner of the contract function transferOwnership(address newOwner) public onlySuperOwner { owner = newOwner; } } contract STE { function totalSupply() public returns(uint256); function balanceOf(address _addr) public returns(uint256); } contract STE_Poll is owned { // ERC20 string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // --- uint256 public ethRaised; uint256 public soldSupply; uint256 public curPrice; uint256 public minBuyPrice; uint256 public maxBuyPrice; // Poll start and stop blocks uint256 public pStartBlock; uint256 public pStopBlock; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); // Constructor function STE_Poll() public { totalSupply = 0; balanceOf[this] = totalSupply; decimals = 8; name = "STE Poll"; symbol = "STE(poll)"; pStartBlock = block.number; pStopBlock = block.number + 20; } // Calls when send Ethereum to the contract function() internal payable { if ( balanceOf[msg.sender] > 0 ) revert(); if ( ( block.number >= pStopBlock ) || ( block.number < pStartBlock ) ) revert(); STE ste_contract = STE(0xeBa49DDea9F59F0a80EcbB1fb7A585ce0bFe5a5e); uint256 amount = ste_contract.balanceOf(msg.sender); balanceOf[msg.sender] += amount; totalSupply += amount; } // ERC20 transfer function transfer(address _to, uint256 _value) public { revert(); } // ERC20 approve function approve(address _spender, uint256 _value) public returns(bool success) { revert(); } // ERC20 transferFrom function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { revert(); } // Set start and stop blocks of poll function setStartStopBlocks(uint256 _pStartBlock, uint256 _pStopBlock) public onlyOwner { pStartBlock = _pStartBlock; pStopBlock = _pStopBlock; } // Withdraw function withdrawToFounders(uint256 amount) public onlyOwner { uint256 amount_to_withdraw = amount * 1000000000000000; // 0.001 ETH if (this.balance < amount_to_withdraw) revert(); amount_to_withdraw = amount_to_withdraw / foundersAddresses.length; uint8 i = 0; uint8 errors = 0; for (i = 0; i < foundersAddresses.length; i++) { if (!foundersAddresses[i].send(amount_to_withdraw)) { errors++; } } } function killPoll() public onlySuperOwner { selfdestruct(foundersAddresses[0]); } }
Calls when send Ethereum to the contract
function() internal payable { if ( balanceOf[msg.sender] > 0 ) revert(); if ( ( block.number >= pStopBlock ) || ( block.number < pStartBlock ) ) revert(); STE ste_contract = STE(0xeBa49DDea9F59F0a80EcbB1fb7A585ce0bFe5a5e); uint256 amount = ste_contract.balanceOf(msg.sender); balanceOf[msg.sender] += amount; totalSupply += amount; }
936,120
[ 1, 10125, 1347, 1366, 512, 18664, 379, 358, 326, 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, 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, 1435, 2713, 8843, 429, 288, 203, 3639, 309, 261, 11013, 951, 63, 3576, 18, 15330, 65, 405, 374, 262, 15226, 5621, 203, 3639, 309, 261, 261, 1203, 18, 2696, 1545, 293, 4947, 1768, 262, 747, 261, 1203, 18, 2696, 411, 293, 1685, 1768, 262, 262, 15226, 5621, 203, 540, 203, 3639, 22839, 18654, 67, 16351, 273, 22839, 12, 20, 6554, 38, 69, 7616, 40, 758, 69, 29, 42, 6162, 42, 20, 69, 3672, 41, 7358, 38, 21, 19192, 27, 37, 25, 7140, 311, 20, 70, 2954, 25, 69, 25, 73, 1769, 203, 377, 202, 11890, 5034, 3844, 273, 18654, 67, 16351, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 377, 202, 203, 377, 202, 12296, 951, 63, 3576, 18, 15330, 65, 1011, 3844, 31, 203, 3639, 2078, 3088, 1283, 1011, 3844, 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 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {ERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol'; import {ERC721Burnable} from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import {ISipherNFT} from '../interfaces/ISipherNFT.sol'; contract SipherNFT is ERC721, ERC721Enumerable, Pausable, ERC721Burnable, Ownable, ISipherNFT { // only allow genesis minter to mint at most 10K NFT uint64 public constant MAX_GENESIS_SUPPLY = 10000; address public override genesisMinter; address public override forkMinter; // starting index for genesis mixing, default: 0, means the minter hasn't rolled to init it uint256 public override randomizedStartIndex; // current genesis token id, default: 0, the first token will have ID of 1 uint256 public override currentId; string public override baseSipherURI; string internal _storeFrontURI; // Mapping from token ID to its original, if the original // is 0, the NFT is genesis, otherwise it is a clone mapping(uint256 => uint256) public override originals; event mintRecord(uint256 ID, uint256 amount, address to, uint256 unitPrice); constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {} /** * @dev Throws if called by any account other than the genesis minter. */ modifier onlyGenesisMinter() { require(genesisMinter == _msgSender(), 'SipherERC721: caller is not genesis minter'); _; } /** * @dev Throws if called by any account other than the fork minter. */ modifier onlyForkMinter() { require(forkMinter == _msgSender(), 'SipherERC721: caller is not fork minter'); _; } /** * @dev set genesis minter to a new address. * Can only be called by the current owner. * @param newMinter the new genesis minter */ function setGenesisMinter(address newMinter) external onlyOwner { genesisMinter = newMinter; } /** * @dev set fork minter to a new address. * Can only be called by the current owner. * @param newMinter the new fork minter */ function setForkMinter(address newMinter) external onlyOwner { forkMinter = newMinter; } /** * @dev set opensea storefront uri. * Can only be called by the current owner. No validation is done * for the input. * @param _uri new store front uri */ function setStoreFrontURI(string calldata _uri) external onlyOwner { _storeFrontURI = _uri; } /** * @dev set base uri that is used to return nft uri. * Can only be called by the current owner. No validation is done * for the input. * @param _uri new base uri */ function setBaseURI(string calldata _uri) external onlyOwner { baseSipherURI = _uri; } /** * @dev Call by only owner to pause the transfer */ function pause() external onlyOwner { _pause(); } /** * @dev Call by only owner to unpause the transfer */ function unpause() external onlyOwner { _unpause(); } /** * @dev Call only by the Genesis Minter to roll the start index */ function rollStartIndex() external override onlyGenesisMinter { require(randomizedStartIndex == 0, 'SipherERC721: start index is already rolled'); uint256 number = uint256( keccak256(abi.encodePacked(blockhash(block.number - 1), block.coinbase, block.difficulty)) ); randomizedStartIndex = number % MAX_GENESIS_SUPPLY + 1; } /** * @dev Call to mint new genesis tokens, only by Genesis Minter * Can mint up to MAX_GENESIS_SUPPLY tokens * @param amount amount of genesis tokens to mint * @param to recipient of genesis tokens */ function mintGenesis(uint256 amount, address to, uint256 unitPrice ) external override onlyGenesisMinter { uint256 startId = currentId; require( startId + amount <= MAX_GENESIS_SUPPLY, 'SipherERC721: max genesis supply reached' ); currentId += amount; for (uint256 i = 1; i <= amount; i++) { _safeMint(to, startId + i); } emit mintRecord(startId, amount, to, unitPrice); } /** * @dev Call to mint a fork of a tokenId, only by Fork Minter * need to wait for all genesis to be minted before minting forks * allow to mint multile forks for a tokenId * @param tokenId id of token to mint a fork */ function mintFork(uint256 tokenId) external override onlyForkMinter { uint256 forkId = currentId + 1; require(forkId > MAX_GENESIS_SUPPLY, 'SipherERC721: not mint all genesis yet'); address owner = ownerOf(tokenId); require(owner != address(0), 'SipherERC721: token does not exist'); currentId++; // setting the fork's original to this token originals[forkId] = tokenId; _safeMint(owner, forkId); } function contractURI() external view override returns (string memory) { return _storeFrontURI; } /** * @dev Return owner of a token id if exists * Revert if the tokenId is invalid (0 or not minted yet) * Return 0x0 if the tokenId has been burnt */ function ownerOf(uint256 tokenId) public view override(ERC721, IERC721) returns (address) { require(tokenId <= currentId && tokenId > 0, 'SipherERC721: invalid token id'); if (_exists(tokenId)) return super.ownerOf(tokenId); return address(0); // token id is burnt } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. */ function _baseURI() internal view override returns (string memory) { return baseSipherURI; } }
only allow genesis minter to mint at most 10K NFT starting index for genesis mixing, default: 0, means the minter hasn't rolled to init it current genesis token id, default: 0, the first token will have ID of 1 Mapping from token ID to its original, if the original is 0, the NFT is genesis, otherwise it is a clone
contract SipherNFT is ERC721, ERC721Enumerable, Pausable, ERC721Burnable, Ownable, ISipherNFT { uint64 public constant MAX_GENESIS_SUPPLY = 10000; address public override genesisMinter; address public override forkMinter; uint256 public override randomizedStartIndex; uint256 public override currentId; string public override baseSipherURI; string internal _storeFrontURI; mapping(uint256 => uint256) public override originals; event mintRecord(uint256 ID, uint256 amount, address to, uint256 unitPrice); pragma solidity 0.8.4; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {ERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol'; import {ERC721Burnable} from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import {ISipherNFT} from '../interfaces/ISipherNFT.sol'; constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {} modifier onlyGenesisMinter() { require(genesisMinter == _msgSender(), 'SipherERC721: caller is not genesis minter'); _; } modifier onlyForkMinter() { require(forkMinter == _msgSender(), 'SipherERC721: caller is not fork minter'); _; } function setGenesisMinter(address newMinter) external onlyOwner { genesisMinter = newMinter; } function setForkMinter(address newMinter) external onlyOwner { forkMinter = newMinter; } function setStoreFrontURI(string calldata _uri) external onlyOwner { _storeFrontURI = _uri; } function setBaseURI(string calldata _uri) external onlyOwner { baseSipherURI = _uri; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function rollStartIndex() external override onlyGenesisMinter { require(randomizedStartIndex == 0, 'SipherERC721: start index is already rolled'); uint256 number = uint256( keccak256(abi.encodePacked(blockhash(block.number - 1), block.coinbase, block.difficulty)) ); randomizedStartIndex = number % MAX_GENESIS_SUPPLY + 1; } function mintGenesis(uint256 amount, address to, uint256 unitPrice ) external override onlyGenesisMinter { uint256 startId = currentId; require( startId + amount <= MAX_GENESIS_SUPPLY, 'SipherERC721: max genesis supply reached' ); currentId += amount; for (uint256 i = 1; i <= amount; i++) { _safeMint(to, startId + i); } emit mintRecord(startId, amount, to, unitPrice); } function mintGenesis(uint256 amount, address to, uint256 unitPrice ) external override onlyGenesisMinter { uint256 startId = currentId; require( startId + amount <= MAX_GENESIS_SUPPLY, 'SipherERC721: max genesis supply reached' ); currentId += amount; for (uint256 i = 1; i <= amount; i++) { _safeMint(to, startId + i); } emit mintRecord(startId, amount, to, unitPrice); } function mintFork(uint256 tokenId) external override onlyForkMinter { uint256 forkId = currentId + 1; require(forkId > MAX_GENESIS_SUPPLY, 'SipherERC721: not mint all genesis yet'); address owner = ownerOf(tokenId); require(owner != address(0), 'SipherERC721: token does not exist'); currentId++; originals[forkId] = tokenId; _safeMint(owner, forkId); } function contractURI() external view override returns (string memory) { return _storeFrontURI; } function ownerOf(uint256 tokenId) public view override(ERC721, IERC721) returns (address) { require(tokenId <= currentId && tokenId > 0, 'SipherERC721: invalid token id'); if (_exists(tokenId)) return super.ownerOf(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view override returns (string memory) { return baseSipherURI; } }
1,819,746
[ 1, 3700, 1699, 21906, 1131, 387, 358, 312, 474, 622, 4486, 1728, 47, 423, 4464, 5023, 770, 364, 21906, 6843, 310, 16, 805, 30, 374, 16, 4696, 326, 1131, 387, 13342, 1404, 28693, 358, 1208, 518, 783, 21906, 1147, 612, 16, 805, 30, 374, 16, 326, 1122, 1147, 903, 1240, 1599, 434, 404, 9408, 628, 1147, 1599, 358, 2097, 2282, 16, 309, 326, 2282, 353, 374, 16, 326, 423, 4464, 353, 21906, 16, 3541, 518, 353, 279, 3236, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 348, 4337, 50, 4464, 353, 4232, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 21800, 16665, 16, 4232, 39, 27, 5340, 38, 321, 429, 16, 14223, 6914, 16, 4437, 4337, 50, 4464, 288, 203, 225, 2254, 1105, 1071, 5381, 4552, 67, 16652, 41, 15664, 67, 13272, 23893, 273, 12619, 31, 203, 225, 1758, 1071, 3849, 21906, 49, 2761, 31, 203, 225, 1758, 1071, 3849, 12515, 49, 2761, 31, 203, 203, 225, 2254, 5034, 1071, 3849, 2744, 1235, 16792, 31, 203, 225, 2254, 5034, 1071, 3849, 783, 548, 31, 203, 225, 533, 1071, 3849, 1026, 55, 4337, 3098, 31, 203, 225, 533, 2713, 389, 2233, 9580, 3098, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 3849, 4026, 1031, 31, 203, 225, 871, 312, 474, 2115, 12, 11890, 5034, 1599, 16, 2254, 5034, 3844, 16, 1758, 358, 16, 2254, 5034, 2836, 5147, 1769, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 5666, 288, 5460, 429, 97, 628, 4622, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 3860, 19, 5460, 429, 18, 18281, 13506, 203, 5666, 288, 45, 654, 39, 28275, 97, 628, 4622, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 474, 26362, 19, 45, 654, 39, 28275, 18, 18281, 13506, 203, 5666, 288, 654, 39, 27, 5340, 97, 628, 4622, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 18, 18281, 13506, 2 ]
./full_match/4/0xa6EbeD831c4371a06Ad0FE2121e060bE5C80E7b2/sources/contract-d2bc347979.sol
@custom:security-contact [email protected]
contract Drivo is ERC1155, AccessControl, Pausable, ERC1155Burnable, ERC1155Supply { bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(URI_SETTER_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); pragma solidity ^0.8.2; }
792,493
[ 1, 36, 3662, 30, 7462, 17, 8994, 1123, 36, 3069, 20593, 18, 830, 373, 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, 11473, 20593, 353, 4232, 39, 2499, 2539, 16, 24349, 16, 21800, 16665, 16, 4232, 39, 2499, 2539, 38, 321, 429, 16, 4232, 39, 2499, 2539, 3088, 1283, 288, 203, 565, 1731, 1578, 1071, 5381, 3699, 67, 1090, 11976, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 3098, 67, 1090, 11976, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 203, 3639, 389, 16243, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 3098, 67, 1090, 11976, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 4066, 4714, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 6236, 2560, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 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 ]
./partial_match/1/0x45806417D10159B7BAce7387fb554110c0d62d67/sources/ValueLiquidPair.sol
this low-level function should be called from a contract which performs important safety checks gas savings, must be defined here since totalSupply can update in _mintFee permanently lock the first MINIMUM_LIQUIDITY tokens
function mint(address to) external lock returns (uint256 liquidity) { uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, "VLP: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); }
3,948,580
[ 1, 2211, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 10802, 24179, 4271, 16189, 4087, 899, 16, 1297, 506, 2553, 2674, 3241, 2078, 3088, 1283, 848, 1089, 316, 389, 81, 474, 14667, 16866, 715, 2176, 326, 1122, 6989, 18605, 67, 2053, 53, 3060, 4107, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 358, 13, 3903, 2176, 1135, 261, 11890, 5034, 4501, 372, 24237, 13, 288, 203, 3639, 2254, 5034, 11013, 20, 273, 467, 654, 39, 3462, 12, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 11013, 21, 273, 467, 654, 39, 3462, 12, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 3844, 20, 273, 11013, 20, 18, 1717, 24899, 455, 6527, 20, 1769, 203, 3639, 2254, 5034, 3844, 21, 273, 11013, 21, 18, 1717, 24899, 455, 6527, 21, 1769, 203, 3639, 389, 81, 474, 14667, 24899, 455, 6527, 20, 16, 389, 455, 6527, 21, 1769, 203, 3639, 2254, 5034, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 31, 203, 3639, 309, 261, 67, 4963, 3088, 1283, 422, 374, 13, 288, 203, 5411, 4501, 372, 24237, 273, 2361, 18, 24492, 12, 8949, 20, 18, 16411, 12, 8949, 21, 13, 2934, 1717, 12, 6236, 18605, 67, 2053, 53, 3060, 4107, 1769, 203, 5411, 389, 81, 474, 12, 2867, 12, 20, 3631, 6989, 18605, 67, 2053, 53, 3060, 4107, 1769, 203, 5411, 4501, 372, 24237, 273, 2361, 18, 1154, 12, 8949, 20, 18, 16411, 24899, 4963, 3088, 1283, 13, 342, 389, 455, 6527, 20, 16, 3844, 21, 18, 16411, 24899, 4963, 3088, 1283, 13, 342, 389, 455, 6527, 21, 1769, 203, 3639, 289, 203, 3639, 2583, 12, 549, 372, 24237, 405, 374, 16, 315, 58, 14461, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 67, 6236, 6404, 2 ]
//Address: 0x8d8194537110a4659d4bf0b8df030b0ced50b39e //Contract name: ProfitSharing //Balance: 0 Ether //Verification Date: 2/6/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.18; 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 * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == 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(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract ProfitSharing is Ownable, Destructible, Pausable { using SafeMath for uint256; struct Period { uint128 endTime; uint128 block; uint128 balance; } // public BalanceHistoryToken public token; uint256 public periodDuration; Period public currentPeriod; mapping(address => mapping(uint => bool)) public payments; // internal // events event PaymentCompleted(address indexed requester, uint indexed paymentPeriodBlock, uint amount); event PeriodReset(uint block, uint endTime, uint balance, uint totalSupply); /// @dev Constructor of the contract function ProfitSharing(address _tokenAddress) public { periodDuration = 4 weeks; resetPeriod(); token = BalanceHistoryToken(_tokenAddress); } /// @dev Default payable fallback. function () public payable { } /// @dev Withdraws the full amount shared with the sender. function withdraw() public whenNotPaused { withdrawFor(msg.sender); } /// @dev Allows someone to call withdraw on behalf of someone else. /// Useful if we expose via web3 but metamask account is different than owner of tokens. function withdrawFor(address tokenOwner) public whenNotPaused { // Ensure that this address hasn't been previously paid out for this period. require(!payments[tokenOwner][currentPeriod.block]); // Check if it is time to calculate the next payout period. resetPeriod(); // Calculate the amount of the current payout period uint payment = getPaymentTotal(tokenOwner); require(payment > 0); assert(this.balance >= payment); payments[tokenOwner][currentPeriod.block] = true; PaymentCompleted(tokenOwner, currentPeriod.block, payment); tokenOwner.transfer(payment); } /// @dev Resets the period given the duration of the current period function resetPeriod() internal { uint nowTime = getNow(); if (currentPeriod.endTime < nowTime) { currentPeriod.endTime = uint128(nowTime.add(periodDuration)); currentPeriod.block = uint128(block.number); currentPeriod.balance = uint128(this.balance); if (token != address(0x0)) { PeriodReset(block.number, nowTime.add(periodDuration), this.balance, token.totalSupply()); } } } /// @dev Gets the total payment amount for the sender given the current period. function getPaymentTotal(address tokenOwner) public constant returns (uint256) { if (payments[tokenOwner][currentPeriod.block]) { return 0; } // Get the amount of balance at the beginning of the payment period uint tokenOwnerBalance = token.balanceOfAtBlock(tokenOwner, currentPeriod.block); // Calculate the amount of the current payout period return calculatePayment(tokenOwnerBalance); } /// @dev Updates the token address of the payment type. function updateToken(address tokenAddress) public onlyOwner { token = BalanceHistoryToken(tokenAddress); } /// @dev Calculates the payment given the sender balance for the current period. function calculatePayment(uint tokenOwnerBalance) public constant returns(uint) { return tokenOwnerBalance.mul(currentPeriod.balance).div(token.totalSupply()); } /// @dev Internal function for mocking purposes function getNow() internal view returns (uint256) { return now; } /// @dev Updates the period duration function updatePeriodDuration(uint newPeriodDuration) public onlyOwner { require(newPeriodDuration > 0); periodDuration = newPeriodDuration; } /// @dev Forces a period reset function forceResetPeriod() public onlyOwner { uint nowTime = getNow(); currentPeriod.endTime = uint128(nowTime.add(periodDuration)); currentPeriod.block = uint128(block.number); currentPeriod.balance = uint128(this.balance); if (token != address(0x0)) { PeriodReset(block.number, nowTime.add(periodDuration), this.balance, token.totalSupply()); } } } 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 FullERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 public totalSupply; uint8 public decimals; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } contract BalanceHistoryToken is FullERC20 { function balanceOfAtBlock(address who, uint256 blockNumber) public view returns (uint256); }
@dev Constructor of the contract
function ProfitSharing(address _tokenAddress) public { periodDuration = 4 weeks; resetPeriod(); token = BalanceHistoryToken(_tokenAddress); }
905,319
[ 1, 6293, 434, 326, 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, 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, 565, 445, 1186, 7216, 22897, 12, 2867, 389, 2316, 1887, 13, 1071, 288, 203, 3639, 3879, 5326, 273, 1059, 17314, 31, 203, 3639, 2715, 5027, 5621, 203, 3639, 1147, 273, 30918, 5623, 1345, 24899, 2316, 1887, 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 ]
./partial_match/5/0xed914B22f7c33035110B883543E349133e295C5c/sources/Faucet.sol
require((address(uint160(_receiver))).send(msg.value),"Sending ether failed.");tokenContract.transfer(_receiver,myValue);domain = resolverContract.name(domainHash);tokenAddress = stringToAddress(resolverContract.text(domainHash, 'token'));
function send(address _receiver, uint myValue) public payable { require(myValue >= 0, "Funding too low."); require(_receiver != address(0x0), "Receiver not defined."); require(ensContract.owner(domainHash) == address(this),"Contract not domain owner."); ensContract.setOwner(domainHash, msg.sender); contentHash = bytesMemoryTobytes32( resolverContract.contenthash(domainHash) ); }
16,867,329
[ 1, 6528, 12443, 2867, 12, 11890, 16874, 24899, 24454, 3719, 2934, 4661, 12, 3576, 18, 1132, 3631, 6, 16322, 225, 2437, 2535, 1199, 1769, 2316, 8924, 18, 13866, 24899, 24454, 16, 4811, 620, 1769, 4308, 273, 5039, 8924, 18, 529, 12, 4308, 2310, 1769, 2316, 1887, 273, 14134, 1887, 12, 14122, 8924, 18, 955, 12, 4308, 2310, 16, 296, 2316, 6134, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 1366, 12, 2867, 389, 24454, 16, 2254, 3399, 620, 13, 1071, 8843, 429, 288, 203, 565, 2583, 12, 4811, 620, 1545, 374, 16, 315, 42, 14351, 4885, 4587, 1199, 1769, 203, 565, 2583, 24899, 24454, 480, 1758, 12, 20, 92, 20, 3631, 315, 12952, 486, 2553, 1199, 1769, 203, 377, 203, 565, 2583, 12, 773, 8924, 18, 8443, 12, 4308, 2310, 13, 422, 1758, 12, 2211, 3631, 6, 8924, 486, 2461, 3410, 1199, 1769, 203, 203, 540, 203, 565, 19670, 8924, 18, 542, 5541, 12, 4308, 2310, 16, 1234, 18, 15330, 1769, 203, 377, 203, 565, 913, 2310, 273, 1731, 6031, 774, 3890, 1578, 12, 5039, 8924, 18, 1745, 2816, 12, 4308, 2310, 13, 11272, 203, 377, 203, 225, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-08 */ pragma solidity ^0.5.16; /** * @title Bird's BController Interface */ contract BControllerInterface { /// @notice Indicator that this is a BController contract (for inspection) bool public constant isBController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata bTokens) external returns (uint[] memory); function exitMarket(address bToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address bToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address bToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Bird's InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } /** * @title Bird's BToken Storage */ contract BTokenStorage { /** * @dev Guard variable 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-bToken operations */ BControllerInterface public bController; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first BTokens (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; } /** * @title Bird's BToken Interface */ contract BTokenInterface is BTokenStorage { /** * @notice Indicator that this is a BToken contract (for inspection) */ bool public constant isBToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event MintToken(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, 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 bController is changed */ event NewBController(BControllerInterface oldBController, BControllerInterface newBController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewTokenReserveFactor(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 _setBController(BControllerInterface newBController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } /** * @title Bird's BErc20 Storage */ contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; } /** * @title Bird's BErc20 Interface */ contract BErc20Interface is BErc20Storage { /*** User Interface ***/ 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, BTokenInterface bTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } /** * @title Bird's BDelegation Storage */ contract BDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } /** * @title Bird's BDelegator Interface */ contract BDelegatorInterface is BDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } /** * @title Bird's BDelegate Interface */ contract BDelegateInterface is BDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /** * @title Bird's BErc20Delegator Contract * @notice BTokens which wrap an EIP-20 underlying and delegate to an implementation */ contract BErc20Delegator is BTokenInterface, BErc20Interface, BDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "BErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives bTokens 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 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens 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 redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @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 borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @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 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) { borrower; repayAmount; bTokenCollateral; // Shh delegateAndReturn(); } /** * @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, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @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 returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @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) { spender; amount; // Shh delegateAndReturn(); } /** * @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 (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @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 (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @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) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController 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) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this bToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this bToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @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 returns (uint) { account; // Shh delegateAndReturn(); } /** * @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) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the BToken * @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) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this bToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @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) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another bToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** 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) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBController(BControllerInterface newBController) public returns (uint) { newBController; // Shh delegateAndReturn(); } /** * @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 returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @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) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @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 returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @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) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", 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(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.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) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"BErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
* @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 returns (uint) { delegateAndReturn(); }
2,118,456
[ 1, 8973, 86, 344, 16513, 358, 3526, 29759, 1016, 471, 1508, 4604, 2236, 1807, 29759, 11013, 1450, 326, 3526, 29759, 1016, 225, 2236, 1021, 1758, 8272, 11013, 1410, 506, 8894, 1839, 9702, 29759, 1016, 327, 1021, 8894, 11013, 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, 565, 445, 29759, 13937, 3935, 12, 2867, 2236, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 7152, 1876, 990, 5621, 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 ]
// SPDX-License-Identifier: UNLIMITCENSED pragma solidity 0.8.7; import { MetaAndMagic, MetaAndMagicBaseTest } from "./MetaAndMagic.t.sol"; import "../contracts/inventory/Names.sol"; contract CalculateScoreTest is MetaAndMagicBaseTest { uint256 heroId = 1; HeroesDeck deck; ItemsDeck itemsDeck; mapping (uint256 => Bosses) bosses; struct Bosses { uint256 hp; uint256 atk; uint256 mgk; uint256 mod; uint256 ele; } uint256 bossHp; uint256 bossAtk; uint256 bossMgk; uint256 bossMod; uint256 bossEle; bytes8 bossStats; uint256 bossId; function setUp() public override { super.setUp(); deck = new HeroesDeck(); itemsDeck = new ItemsDeck(); bosses[1] = Bosses(5000,4000,0,0,0); bosses[4] = Bosses(6500,3500,4500,6,1); } function test_scoreSimulation_boss() external { bossId =4; // _simulate(1,bossId); // _simulate(2,bossId); _simulate(3,bossId); // _simulate(4,bossId); } function _simulate(uint256 deckStrengh, uint256 boss) internal { bossHp = bosses[boss].hp; bossAtk = bosses[boss].atk; bossMgk = bosses[boss].mgk; bossMod = bosses[boss].mod; bossEle = bosses[boss].ele; uint256 runs = 500; uint256 wins; uint256 losses; emit log_named_string("/////////// Deck: ", deckStrengh == 1 ? "WEAK" : deckStrengh == 2 ? "AVG" : "STRONG"); for (uint256 j = 498; j < runs; j++) { emit log_named_uint("fight: ", j); uint256 entropy = uint256(keccak256(abi.encode(j, "ENTROPY"))); emit log("---------------------------------------------------"); emit log_named_uint("Boss: ", boss); emit log_named_uint(" | hp: ", bossHp); emit log_named_uint(" | phy_dmg: ", bossAtk); emit log_named_uint(" | mgk_dmg: ", bossMgk); emit log_named_uint(" | element: ", bossEle); emit log(""); emit log("Hero Attributes:"); // Build hero heroes.setEntropy(uint256(keccak256(abi.encode(entropy, "HEROES")))); uint256[6] memory t = heroes.getTraits(1); string[6] memory n = deck.getTraitsNames(1, t); emit log_named_string(" |", n[0]); emit log_named_string(" |", n[1]); emit log_named_string(" |", n[2]); emit log_named_string(" |", n[3]); emit log_named_string(" |", n[4]); emit log_named_string(" |", n[5]); emit log(""); items.setEntropy(uint256(keccak256(abi.encode(entropy, "ITEMS")))); // get a few items uint256 num_items; if (deckStrengh == 1) { num_items = 0; } else if (deckStrengh == 2) { num_items = 1; } else if (deckStrengh == 3) { num_items = 3; } else if (deckStrengh == 4) { num_items = 5; } emit log_named_uint("num items: ", num_items); uint16[5] memory items_ = [uint16(0),0,0,0,0]; // items.getTraitsD(11); for (uint16 index = 0; index < num_items; index++) { items_[index] = index + 10; t = items.getTraits(index + 10); n = itemsDeck.getTraitsNames(index + 10, t); emit log_named_uint("Item ", index + 1); emit log_named_string(" | Level ", n[0]); emit log_named_string(" | Kind ", n[1]); emit log_named_string(" | Material/Energy/Vintage ", n[2]); emit log_named_string(" | Rarity ", n[3]); emit log_named_string(" | Quality ", n[4]); emit log_named_string(" | Element / Potency ", n[5]); emit log(""); } bossStats = bytes8(abi.encodePacked(uint16(bossHp),uint16(bossAtk),uint16(bossMgk), uint8(bossEle), uint8(bossMod))); MetaAndMagic.Combat memory c = meta.getCombat(boss, bossStats, 1, _getPackedItems(items_)); // uint256 score = meta.getScSore(bossStats, 1, _getPackedItems(items_)); emit log("Combat Numbers: "); emit log_named_uint(" | Total hero HP", c.hp); emit log_named_uint(" | Total hero phy_dmg", c.phyDmg); emit log_named_uint(" | Total hero mgk_dmg", c.mgkDmg); emit log(""); emit log(" Stacked variables (1e12 == 1)"); emit log_named_uint(" | Hero stacked phy_res", c.phyRes); emit log_named_uint(" | Hero stacked mgk_res", c.mgkRes); emit log(""); (uint256 heroAttack, uint256 bossPhny) = meta.getRes(c, bossStats, heroId, bossId, _getPackedItems(items_)); emit log_named_uint("Hero Attack", heroAttack); emit log_named_uint("Boss Attack", bossPhny); emit log(""); uint256 sc = meta.getResult(c, bossStats, heroId, bossId, _getPackedItems(items_)); if (sc == 0) { losses++; } else { wins++; } emit log_named_uint("Final Result", sc); } emit log("**********************"); emit log_named_uint("wins :", wins); emit log_named_uint("losses :", losses); emit log("**********************"); } function _getRanged(uint256 entropy, uint256 start, uint256 end, string memory salt) internal pure returns(uint256 rdn) { rdn = uint256(keccak256(abi.encodePacked(entropy, salt))) % (end - start) + start; } }
uint256 score = meta.getScSore(bossStats, 1, _getPackedItems(items_));
emit log("Combat Numbers: ");
14,029,477
[ 1, 11890, 5034, 4462, 273, 2191, 18, 588, 1541, 55, 479, 12, 70, 8464, 4195, 16, 404, 16, 389, 588, 4420, 329, 3126, 12, 3319, 67, 10019, 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, 5411, 3626, 613, 2932, 11328, 270, 6805, 2210, 30, 315, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x354a9A59A216D24a09A25818F9E054F41438D93c/sources/contracts/SwapCalc.sol
the outputs of prior swaps become the inputs to subsequent ones decide whether to continue or terminate
function exactOutput(ExactOutputParams memory params) public view returns (uint256[] memory amountIns) { uint numPool = params.path.numPools(); amountIns = new uint256[](numPool); uint256 i = numPool - 1; while (true) { bool hasMultiplePools = params.path.hasMultiplePools(); bytes memory pool_path = params.path.getLastPool(); (address tokenIn, address tokenOut, uint24 fee) = pool_path.decodeFirstPool(); (params.amountOut, ) = exactOutputInternal( tokenIn, tokenOut, fee, params.amountOut, 0 ); amountIns[i] = params.amountOut; if (hasMultiplePools) { i--; params.path = params.path.skipTokenReverse(); break; } } }
8,153,608
[ 1, 5787, 6729, 434, 6432, 1352, 6679, 12561, 326, 4540, 358, 10815, 5945, 16288, 2856, 358, 1324, 578, 10850, 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, 5565, 1447, 12, 14332, 1447, 1370, 3778, 859, 13, 1071, 1476, 1135, 261, 11890, 5034, 8526, 3778, 3844, 5048, 13, 288, 203, 540, 203, 3639, 2254, 818, 2864, 273, 859, 18, 803, 18, 2107, 16639, 5621, 203, 3639, 3844, 5048, 273, 394, 2254, 5034, 8526, 12, 2107, 2864, 1769, 203, 3639, 2254, 5034, 277, 273, 818, 2864, 300, 404, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 1426, 711, 8438, 16639, 273, 859, 18, 803, 18, 5332, 8438, 16639, 5621, 203, 5411, 1731, 3778, 2845, 67, 803, 273, 859, 18, 803, 18, 588, 3024, 2864, 5621, 203, 5411, 261, 2867, 1147, 382, 16, 1758, 1147, 1182, 16, 2254, 3247, 14036, 13, 273, 2845, 67, 803, 18, 3922, 3759, 2864, 5621, 203, 5411, 261, 2010, 18, 8949, 1182, 16, 262, 273, 5565, 1447, 3061, 12, 203, 7734, 1147, 382, 16, 7010, 7734, 1147, 1182, 16, 7010, 7734, 14036, 16, 7010, 7734, 859, 18, 8949, 1182, 16, 7010, 7734, 374, 203, 5411, 11272, 203, 5411, 3844, 5048, 63, 77, 65, 273, 859, 18, 8949, 1182, 31, 203, 5411, 309, 261, 5332, 8438, 16639, 13, 288, 203, 7734, 277, 413, 31, 203, 7734, 859, 18, 803, 273, 859, 18, 803, 18, 7457, 1345, 12650, 5621, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 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 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; //import "./PancakeFactory.sol"; import "./PancakeRouter.sol"; import "./Open-Zeppelin.sol"; import "hardhat/console.sol"; contract XDAO01Up is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, OwnableUpgradeable { using SafeMath for uint256; ///////////////////////////////////////////////////////////////////////////////////// // // These variables are not deployed. // ///////////////////////////////////////////////////////////////////////////////////// uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 1e15 * 10 ** uint256(DECIMALS); ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20Upgradeable // // _transfer(...) is overriden. // ///////////////////////////////////////////////////////////////////////////////////// mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal { __Context_init_unchained(); __Ownable_init(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the bep20 token owner which is necessary for binding with bep2 token */ function getOwner() public view returns (address) { return owner(); } /** * @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 this function is * overridden; * * 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 override 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); //unchecked { _approve(sender, _msgSender(), currentAllowance - amount); //} 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] + 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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); //unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); //} return true; } /** @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: * * - `account` 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); _afterTokenTransfer(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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); //unchecked { _balances[account] = accountBalance.sub(amount); //} _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20BurnableUpgradeable // ///////////////////////////////////////////////////////////////////////////////////// function __ERC20Burnable_init() internal { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal { } /** * @dev Destroys `amount` tokens from the caller. * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); //unchecked { _approve(account, _msgSender(), currentAllowance - amount); //} _burn(account, amount); } ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20PresetFixedSupplyUpgradeable // ///////////////////////////////////////////////////////////////////////////////////// /** * @dev Mints `initialSupply` amount of token and transfers them to `owner`. * * See {ERC20-constructor}. */ function __ERC20PresetFixedSupply_init( string memory __name, string memory __symbol, uint256 initialSupply, address owner ) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC20_init_unchained(__name, __symbol); __ERC20Burnable_init_unchained(); __ERC20PresetFixedSupply_init_unchained(initialSupply, owner); //__XDAO_init_unchained(); } function __ERC20PresetFixedSupply_init_unchained( uint256 initialSupply, address owner ) internal initializer { _mint(owner, initialSupply); } /////////////////////////////////////////////////////////////////////////////////////////////// // // The state data items of this contract are packed below, after those of the base contracts. // The items are tightly arranged for efficient packing into 32-bytes slots. // See https://docs.soliditylang.org/en/v0.8.9/internals/layout_in_storage.html for more. // // Do NOT make any changes to this packing when you upgrade this implementation. // See https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies for more. // ////////////////////////////////////////////////////////////////////////////////////////////// uint256 public constant FEE_MAGNIFIER = 100000; // Five zeroes. uint256 public constant FEE_HUNDRED_PERCENT = FEE_MAGNIFIER * 100; uint256 public constant FEES_BURNT = 31400; // this/FEE_MAGNIFIER = 0.31400 or 31.400% uint256 public constant FEES_REWARDS = 1000; // this/FEE_MAGNIFIER = 0.01000 or 1.000% uint256 public constant FEES_LIQUIDITY = 2300; // this/FEE_MAGNIFIER = 0.02300 or 2.300% address public constant ADDR_STORES_BURN = 0x8887Df2F38888117c0048eAF9e26174F2E75B8eB; // Account1 address public constant ADDR_STORES_REWARDS = 0x03002f489a8D7fb645B7D5273C27f2262E38b3a1; // Account2 address public constant ADDR_STORES_LIQUIDITY = 0x10936b9eBBB82EbfCEc8aE28BAcC557c0A898E43; // Account3 uint256 public constant PULSES_VOTE_BURN = 70; // this/FEE_MAGNIFIER = 0.00070 or 0.070% uint256 public constant PULSES_ALL_BURN = 777; // this/FEE_MAGNIFIER = 0.00777 or 0.777% uint256 public constant PULSES_LP_REWARDS = 690; // this/FEE_MAGNIFIER = 0.00690 or 0.690% uint256 public constant MAX_TRANSFER_AMOUNT = 1e12 * 10**uint256(DECIMALS); uint256 public constant QUANTUM_BURN = 1e5 * 10**uint256(DECIMALS); uint256 public constant QUANTUM_REWARDS = 2e5 * 10**uint256(DECIMALS); uint256 public constant QUANTUM_LIQUIDITY = 3e5 * 10**uint256(DECIMALS); uint256 public constant MIN_HODL_TIME_SECONDS = 31556952; // A year spans 31556952 seconds. address public constant ADDR_HERTZ_REWARDS = 0x5cA00f843cd9649C41fC5B71c2814d927D69Df95; // Account4 using SafeMath for uint256; struct Fees { uint256 burn; uint256 rewards; uint256 liquidity; } struct StoreAddresses { address burn; address rewards; address liquidity; } struct StoreBalances { uint256 burn; uint256 rewards; uint256 liquidity; } struct Quantums { uint256 burn; uint256 rewards; uint256 liquidity; } struct Pulses { uint256 vote_burn; uint256 all_burn; uint256 lp_rewards; } event SetFees(Fees _fees); event SetStoreAddresses(StoreAddresses _storeAddresses); event SetPulses(Pulses _pulses); event SetMaxTransferAmount(uint256 _maxTransferAmount); event SwapAndLiquify(uint256 tokenSwapped, uint256 etherReceived, uint256 tokenLiquified, uint256 etherLiquified ); event TransferEther(address sender, address recipient, uint256 amount); Fees public fees; StoreAddresses public storeAddresses; Pulses public pulses; Quantums public quantums; uint256 public maxTransferAmount; mapping(address => uint) public lastTransferTime; uint256 public minHoldTimeSec; IPancakeRouter02 public dexRouter; address public pairWithWETH; address public pairWithHertz; mapping(address => bool) public isHolder; address[] public holders; bool public autoManagement; // Place this bool type at the bottom of storage. address public hertztoken; address public hertzRewardsAddress; /////////////////////////////////////////////////////////////////////////////////////////////// // // The logic (operational code) of the implementation. // You can upgrade this part of the implementation freely: // - add new state data itmes. // - override, add, or remove. // You cannot make changes to the above existing state data items. // ////////////////////////////////////////////////////////////////////////////////////////////// function initialize(address _dexRouter, address _hertztoken) public virtual initializer { // onlyOwwer is impossible call here. __Ownable_init(); __ERC20PresetFixedSupply_init("XDAO Utility Token", "XO", INITIAL_SUPPLY, owner()); __XDAO_init(_dexRouter, _hertztoken); } function __XDAO_init(address _dexRouter, address _hertztoken) public onlyOwner { __XDAO_init_unchained(_dexRouter, _hertztoken); } function __XDAO_init_unchained(address _dexRouter, address _hertztoken) public onlyOwner { revertToInitialSettings(_dexRouter, _hertztoken); } function revertToInitialSettings(address _dexRouter, address _hertztoken) public virtual onlyOwner { Fees memory _fese = Fees(FEES_BURNT, FEES_REWARDS, FEES_LIQUIDITY); setFees(_fese); StoreAddresses memory _addresses = StoreAddresses(ADDR_STORES_BURN, ADDR_STORES_REWARDS, ADDR_STORES_LIQUIDITY); setStoreAddresses(_addresses); Pulses memory _pulses = Pulses(PULSES_VOTE_BURN, PULSES_ALL_BURN, PULSES_LP_REWARDS); setPulses(_pulses); quantums = Quantums(QUANTUM_BURN, QUANTUM_REWARDS, QUANTUM_LIQUIDITY); maxTransferAmount = MAX_TRANSFER_AMOUNT; minHoldTimeSec = MIN_HODL_TIME_SECONDS; autoManagement = true; dexRouter = IPancakeRouter02(_dexRouter); pairWithWETH = createPoolWithWETH(_dexRouter); pairWithHertz = createPoolWithToken(_dexRouter, _hertztoken); hertztoken = _hertztoken; hertzRewardsAddress = ADDR_HERTZ_REWARDS; } function setFees(Fees memory _fees) public virtual onlyOwner { uint256 total; require(_fees.burn <= FEE_HUNDRED_PERCENT, "Burn fee out of range"); require(_fees.rewards <= FEE_HUNDRED_PERCENT, "Rewards fee out of range"); require(_fees.liquidity <= FEE_HUNDRED_PERCENT, "Liquidity fee out of range"); total = _fees.burn + _fees.rewards + _fees.liquidity; require(total <= FEE_HUNDRED_PERCENT, "Total fee out of range"); fees = _fees; emit SetFees(_fees); } function storeBalances() external view returns(StoreBalances memory balances) { balances.burn= _balances[storeAddresses.burn]; balances.rewards = _balances[storeAddresses.rewards]; balances.liquidity = _balances[storeAddresses.liquidity]; } function setStoreAddresses(StoreAddresses memory _storeAddresses) virtual public onlyOwner { require(_storeAddresses.burn != address(0) && _storeAddresses.burn != address(this), "Invalid fee address"); require(_storeAddresses.rewards != address(0) && _storeAddresses.burn != address(this), "Invalid fee address"); require(_storeAddresses.liquidity != address(0) && _storeAddresses.burn != address(this), "Invalid fee address"); storeAddresses = _storeAddresses; emit SetStoreAddresses(_storeAddresses); } function setPulses(Pulses memory _pulses) public virtual onlyOwner { require(_pulses.vote_burn <= FEE_HUNDRED_PERCENT, "Vote-burn rate of range"); require(_pulses.all_burn <= FEE_HUNDRED_PERCENT, "All-burn rate out of range"); require(_pulses.lp_rewards <= FEE_HUNDRED_PERCENT, "LP-rewards rate out of range"); pulses = _pulses; emit SetPulses(_pulses); } function setQuantums(Quantums memory _quantums) public virtual onlyOwner { require(_quantums.burn > 0, "Invalid quantum"); require(_quantums.rewards > 0, "Invalid quantum"); require(_quantums.liquidity > 0, "Invalid quantum"); quantums = _quantums; } function setMaxTransferAmount(uint256 _maxTransferAmount) virtual external onlyOwner { maxTransferAmount = _maxTransferAmount; emit SetMaxTransferAmount(_maxTransferAmount); } function setMinHoldTimeSec( uint256 _minHoldTimeSec ) virtual external onlyOwner { minHoldTimeSec = _minHoldTimeSec; } function setAutoManagement( bool _autoManagement ) external virtual onlyOwner { autoManagement = _autoManagement; } bool managing; modifier lockManaging { require( ! managing, "Nested managing."); managing = true; _; managing = false; } function createPoolWithWETH( address _routerAddress ) virtual public onlyOwner returns(address pool) { IPancakeRouter02 _dexRouter = IPancakeRouter02(_routerAddress); pool = IPancakeFactory(_dexRouter.factory()).getPair(address(this), _dexRouter.WETH()); if(pool == address(0)) { pool = IPancakeFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH()); } } function createPoolWithToken(address _routerAddress, address token ) virtual public onlyOwner returns(address pool) { IPancakeRouter02 _dexRouter = IPancakeRouter02(_routerAddress); pool = IPancakeFactory(_dexRouter.factory()).getPair(address(this), token); if(pool == address(0)) { pool = IPancakeFactory(_dexRouter.factory()).createPair(address(this), token); } } //==================================================================================================== function _sureTransfer(address sender, address recipient, uint256 amount) internal virtual { // No check at all. _balances[sender] -= amount; _balances[recipient] += amount; } uint256 internal _call_level; function _transfer(address sender, address recipient, uint256 amount) internal virtual { _call_level += 1; require(sender != address(0), "Transfer from zero address"); require(recipient != address(0), "Transfer to zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); if(_call_level == 1 && ! _isUnlimitedTransfer(sender, recipient) ) { require(amount <= maxTransferAmount, "Transfer exceeds limit"); } _balances[sender] -= amount; if(_call_level == 1 && ! _isFeeFreeTransfer(sender, recipient) ) { amount -= _payFees(sender, recipient, amount); } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); if(_call_level == 1 && autoManagement && ! _isUnmanageableTransfer(sender, recipient) ) { uint256 gasfee_left = gasleft() * tx.gasprice; bool worked = _cleanupStoresInQuantum(); //Assuming "function receive() external payable" exists. if( worked == true ) { uint256 gasfee_used = gasfee_left - gasleft() * tx.gasprice; (bool sent, bytes memory data) = tx.origin.call{ value: gasfee_used } (""); require(sent, "Failed to compensate"); emit TransferEther(address(this), tx.origin, gasfee_used); } } _afterTokenTransfer(sender, recipient, amount); _call_level -= 1; } function _isUnlimitedTransfer(address sender, address recipient) internal view virtual returns (bool unlimited) { // Start from highly frequent occurences. unlimited = _isBidirUnlimitedAddress(sender) || _isBidirUnlimitedAddress(recipient); } function _isBidirUnlimitedAddress(address _address) internal view virtual returns (bool unlimited) { unlimited = _address == owner() || _address == pairWithWETH || _address == pairWithHertz || _address == storeAddresses.burn || _address == storeAddresses.rewards || _address == storeAddresses.liquidity; } function _isFeeFreeTransfer(address sender, address recipient) internal view virtual returns (bool feeFree) { // Start from highly frequent occurences. feeFree = _isBidirFeeFreeAddress(sender) || _isBidirFeeFreeAddress(recipient); } function _isBidirFeeFreeAddress(address _address) internal view virtual returns (bool feeFree) { feeFree = _address == owner() || _address == pairWithWETH || _address == pairWithHertz || _address == storeAddresses.burn || _address == storeAddresses.rewards || _address == storeAddresses.liquidity; } function _isUnmanageableTransfer(address sender, address recipient) internal virtual view returns(bool _unmanageable) { _unmanageable = _isBidirUnmanageableAddress(sender) || _isBidirUnmanageableAddress(recipient); } function _isBidirUnmanageableAddress(address _address) internal view virtual returns (bool feeFree) { feeFree = _address == owner() || _address == pairWithWETH || _address == pairWithHertz || _address == storeAddresses.burn || _address == storeAddresses.rewards || _address == storeAddresses.liquidity; } function _payFees(address sender, address recipient, uint256 principal) internal virtual returns(uint256 total) { uint256 fee = principal.mul(fees.burn).div(FEE_MAGNIFIER); _balances[storeAddresses.burn] += fee; total += fee; emit Transfer(sender, storeAddresses.burn, fee); // console.log("marketing fee : ", fee); fee = principal.mul(fees.rewards).div(FEE_MAGNIFIER); _balances[storeAddresses.rewards] += fee; total += fee; emit Transfer(sender, storeAddresses.rewards, fee); // console.log("charity fee : ", fee); fee = principal.mul(fees.liquidity).div(FEE_MAGNIFIER); _balances[storeAddresses.liquidity] += fee; total += fee; emit Transfer(sender, storeAddresses.liquidity, fee); // console.log("lottery fee : ", fee); lastTransferTime[sender] = block.timestamp; lastTransferTime[recipient] = block.timestamp; } function _cleanupStoresInQuantum() internal virtual returns(bool worked) { // 1. Empty the storeAddresses.burn account completely. Do not change the order. if( _balances[storeAddresses.burn] > quantums.burn) { _cleanupBurnStore(); worked = true; } // 2. Empty the storeAddresses.rewards account completely. Do not change the order. if( _balances[storeAddresses.rewards] > quantums.rewards) { _cleanupRewardsStore(); worked = true; } // 3. Try and Empty the storeAddresses.liquidity account completely. Do not change the order. if( _balances[storeAddresses.liquidity] > quantums.liquidity) { _cleanupLiquidityStore(); worked = true; } } function cleanupBurnStore() external virtual onlyOwner { _cleanupBurnStore(); } function _cleanupBurnStore() internal virtual { _burn(storeAddresses.burn, _balances[storeAddresses.burn]); // burn all. } function cleanupRewardsStore() external virtual onlyOwner { _cleanupRewardsStore(); } function _cleanupRewardsStore() internal virtual lockManaging { // No! require(_balances[address(this)] == uint256(0), "Non-empty store space"); uint256 amount = _balances[storeAddresses.rewards]; _sureTransfer(storeAddresses.rewards, address(this), amount); _swapForToken(amount, hertztoken, hertzRewardsAddress); } function cleanupLiquidityStore() external virtual onlyOwner { _cleanupLiquidityStore(); } function _cleanupLiquidityStore() internal virtual lockManaging { uint256 etherInitial = address(this).balance; uint256 amountToLiquify = _balances[storeAddresses.liquidity]; if (amountToLiquify >= quantums.liquidity) { uint256 tokenForEther; { uint256 _reserveToken; uint256 _reserveEther; address token0 = IPancakePair(pairWithWETH).token0(); if (address(this) == token0) { (_reserveToken, _reserveEther,) = IPancakePair(pairWithWETH).getReserves(); } else { (_reserveEther, _reserveToken,) = IPancakePair(pairWithWETH).getReserves(); } uint256 b = 1998 * _reserveToken; // tokenForEther <= Ideal, leading to the token side, and not the ether side, remaining. tokenForEther = ( sqrt( b.mul(b) + 3992000 * _reserveToken * amountToLiquify) - b ) / 1996; } uint256 balance0 = _balances[address(this)]; _sureTransfer(storeAddresses.liquidity, address(this), _balances[storeAddresses.liquidity]); _swapForEther(tokenForEther); uint256 tokenAfterSwap = _balances[address(this)]; uint256 etherAfterSwap = address(this).balance; uint256 tokenToAddLiq = amountToLiquify - tokenForEther; uint256 etherToAddLiq = etherAfterSwap - etherInitial; _addLiquidity(tokenToAddLiq, etherToAddLiq); // No gurantee that the both amounts are deposited without refund. uint256 tokenAfterAddLiq = _balances[address(this)]; uint256 etherAfterAddLiq = address(this).balance; require(etherAfterAddLiq >= etherInitial, "\tEther loss in address(this) account"); console.log("\tOn-chain messages..."); console.log("\tTotal XO wei that were provided for liquefying: ", amountToLiquify); console.log("\t1. XO wei that were forwarded to the pool directly: ", tokenToAddLiq); console.log("\t2. XO wei that were sold for FTM at the dex: ", tokenForEther); console.log("\t3. FTM wei that were bought with the XOs at the dex: ", etherAfterSwap - etherInitial); console.log("\t4. FTM wei that were forwarded to the pool: ", etherAfterSwap - etherInitial); console.log("\t5. XO wei that the pool didn't accept: ", tokenAfterAddLiq - balance0); console.log("\t6. FTM wei that the pool didn't accept: ", etherAfterAddLiq - etherInitial); console.log("\t7. PPM that failed to be accepted by the pool: ", (tokenAfterAddLiq - balance0) * 10**6 / amountToLiquify ); emit SwapAndLiquify( tokenForEther, // tokenSwapped. token decreased by swap etherAfterSwap - etherInitial, // etherReceived. ether increased by swap tokenAfterAddLiq - tokenAfterSwap, // tokenLiquified. token decreased by addLiquidity etherAfterAddLiq - etherAfterSwap // etherLiquified. ether decreased by addLiquidity ); } } function _swapForEther(uint256 tokenAmount) virtual internal { require( _balances[address(this)] >= tokenAmount, "" ); address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); // The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account. // The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn ); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), // targetAccount block.timestamp ); } function _swapForToken(uint256 amountIn, address targetToken, address targetAccount) virtual internal { require( _balances[address(this)] >= amountIn, "" ); address[] memory path = new address[](2); path[0] = address(this); path[1] = targetToken; // The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account. // The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn ); _approve(address(this), address(dexRouter), amountIn); dexRouter.swapExactTokensForTokens( amountIn, 0, path, targetAccount, block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) virtual internal { // The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account. // The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn ); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), // What if the owner changes? Why not use a 3rd, neutral address? block.timestamp ); } receive() external payable {} function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Calculate the square root of the perfect square of a power of two that is the closest to x. uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. //unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; //} } uint256[10] private __gap; }
Place this bool type at the bottom of storage.
bool public autoManagement;
7,234,359
[ 1, 6029, 333, 1426, 618, 622, 326, 5469, 434, 2502, 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, 1426, 1071, 3656, 10998, 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 ]