file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT import "../Registry.sol"; import "../Module.sol"; import "../interfaces/IBank.sol"; import "../interfaces/IMember.sol"; import "../../guards/ModuleGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract BankContract is IBank, Module, ModuleGuard { using SafeMath for uint256; event TokensCollected( address indexed moloch, address indexed token, uint256 amountToCollect ); event Transfer( address indexed fromAddress, address indexed toAddress, address token, uint256 amount ); address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); uint256 public constant MAX_TOKENS = 100; struct BankingState { address[] tokens; mapping(address => bool) availableTokens; mapping(address => mapping(address => uint256)) tokenBalances; } mapping(address => BankingState) states; function addToEscrow( Registry dao, address token, uint256 amount ) external override onlyModule(dao) { require( token != GUILD && token != ESCROW && token != TOTAL, "invalid token" ); unsafeAddToBalance(address(dao), ESCROW, token, amount); if (!states[address(dao)].availableTokens[token]) { require( states[address(dao)].tokens.length < MAX_TOKENS, "max limit reached" ); states[address(dao)].availableTokens[token] = true; states[address(dao)].tokens.push(token); } } function addToGuild( Registry dao, address token, uint256 amount ) external override onlyModule(dao) { require( token != GUILD && token != ESCROW && token != TOTAL, "invalid token" ); unsafeAddToBalance(address(dao), GUILD, token, amount); if (!states[address(dao)].availableTokens[token]) { require( states[address(dao)].tokens.length < MAX_TOKENS, "max limit reached" ); states[address(dao)].availableTokens[token] = true; states[address(dao)].tokens.push(token); } } function transferFromGuild( Registry dao, address applicant, address token, uint256 amount ) external override onlyModule(dao) { require( states[address(dao)].tokenBalances[GUILD][token] >= amount, "insufficient balance" ); unsafeSubtractFromBalance(address(dao), GUILD, token, amount); unsafeAddToBalance(address(dao), applicant, token, amount); emit Transfer(GUILD, applicant, token, amount); } function ragequit( Registry dao, address memberAddr, uint256 sharesToBurn ) external override onlyModule(dao) { //Get the total shares before burning member shares IMember memberContract = IMember(dao.getAddress(MEMBER_MODULE)); uint256 totalShares = memberContract.getTotalShares(); //Burn shares if member has enough shares memberContract.burnShares(dao, memberAddr, sharesToBurn); //Update internal Guild and Member balances for (uint256 i = 0; i < states[address(dao)].tokens.length; i++) { address token = states[address(dao)].tokens[i]; uint256 amountToRagequit = fairShare( states[address(dao)].tokenBalances[GUILD][token], sharesToBurn, totalShares ); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution // (which would break ragekicks) if a token overflows, // it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways states[address(dao)].tokenBalances[GUILD][ token ] -= amountToRagequit; states[address(dao)].tokenBalances[memberAddr][ token ] += amountToRagequit; //TODO: do we want to emit an event for each token transfer? // emit Transfer(GUILD, applicant, token, amount); } } } function isNotReservedAddress(address applicant) external pure override returns (bool) { return applicant != address(0x0) && applicant != GUILD && applicant != ESCROW && applicant != TOTAL; } /** * Public read-only functions */ function balanceOf( Registry dao, address user, address token ) external view override returns (uint256) { return states[address(dao)].tokenBalances[user][token]; } /** * Internal bookkeeping */ function unsafeAddToBalance( address dao, address user, address token, uint256 amount ) internal { states[dao].tokenBalances[user][token] += amount; states[dao].tokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance( address dao, address user, address token, uint256 amount ) internal { states[dao].tokenBalances[user][token] -= amount; states[dao].tokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer( address dao, address from, address to, address token, uint256 amount ) internal { unsafeSubtractFromBalance(dao, from, token, amount); unsafeAddToBalance(dao, to, token, amount); } /** * Internal utility */ function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0, "total shares should not be 0"); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / _totalShares; } return (balance / _totalShares) * shares; } }
* Internal utility/ no overflow in multiplication above?
function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0, "total shares should not be 0"); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { return prod / _totalShares; } return (balance / _totalShares) * shares; }
15,805,049
[ 1, 3061, 12788, 19, 1158, 9391, 316, 23066, 5721, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 1826, 9535, 12, 203, 3639, 2254, 5034, 11013, 16, 203, 3639, 2254, 5034, 24123, 16, 203, 3639, 2254, 5034, 389, 4963, 24051, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 24899, 4963, 24051, 480, 374, 16, 315, 4963, 24123, 1410, 486, 506, 374, 8863, 203, 3639, 309, 261, 12296, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 10791, 273, 11013, 380, 24123, 31, 203, 3639, 309, 261, 17672, 342, 11013, 422, 24123, 13, 288, 203, 5411, 327, 10791, 342, 389, 4963, 24051, 31, 203, 3639, 289, 203, 3639, 327, 261, 12296, 342, 389, 4963, 24051, 13, 380, 24123, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /// @title A facet of CSportsCore that holds all important constants and modifiers /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsConstants { /// @dev The maximum # of marketing tokens that can ever be created /// by the commissioner. uint16 public MAX_MARKETING_TOKENS = 2500; /// @dev The starting price for commissioner auctions (if the average /// of the last 2 is less than this, we will use this value) /// A finney is 1/1000 of an ether. uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby /// @dev The duration of commissioner auctions uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing; /// @dev Number of seconds in a week uint32 constant WEEK_SECS = 1 weeks; } /// @title A facet of CSportsCore that manages an individual's authorized role against access privileges. /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsAuth is CSportsConstants { // This facet controls access control for CryptoSports. 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 CSportsCore constructor. // // - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts. // // - The COO: The COO can perform administrative functions. // // - The Commisioner can perform "oracle" functions like adding new real world players, // setting players active/inactive, and scoring contests. // /// @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; address public commissionerAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Flag that identifies whether or not we are in development and should allow development /// only functions to be called. bool public isDevelopment = true; /// @dev Access modifier to allow access to development mode functions modifier onlyUnderDevelopment() { require(isDevelopment == true); _; } /// @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); _; } /// @dev Access modifier for Commissioner-only functionality modifier onlyCommissioner() { require(msg.sender == commissionerAddress); _; } /// @dev Requires any one of the C level addresses modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == commissionerAddress ); _; } /// @dev prevents contracts from hitting the method modifier notContract() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0); _; } /// @dev One way switch to set the contract into prodution mode. This is one /// way in that the contract can never be set back into development mode. Calling /// this function will block all future calls to functions that are meant for /// access only while we are under development. It will also enable more strict /// additional checking on various parameters and settings. function setProduction() public onlyCEO onlyUnderDevelopment { isDevelopment = false; } /// @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; } /// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO. /// @param _newCommissioner The address of the new COO function setCommissioner(address _newCommissioner) public onlyCEO { require(_newCommissioner != address(0)); commissionerAddress = _newCommissioner; } /// @dev Assigns all C-Level addresses /// @param _ceo CEO address /// @param _cfo CFO address /// @param _coo COO address /// @param _commish Commissioner address function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO { require(_ceo != address(0)); require(_cfo != address(0)); require(_coo != address(0)); require(_commish != address(0)); ceoAddress = _ceo; cfoAddress = _cfo; cooAddress = _coo; commissionerAddress = _commish; } /// @dev Transfers the balance of this contract to the CFO function withdrawBalance() external onlyCFO { cfoAddress.transfer(address(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 { paused = false; } } /// @dev Interface required by league roster contract to access /// the mintPlayers(...) function interface CSportsRosterInterface { /// @dev Called by core contract as a sanity check function isLeagueRosterContract() external pure returns (bool); /// @dev Called to indicate that a commissioner auction has completed function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) external; /// @dev Called to indicate that a commissioner auction was canceled function commissionerAuctionCancelled(uint32 _rosterIndex) external view; /// @dev Returns the metadata for a specific real world player token function getMetadata(uint128 _md5Token) external view returns (string); /// @dev Called to return a roster index given the MD5 function getRealWorldPlayerRosterIndex(uint128 _md5Token) external view returns (uint128); /// @dev Returns a player structure given its index function realWorldPlayerFromIndex(uint128 idx) external view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled); /// @dev Called to update a real world player entry - only used dureing development function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) external; } /// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster /// contract. Also referenced by CSportsCore. /// @author CryptoSports, Inc. (http://cryptosports.team) contract CSportsRosterPlayer { struct RealWorldPlayer { // The player's certified identification. This is the md5 hash of // {player's last name}-{player's first name}-{player's birthday in YYYY-MM-DD format}-{serial number} // where the serial number is usually 0, but gives us an ability to deal with making // sure all MD5s are unique. uint128 md5Token; // Stores the average sale price of the most recent 2 commissioner sales uint128 prevCommissionerSalePrice; // The last time this real world player was minted. uint64 lastMintedTime; // The number of PlayerTokens minted for this real world player uint32 mintedCount; // When true, there is an active auction for this player owned by // the commissioner (indicating a gen0 minting auction is in progress) bool hasActiveCommissionerAuction; // Indicates this real world player can be actively minted bool mintingEnabled; // Any metadata we want to attach to this player (in JSON format) string metadata; } } /// @title CSportsTeam Interface /// @dev This interface defines methods required by the CSportsContestCore /// in implementing a contest. /// @author CryptoSports contract CSportsTeam { bool public isTeamContract; /// @dev Define team events event TeamCreated(uint256 teamId, address owner); event TeamUpdated(uint256 teamId); event TeamReleased(uint256 teamId); event TeamScored(uint256 teamId, int32 score, uint32 place); event TeamPaid(uint256 teamId); function setCoreContractAddress(address _address) public; function setLeagueRosterContractAddress(address _address) public; function setContestContractAddress(address _address) public; function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32); function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public; function releaseTeam(uint32 _teamId) public; function getTeamOwner(uint32 _teamId) public view returns (address); function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public; function getScore(uint32 _teamId) public view returns (int32); function getPlace(uint32 _teamId) public view returns (uint32); function ownsPlayerTokens(uint32 _teamId) public view returns (bool); function refunded(uint32 _teamId) public; function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]); function getTeam(uint32 _teamId) public view returns ( address _owner, int32 _score, uint32 _place, bool _holdsEntryFee, bool _ownsPlayerTokens); } /// @title Base contract for CryptoSports. Holds all common structs, events and base variables. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsBase is CSportsAuth, CSportsRosterPlayer { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// @dev This emits when a commissioner auction is successfully closed event CommissionerAuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); /// @dev This emits when a commissioner auction is canceled event CommissionerAuctionCanceled(uint256 tokenId); /******************/ /*** DATA TYPES ***/ /******************/ /// @dev The main player token structure. Every released player in the League /// is represented by a single instance of this structure. struct PlayerToken { // @dev ID of the real world player this token represents. We can only have // a max of 4,294,967,295 real world players, which seems to be enough for // a while (haha) uint32 realWorldPlayerId; // @dev Serial number indicating the number of PlayerToken(s) for this // same realWorldPlayerId existed at the time this token was minted. uint32 serialNumber; // The timestamp from the block when this player token was minted. uint64 mintedTime; // The most recent sale price of the player token in an auction uint128 mostRecentPrice; } /**************************/ /*** MAPPINGS (STORAGE) ***/ /**************************/ /// @dev A mapping from a PlayerToken ID to the address that owns it. All /// PlayerTokens have an owner (newly minted PlayerTokens are owned by /// the core contract). mapping (uint256 => address) public playerTokenToOwner; /// @dev Maps a PlayerToken ID to an address approved to take ownership. mapping (uint256 => address) public playerTokenToApproved; // @dev A mapping to a given address' tokens mapping(address => uint32[]) public ownedTokens; // @dev A mapping that relates a token id to an index into the // ownedTokens[currentOwner] array. mapping(uint32 => uint32) tokenToOwnedTokensIndex; /// @dev Maps operators mapping(address => mapping(address => bool)) operators; // This mapping and corresponding uint16 represent marketing tokens // that can be created by the commissioner (up to remainingMarketingTokens) // and then given to third parties in the form of 4 words that sha256 // hash into the key for the mapping. // // Maps uint256(keccak256) => leagueRosterPlayerMD5 uint16 public remainingMarketingTokens = MAX_MARKETING_TOKENS; mapping (uint256 => uint128) marketingTokens; /***************/ /*** STORAGE ***/ /***************/ /// @dev Instance of our CSportsLeagueRoster contract. Can be set by /// the CEO only once because this immutable tie to the league roster /// is what relates a playerToken to a real world player. If we could /// update the leagueRosterContract, we could in effect de-value the /// ownership of a playerToken by switching the real world player it /// represents. CSportsRosterInterface public leagueRosterContract; /// @dev Addresses of team contract that is authorized to hold player /// tokens for contests. CSportsTeam public teamContract; /// @dev An array containing all PlayerTokens in existence. PlayerToken[] public playerTokens; /************************************/ /*** RESTRICTED C-LEVEL FUNCTIONS ***/ /************************************/ /// @dev Sets the reference to the CSportsLeagueRoster contract. /// @param _address - Address of CSportsLeagueRoster contract. function setLeagueRosterContractAddress(address _address) public onlyCEO { // This method may only be called once to guarantee the immutable // nature of owning a real world player. if (!isDevelopment) { require(leagueRosterContract == address(0)); } CSportsRosterInterface candidateContract = CSportsRosterInterface(_address); // NOTE: verify that a contract is what we expect (not foolproof, just // a sanity check) require(candidateContract.isLeagueRosterContract()); // Set the new contract address leagueRosterContract = candidateContract; } /// @dev Adds an authorized team contract that can hold player tokens /// on behalf of a contest, and will return them to the original /// owner when the contest is complete (or if entry is canceled by /// the original owner, or if the contest is canceled). function setTeamContractAddress(address _address) public onlyCEO { CSportsTeam candidateContract = CSportsTeam(_address); // NOTE: verify that a contract is what we expect (not foolproof, just // a sanity check) require(candidateContract.isTeamContract()); // Set the new contract address teamContract = candidateContract; } /**************************/ /*** INTERNAL FUNCTIONS ***/ /**************************/ /// @dev Identifies whether or not the addressToTest is a contract or not /// @param addressToTest The address we are interested in function _isContract(address addressToTest) internal view returns (bool) { uint size; assembly { size := extcodesize(addressToTest) } return (size > 0); } /// @dev Returns TRUE if the token exists /// @param _tokenId ID to check function _tokenExists(uint256 _tokenId) internal view returns (bool) { return (_tokenId < playerTokens.length); } /// @dev An internal method that mints a new playerToken and stores it /// in the playerTokens array. /// @param _realWorldPlayerId ID of the real world player to mint /// @param _serialNumber - Indicates the number of playerTokens for _realWorldPlayerId /// that exist prior to this to-be-minted playerToken. /// @param _owner - The owner of this newly minted playerToken function _mintPlayer(uint32 _realWorldPlayerId, uint32 _serialNumber, address _owner) internal returns (uint32) { // We are careful here to make sure the calling contract keeps within // our structure's size constraints. Highly unlikely we would ever // get to a point where these constraints would be a problem. require(_realWorldPlayerId < 4294967295); require(_serialNumber < 4294967295); PlayerToken memory _player = PlayerToken({ realWorldPlayerId: _realWorldPlayerId, serialNumber: _serialNumber, mintedTime: uint64(now), mostRecentPrice: 0 }); uint256 newPlayerTokenId = playerTokens.push(_player) - 1; // It's probably never going to happen, 4 billion playerToken(s) is A LOT, but // let's just be 100% sure we never let this happen. require(newPlayerTokenId < 4294967295); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPlayerTokenId); return uint32(newPlayerTokenId); } /// @dev Removes a token (specified by ID) from ownedTokens and /// tokenToOwnedTokensIndex mappings for a given address. /// @param _from Address to remove from /// @param _tokenId ID of token to remove function _removeTokenFrom(address _from, uint256 _tokenId) internal { // Grab the index into the _from owner's ownedTokens array uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)]; // Remove the _tokenId from ownedTokens[_from] array uint lastIndex = ownedTokens[_from].length - 1; uint32 lastToken = ownedTokens[_from][lastIndex]; // Swap the last token into the fromIndex position (which is _tokenId's // location in the ownedTokens array) and shorten the array ownedTokens[_from][fromIndex] = lastToken; ownedTokens[_from].length--; // Since we moved lastToken, we need to update its // entry in the tokenToOwnedTokensIndex tokenToOwnedTokensIndex[lastToken] = fromIndex; // _tokenId is no longer mapped tokenToOwnedTokensIndex[uint32(_tokenId)] = 0; } /// @dev Adds a token (specified by ID) to ownedTokens and /// tokenToOwnedTokensIndex mappings for a given address. /// @param _to Address to add to /// @param _tokenId ID of token to remove function _addTokenTo(address _to, uint256 _tokenId) internal { uint32 toIndex = uint32(ownedTokens[_to].push(uint32(_tokenId))) - 1; tokenToOwnedTokensIndex[uint32(_tokenId)] = toIndex; } /// @dev Assigns ownership of a specific PlayerToken to an address. /// @param _from - Address of who this transfer is from /// @param _to - Address of who to tranfer to /// @param _tokenId - The ID of the playerToken to transfer function _transfer(address _from, address _to, uint256 _tokenId) internal { // transfer ownership playerTokenToOwner[_tokenId] = _to; // When minting brand new PlayerTokens, the _from is 0x0, but we don't deal with // owned tokens for the 0x0 address. if (_from != address(0)) { // Remove the _tokenId from ownedTokens[_from] array (remove first because // this method will zero out the tokenToOwnedTokensIndex[_tokenId], which would // stomp on the _addTokenTo setting of this value) _removeTokenFrom(_from, _tokenId); // Clear our approved mapping for this token delete playerTokenToApproved[_tokenId]; } // Now add the token to the _to address' ownership structures _addTokenTo(_to, _tokenId); // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev Converts a uint to its string equivalent /// @param v uint to convert function uintToString(uint v) internal pure returns (string str) { bytes32 b32 = uintToBytes32(v); str = bytes32ToString(b32); } /// @dev Converts a uint to a bytes32 /// @param v uint to convert function uintToBytes32(uint v) internal pure returns (bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } /// @dev Converts bytes32 to a string /// @param data bytes32 to convert function bytes32ToString (bytes32 data) internal pure returns (string) { uint count = 0; bytes memory bytesString = new bytes(32); // = 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; count++; } else { break; } } bytes memory s = new bytes(count); for (j = 0; j < count; j++) { s[j] = bytesString[j]; } return string(s); } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. /// /// MOVED THIS TO CSportsBase because of how class structure is derived. /// event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f. interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x780e9d63. interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title The facet of the CSports core contract that manages ownership, ERC-721 compliant. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsOwnership is CSportsBase { /// @notice These are set in the contract constructor at deployment time string _name; string _symbol; string _tokenURI; // bool public implementsERC721 = true; // function implementsERC721() public pure returns (bool) { return true; } /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string) { return _name; } /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string) { return _symbol; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string ret) { string memory tokenIdAsString = uintToString(uint(_tokenId)); ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/")); } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = playerTokenToOwner[_tokenId]; require(owner != address(0)); } /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) public view returns (uint256 count) { // I am not a big fan of referencing a property on an array element // that may not exist. But if it does not exist, Solidity will return 0 // which is right. return ownedTokens[_owner].length; } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(_to != address(0)); require (_tokenExists(_tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); require(_owns(_from, _tokenId)); // Validate the sender require(_owns(msg.sender, _tokenId) || // sender owns the token (msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address operators[_from][msg.sender]); // sender is an authorized operator for this token // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Transfer ownership of a batch of NFTs -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for all NFTs. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// any `_tokenId` is not a valid NFT. /// @param _from - Current owner of the token being authorized for transfer /// @param _to - Address we are transferring to /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchTransferFrom( address _from, address _to, uint32[] _tokenIds ) public whenNotPaused { for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); require(_owns(_from, _tokenId)); // Validate the sender require(_owns(msg.sender, _tokenId) || // sender owns the token (msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address operators[_from][msg.sender]); // sender is an authorized operator for this token // Reassign ownership, clear pending approvals (not necessary here), // and emit Transfer event. _transfer(_from, _to, _tokenId); } } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _to The new approved NFT controller /// @param _tokenId The NFT to approve function approve( address _to, uint256 _tokenId ) public whenNotPaused { address owner = ownerOf(_tokenId); require(_to != owner); // Only an owner or authorized operator can grant transfer approval. require((msg.sender == owner) || (operators[ownerOf(_tokenId)][msg.sender])); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchApprove( address _to, uint32[] _tokenIds ) public whenNotPaused { for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Only an owner or authorized operator can grant transfer approval. require(_owns(msg.sender, _tokenId) || (operators[ownerOf(_tokenId)][msg.sender])); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } } /// @notice Escrows all of the tokensIds passed by transfering ownership /// to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT. /// @param _owner - Current owner of the token being authorized for transfer /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchEscrowToTeamContract( address _owner, uint32[] _tokenIds ) public whenNotPaused { require(teamContract != address(0)); require(msg.sender == address(teamContract)); for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Only an owner can transfer the token. require(_owns(_owner, _tokenId)); // Reassign ownership, clear pending approvals (not necessary here), // and emit Transfer event. _transfer(_owner, teamContract, _tokenId); } } bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable { transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { ERC721TokenReceiver receiver = ERC721TokenReceiver(_to); bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, data); require(response == TOKEN_RECEIVED_SIG); } } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { require(_to != address(0)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { ERC721TokenReceiver receiver = ERC721TokenReceiver(_to); bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, ""); require(response == TOKEN_RECEIVED_SIG); } } /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint) { return playerTokens.length; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `index` >= `balanceOf(owner)` or if /// `owner` is the zero address, representing invalid NFTs. /// @param owner An address where we are interested in NFTs owned by them /// @param index A counter less than `balanceOf(owner)` /// @return The token identifier for the `index`th NFT assigned to `owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId) { require(owner != address(0)); require(index < balanceOf(owner)); return ownedTokens[owner][index]; } /// @notice Enumerate valid NFTs /// @dev Throws if `index` >= `totalSupply()`. /// @param index A counter less than `totalSupply()` /// @return The token identifier for the `index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 index) external view returns (uint256) { require (_tokenExists(index)); return index; } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { require(_operator != msg.sender); operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address) { require(_tokenExists(_tokenId)); return playerTokenToApproved[_tokenId]; } /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return ( interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x80ac58cd || // ERC-721 interfaceID == 0x780e9d63); // ERC721Enumerable } // 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 PlayerToken. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return playerTokenToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular PlayerToken. /// @param _claimant the address we are confirming PlayerToken is approved for. /// @param _tokenId PlayerToken id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return playerTokenToApproved[_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 PlayerToken on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { playerTokenToApproved[_tokenId] = _approved; } } /// @dev Interface to the sale clock auction contract interface CSportsAuctionInterface { /// @dev Sanity check that allows us to ensure that we are pointing to the /// right auction in our setSaleAuctionAddress() call. function isSaleClockAuction() external pure returns (bool); /// @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 ) external; /// @dev Reprices (and updates duration) of an array of tokens that are currently /// being auctioned by this contract. /// @param _tokenIds Array of tokenIds corresponding to auctions being updated /// @param _startingPrices New starting prices /// @param _endingPrices New ending price /// @param _duration New duration /// @param _seller Address of the seller in all specified auctions to be updated function repriceAuctions( uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256 _duration, address _seller ) external; /// @dev Cancels an auction that hasn't been won yet by calling /// the super(...) and then notifying any listener. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external; /// @dev Withdraw the total contract balance to the core contract function withdrawBalance() external; } /// @title Interface to allow a contract to listen to auction events. contract SaleClockAuctionListener { function implementsSaleClockAuctionListener() public pure returns (bool); function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public; function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public; function auctionCancelled(uint256 tokenId, address seller) public; } /// @title The facet of the CSports core contract that manages interfacing with auctions /// @author CryptoSports, Inc. (http://cryptosports.team) /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsAuction is CSportsOwnership, SaleClockAuctionListener { // Holds a reference to our saleClockAuctionContract CSportsAuctionInterface public saleClockAuctionContract; /// @dev SaleClockAuctionLIstener interface method concrete implementation function implementsSaleClockAuctionListener() public pure returns (bool) { return true; } /// @dev SaleClockAuctionLIstener interface method concrete implementation function auctionCreated(uint256 /* tokenId */, address /* seller */, uint128 /* startingPrice */, uint128 /* endingPrice */, uint64 /* duration */) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); } /// @dev SaleClockAuctionLIstener interface method concrete implementation /// @param tokenId - ID of the token whose auction successfully completed /// @param totalPrice - Price at which the auction closed at /// @param seller - Account address of the auction seller /// @param winner - Account address of the auction winner (buyer) function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); // Record the most recent sale price to the token PlayerToken storage _playerToken = playerTokens[tokenId]; _playerToken.mostRecentPrice = totalPrice; if (seller == address(this)) { // We completed a commissioner auction! leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice); emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner); } } /// @dev SaleClockAuctionLIstener interface method concrete implementation /// @param tokenId - ID of the token whose auction was cancelled /// @param seller - Account address of seller who decided to cancel the auction function auctionCancelled(uint256 tokenId, address seller) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); if (seller == address(this)) { // We cancelled a commissioner auction! leagueRosterContract.commissionerAuctionCancelled(playerTokens[tokenId].realWorldPlayerId); emit CommissionerAuctionCanceled(tokenId); } } /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionContractAddress(address _address) public onlyCEO { require(_address != address(0)); CSportsAuctionInterface candidateContract = CSportsAuctionInterface(_address); // Sanity check require(candidateContract.isSaleClockAuction()); // Set the new contract address saleClockAuctionContract = candidateContract; } /// @dev Allows the commissioner to cancel his auctions (which are owned /// by this contract) function cancelCommissionerAuction(uint32 tokenId) public onlyCommissioner { require(saleClockAuctionContract != address(0)); saleClockAuctionContract.cancelAuction(tokenId); } /// @dev Put a player up for auction. The message sender must own the /// player token being put up for auction. /// @param _playerTokenId - ID of playerToken to be auctioned /// @param _startingPrice - Starting price in wei /// @param _endingPrice - Ending price in wei /// @param _duration - Duration in seconds function createSaleAuction( uint256 _playerTokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If player is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _playerTokenId)); _approve(_playerTokenId, saleClockAuctionContract); // saleClockAuctionContract.createAuction throws if inputs are invalid and clears // transfer after escrowing the player. saleClockAuctionContract.createAuction( _playerTokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the CSportsCore contract. We use two-step withdrawal to /// avoid two transfer calls in the auction bid function. /// To withdraw from this CSportsCore contract, the CFO must call /// the withdrawBalance(...) function defined in CSportsAuth. function withdrawAuctionBalances() external onlyCOO { saleClockAuctionContract.withdrawBalance(); } } /// @title The facet of the CSportsCore contract that manages minting new PlayerTokens /// @author CryptoSports, Inc. (http://cryptosports.team) /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsMinting is CSportsAuction { /// @dev MarketingTokenRedeemed event is fired when a marketing token has been redeemed event MarketingTokenRedeemed(uint256 hash, uint128 rwpMd5, address indexed recipient); /// @dev MarketingTokenCreated event is fired when a marketing token has been created event MarketingTokenCreated(uint256 hash, uint128 rwpMd5); /// @dev MarketingTokenReplaced event is fired when a marketing token has been replaced event MarketingTokenReplaced(uint256 oldHash, uint256 newHash, uint128 rwpMd5); /// @dev Sanity check that identifies this contract as having minting capability function isMinter() public pure returns (bool) { return true; } /// @dev Utility function to make it easy to keccak256 a string in python or javascript using /// the exact algorythm used by Solidity. function getKeccak256(string stringToHash) public pure returns (uint256) { return uint256(keccak256(abi.encodePacked(stringToHash))); } /// @dev Allows the commissioner to load up our marketingTokens mapping with up to /// MAX_MARKETING_TOKENS marketing tokens that can be created if one knows the words /// to keccak256 and match the keywordHash passed here. Use web3.utils.soliditySha3(param1 [, param2, ...]) /// to create this hash. /// /// ONLY THE COMMISSIONER CAN CREATE MARKETING TOKENS, AND ONLY UP TO MAX_MARKETING_TOKENS OF THEM /// /// @param keywordHash - keccak256 of a known set of keyWords /// @param md5Token - The md5 key in the leagueRosterContract that specifies the player /// player token that will be minted and transfered by the redeemMarketingToken(...) method. function addMarketingToken(uint256 keywordHash, uint128 md5Token) public onlyCommissioner { require(remainingMarketingTokens > 0); require(marketingTokens[keywordHash] == 0); // Make sure the md5Token exists in the league roster uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(md5Token); require(_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); // Map the keyword Hash to the RWP md5 and decrement the remainingMarketingTokens property remainingMarketingTokens--; marketingTokens[keywordHash] = md5Token; emit MarketingTokenCreated(keywordHash, md5Token); } /// @dev This method allows the commish to replace an existing marketing token that has /// not been used with a new one (new hash and mdt). Since we are replacing, we co not /// have to deal with remainingMarketingTokens in any way. This is to allow for replacing /// marketing tokens that have not been redeemed and aren't likely to be redeemed (breakage) /// /// ONLY THE COMMISSIONER CAN ACCESS THIS METHOD /// /// @param oldKeywordHash Hash to replace /// @param newKeywordHash Hash to replace with /// @param md5Token The md5 key in the leagueRosterContract that specifies the player function replaceMarketingToken(uint256 oldKeywordHash, uint256 newKeywordHash, uint128 md5Token) public onlyCommissioner { uint128 _md5Token = marketingTokens[oldKeywordHash]; if (_md5Token != 0) { marketingTokens[oldKeywordHash] = 0; marketingTokens[newKeywordHash] = md5Token; emit MarketingTokenReplaced(oldKeywordHash, newKeywordHash, md5Token); } } /// @dev Returns the real world player's MD5 key from a keywords string. A 0x00 returned /// value means the keyword string parameter isn't mapped to a marketing token. /// @param keyWords Keywords to use to look up RWP MD5 // /// ANYONE CAN VALIDATE A KEYWORD STRING (MAP IT TO AN MD5 IF IT HAS ONE) /// /// @param keyWords - A string that will keccak256 to an entry in the marketingTokens /// mapping (or not) function MD5FromMarketingKeywords(string keyWords) public view returns (uint128) { uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords))); uint128 _md5Token = marketingTokens[keyWordsHash]; return _md5Token; } /// @dev Allows anyone to try to redeem a marketing token by passing N words that will /// be SHA256'ed to match an entry in our marketingTokens mapping. If a match is found, /// a CryptoSports token is created that corresponds to the md5 retrieved /// from the marketingTokens mapping and its owner is assigned as the msg.sender. /// /// ANYONE CAN REDEEM A MARKETING token /// /// @param keyWords - A string that will keccak256 to an entry in the marketingTokens mapping function redeemMarketingToken(string keyWords) public { uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords))); uint128 _md5Token = marketingTokens[keyWordsHash]; if (_md5Token != 0) { // Only one redemption per set of keywords marketingTokens[keyWordsHash] = 0; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Grab the real world player record from the leagueRosterContract RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); // Mint this player, sending it to the message sender _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, msg.sender); // Finally, update our realWorldPlayer record to reflect the fact that we just // minted a new one, and there is an active commish auction. The only portion of // the RWP record we change here is an update to the mingedCount. leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled); emit MarketingTokenRedeemed(keyWordsHash, _rwp.md5Token, msg.sender); } } } /// @dev Returns an array of minimum auction starting prices for an array of players /// specified by their MD5s. /// @param _md5Tokens MD5s in the league roster for the players we are inquiring about. function minStartPriceForCommishAuctions(uint128[] _md5Tokens) public view onlyCommissioner returns (uint128[50]) { require (_md5Tokens.length <= 50); uint128[50] memory minPricesArray; for (uint32 i = 0; i < _md5Tokens.length; i++) { uint128 _md5Token = _md5Tokens[i]; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Cannot mint a non-existent real world player continue; } RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); // Skip this if there is no player associated with the md5 specified if (_rwp.md5Token != _md5Token) continue; minPricesArray[i] = uint128(_computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice)); } return minPricesArray; } /// @dev Creates newly minted playerTokens and puts them up for auction. This method /// can only be called by the commissioner, and checks to make sure certian minting /// conditions are met (reverting if not met): /// * The MD5 of the RWP specified must exist in the CSportsLeagueRoster contract /// * Cannot mint a realWorldPlayer that currently has an active commissioner auction /// * Cannot mint realWorldPlayer that does not have minting enabled /// * Cannot mint realWorldPlayer with a start price exceeding our minimum /// If any of the above conditions fails to be met, then no player tokens will be /// minted. /// /// *** ONLY THE COMMISSIONER OR THE LEAGUE ROSTER CONTRACT CAN CALL THIS FUNCTION *** /// /// @param _md5Tokens - array of md5Tokens representing realWorldPlayer that we are minting. /// @param _startPrice - the starting price for the auction (0 will set to current minimum price) function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public { require(leagueRosterContract != address(0)); require(saleClockAuctionContract != address(0)); require((msg.sender == commissionerAddress) || (msg.sender == address(leagueRosterContract))); for (uint32 i = 0; i < _md5Tokens.length; i++) { uint128 _md5Token = _md5Tokens[i]; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Cannot mint a non-existent real world player continue; } // We don't have to check _rosterIndex here because the getRealWorldPlayerRosterIndex(...) // method always returns a valid index. RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); if (_rwp.md5Token != _md5Token) continue; if (!_rwp.mintingEnabled) continue; // Enforce the restrictions that there can ever only be a single outstanding commissioner // auction - no new minting if there is an active commissioner auction for this real world player if (_rwp.hasActiveCommissionerAuction) continue; // Ensure that our price is not less than a minimum uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); // Make sure the start price exceeds our minimum acceptable if (_startPrice < _minStartPrice) { _startPrice = _minStartPrice; } // Mint the new player token uint32 _playerId = _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, address(this)); // @dev Approve ownership transfer to the saleClockAuctionContract (which is required by // the createAuction(...) which will escrow the playerToken) _approve(_playerId, saleClockAuctionContract); // Apply the default duration if (_duration == 0) { _duration = COMMISSIONER_AUCTION_DURATION; } // By setting our _endPrice to zero, we become immune to the USD <==> ether // conversion rate. No matter how high ether goes, our auction price will get // to a USD value that is acceptable to someone (assuming 0 is acceptable that is). // This also helps for players that aren't in very much demand. saleClockAuctionContract.createAuction( _playerId, _startPrice, _endPrice, _duration, address(this) ); // Finally, update our realWorldPlayer record to reflect the fact that we just // minted a new one, and there is an active commish auction. leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, true, _rwp.mintingEnabled); } } /// @dev Reprices (and updates duration) of an array of tokens that are currently /// being auctioned by this contract. Since this function can only be called by /// the commissioner, we don't do a lot of checking of parameters and things. /// The SaleClockAuction's repriceAuctions method assures that the CSportsCore /// contract is the "seller" of the token (meaning it is a commissioner auction). /// @param _tokenIds Array of tokenIds corresponding to auctions being updated /// @param _startingPrices New starting prices for each token being repriced /// @param _endingPrices New ending price /// @param _duration New duration function repriceAuctions( uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256 _duration ) external onlyCommissioner { // We cannot reprice below our player minimum for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = uint32(_tokenIds[i]); PlayerToken memory pt = playerTokens[_tokenId]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); // We require the price to be >= our _minStartPrice require(_startingPrices[i] >= _minStartPrice); } // Note we pass in this CSportsCore contract address as the seller, making sure the only auctions // that can be repriced by this method are commissioner auctions. saleClockAuctionContract.repriceAuctions(_tokenIds, _startingPrices, _endingPrices, _duration, address(this)); } /// @dev Allows the commissioner to create a sale auction for a token /// that is owned by the core contract. Can only be called when not paused /// and only by the commissioner /// @param _playerTokenId - ID of the player token currently owned by the core contract /// @param _startingPrice - Starting price for the auction /// @param _endingPrice - Ending price for the auction /// @param _duration - Duration of the auction (in seconds) function createCommissionerAuction(uint32 _playerTokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) public whenNotPaused onlyCommissioner { require(leagueRosterContract != address(0)); require(_playerTokenId < playerTokens.length); // If player is already on any auction, this will throw because it will not be owned by // this CSportsCore contract (as all commissioner tokens are if they are not currently // on auction). // Any token owned by the CSportsCore contract by definition is a commissioner auction // that was canceled which makes it OK to re-list. require(_owns(address(this), _playerTokenId)); // (1) Grab the real world token ID (md5) PlayerToken memory pt = playerTokens[_playerTokenId]; // (2) Get the full real world player record from its roster index RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); // Ensure that our starting price is not less than a minimum uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); if (_startingPrice < _minStartPrice) { _startingPrice = _minStartPrice; } // Apply the default duration if (_duration == 0) { _duration = COMMISSIONER_AUCTION_DURATION; } // Approve the token for transfer _approve(_playerTokenId, saleClockAuctionContract); // saleClockAuctionContract.createAuction throws if inputs are invalid and clears // transfer after escrowing the player. saleClockAuctionContract.createAuction( _playerTokenId, _startingPrice, _endingPrice, _duration, address(this) ); } /// @dev Computes the next commissioner auction starting price equal to /// the previous real world player sale price + 25% (with a floor). function _computeNextCommissionerPrice(uint128 prevTwoCommissionerSalePriceAve) internal view returns (uint256) { uint256 nextPrice = prevTwoCommissionerSalePriceAve + (prevTwoCommissionerSalePriceAve / 4); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). if (nextPrice > 340282366920938463463374607431768211455) { nextPrice = 340282366920938463463374607431768211455; } // We never auction for less than our floor if (nextPrice < COMMISSIONER_AUCTION_FLOOR_PRICE) { nextPrice = COMMISSIONER_AUCTION_FLOOR_PRICE; } return nextPrice; } } /// @notice This is the main contract that implements the csports ERC721 token. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev This contract is made up of a series of parent classes so that we could /// break the code down into meaningful amounts of related functions in /// single files, as opposed to having one big file. The purpose of /// each facet is given here: /// /// CSportsConstants - This facet holds constants used throughout. /// CSportsAuth - /// CSportsBase - /// CSportsOwnership - /// CSportsAuction - /// CSportsMinting - /// CSportsCore - This is the main CSports constract implementing the CSports /// Fantash Football League. It manages contract upgrades (if / when /// they might occur), and has generally useful helper methods. /// /// This CSportsCore contract interacts with the CSportsLeagueRoster contract /// to determine which PlayerTokens to mint. /// /// This CSportsCore contract interacts with the TimeAuction contract /// to implement and run PlayerToken auctions (sales). contract CSportsCore is CSportsMinting { /// @dev Used by other contracts as a sanity check bool public isCoreContract = true; // Set if (hopefully not) the core contract needs to be upgraded. Can be // set by the CEO but only when paused. When successfully set, we can never // unpause this contract. See the unpause() method overridden by this class. address public newContractAddress; /// @notice Class constructor creates the main CSportsCore smart contract instance. /// @param nftName The ERC721 name for the contract /// @param nftSymbol The ERC721 symbol for the contract /// @param nftTokenURI The ERC721 token uri for the contract constructor(string nftName, string nftSymbol, string nftTokenURI) public { // New contract starts paused. paused = true; /// @notice storage for the fields that identify this 721 token _name = nftName; _symbol = nftSymbol; _tokenURI = nftTokenURI; // All C-level roles are the message sender ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; commissionerAddress = msg.sender; } /// @dev Reject all Ether except if it's from one of our approved sources function() external payable { /*require( msg.sender == address(saleClockAuctionContract) );*/ } /// --------------------------------------------------------------------------- /// /// ----------------------------- PUBLIC FUNCTIONS ---------------------------- /// /// --------------------------------------------------------------------------- /// /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// 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 upgradeContract(address _v2Address) public onlyCEO whenPaused { newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also require that we have /// set a valid season and the contract has not been upgraded. function unpause() public onlyCEO whenPaused { require(leagueRosterContract != address(0)); require(saleClockAuctionContract != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } /// @dev Consolidates setting of contract links into a single call for deployment expediency function setLeagueRosterAndSaleAndTeamContractAddress(address _leagueAddress, address _saleAddress, address _teamAddress) public onlyCEO { setLeagueRosterContractAddress(_leagueAddress); setSaleAuctionContractAddress(_saleAddress); setTeamContractAddress(_teamAddress); } /// @dev Returns all the relevant information about a specific playerToken. ///@param _playerTokenID - player token ID we are seeking the full player token info for function getPlayerToken(uint32 _playerTokenID) public view returns ( uint32 realWorldPlayerId, uint32 serialNumber, uint64 mintedTime, uint128 mostRecentPrice) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; realWorldPlayerId = pt.realWorldPlayerId; serialNumber = pt.serialNumber; mostRecentPrice = pt.mostRecentPrice; mintedTime = pt.mintedTime; } /// @dev Returns the realWorldPlayer MD5 ID for a given playerTokenID /// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for function realWorldPlayerTokenForPlayerTokenId(uint32 _playerTokenID) public view returns (uint128 md5Token) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); md5Token = _rwp.md5Token; } /// @dev Returns the realWorldPlayer Metadata for a given playerTokenID /// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for function realWorldPlayerMetadataForPlayerTokenId(uint32 _playerTokenID) public view returns (string metadata) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); metadata = leagueRosterContract.getMetadata(_rwp.md5Token); } /// --------------------------------------------------------------------------- /// /// ------------------------- RESTRICTED FUNCTIONS ---------------------------- /// /// --------------------------------------------------------------------------- /// /// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be /// called by the CEO and is used in development stage only as it is only needed by our test suite. /// @param _rosterIndex - Index into realWorldPlayers of the entry to change. /// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions /// @param _lastMintedTime - Time this real world player was last minted /// @param _mintedCount - The number of playerTokens that have been minted for this player /// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player /// @param _mintingEnabled - Denotes whether or not we should mint new playerTokens for this real world player function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCEO onlyUnderDevelopment { require(leagueRosterContract != address(0)); leagueRosterContract.updateRealWorldPlayer(_rosterIndex, _prevCommissionerSalePrice, _lastMintedTime, _mintedCount, _hasActiveCommissionerAuction, _mintingEnabled); } }
@notice Enumerate NFTs assigned to an owner @dev Throws if `index` >= `balanceOf(owner)` or if `owner` is the zero address, representing invalid NFTs. @param owner An address where we are interested in NFTs owned by them @param index A counter less than `balanceOf(owner)` @return The token identifier for the `index`th NFT assigned to `owner`, (sort order not specified)
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId) { require(owner != address(0)); require(index < balanceOf(owner)); return ownedTokens[owner][index]; }
6,426,270
[ 1, 3572, 12600, 423, 4464, 87, 6958, 358, 392, 3410, 225, 22435, 309, 1375, 1615, 68, 1545, 1375, 12296, 951, 12, 8443, 22025, 578, 309, 225, 1375, 8443, 68, 353, 326, 3634, 1758, 16, 5123, 2057, 423, 4464, 87, 18, 225, 3410, 1922, 1758, 1625, 732, 854, 20506, 316, 423, 4464, 87, 16199, 635, 2182, 225, 770, 432, 3895, 5242, 2353, 1375, 12296, 951, 12, 8443, 22025, 327, 1021, 1147, 2756, 364, 326, 1375, 1615, 68, 451, 423, 4464, 6958, 358, 1375, 8443, 9191, 282, 261, 3804, 1353, 486, 1269, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 3903, 1476, 1135, 261, 11890, 5034, 389, 2316, 548, 13, 288, 203, 1377, 2583, 12, 8443, 480, 1758, 12, 20, 10019, 203, 1377, 2583, 12, 1615, 411, 11013, 951, 12, 8443, 10019, 203, 1377, 327, 16199, 5157, 63, 8443, 6362, 1615, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** EXAMPLE: pragma */ pragma ton-solidity >=0.35.5; // Check compiler version is at least 0.35.5 pragma ton-solidity ^ 0.35.5; // Check compiler version is at least 0.35.5 and less 0.36.0 pragma ton-solidity < 0.35.5; // Check compiler version is less 0.35.5 pragma ton-solidity >= 0.35.5 < 0.35.7; // Check compiler version equal to 0.35.5 or 0.35.6 pragma ignoreIntOverflow; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; pragma msgValue 123456789; pragma msgValue 1e8; pragma msgValue 10 ton; pragma msgValue 10_000_000_123; /** EXAMPLE: TON units */ require(1 nano == 1); require(1 nanoton == 1); require(1 nTon == 1); require(1 ton == 1e9 nanoton); require(1 Ton == 1e9 nanoton); require(1 micro == 1e-6 ton); require(1 microton == 1e-6 ton); require(1 milli == 1e-3 ton); require(1 milliton == 1e-3 ton); require(1 kiloton == 1e3 ton); require(1 kTon == 1e3 ton); require(1 megaton == 1e6 ton); require(1 MTon == 1e6 ton); require(1 gigaton == 1e9 ton); require(1 GTon == 1e9 ton); /** EXAMPLE: int uint */ int i = 0; uint u = 0; int8 a = 1; uint9 b = 123; //error type; int255 c = 123; //error type; uint256 d = 0xd; /** EXAMPLE: ExtraCurrencyCollection */ ExtraCurrencyCollection curCol; uint32 key; uint256 value; optional(uint32, uint256) res = curCol.min(); optional(uint32, uint256) res = curCol.next(key); optional(uint32, uint256) res = curCol.prev(key); optional(uint32, uint256) res = curCol.nextOrEq(key); optional(uint32, uint256) res = curCol.prevOrEq(key); optional(uint32, uint256) res = curCol.delMin(); optional(uint32, uint256) res = curCol.delMax(); optional(uint256) optValue = curCol.fetch(key); bool exists = curCol.exists(key); bool isEmpty = curCol.empty(); bool success = curCol.replace(key, value); bool success = curCol.add(key, value); optional(uint256) res = curCol.getSet(key, value); optional(uint256) res = curCol.getAdd(key, value); optional(uint256) res = curCol.getReplace(key, value); uint256 uintValue = curCol[index]; /** EXAMPLE: vector */ vector(uint) vect; uint a = 11; vect.push(a); vect.push(111); /** EXAMPLE: for iteration */ uint[] arr = ...; uint sum = 0; for (uint val : arr) { // iteration over array sum += val; } bytes byteArray = "Hello!"; for (byte b : byteArray) { // ... } mapping(uint32 => uint) map = ...; uint keySum = 0; uint valueSum = 0; for ((uint32 key, uint value) : map) { // iteration over mapping keySum += key; valueSum += value; } mapping(uint32 => uint) map = ...; uint keySum = 0; for ((uint32 key, ) : map) { // value is omitted keySum += key; } uint valueSum = 0; for ((, uint value) : map) { // key is omitted valueSum += value; } /** EXAMPLE: repeat */ uint a = 0; repeat(10) { a ++; } require(a == 10, 101); // Despite a is changed in the cycle, code block will be repeated 10 times (10 is initial value of a) repeat(a) { a += 2; } require(a == 30, 102); a = 11; repeat(a - 1) { a -= 1; } require(a == 1, 103); /** EXAMPLE: array */ struct MyStruct { uint a; int b; address c; } uint[] arr; require(arr.empty()); arr.push(); require(!arr.empty()); /** EXAMPLE: bytes and hex literal */ bytes a = "abzABZ0129"; // initialised with string bytes b = hex"0DE_001a_239_abf"; // initialised with hex data bytes bad_ = hex"_0DE_001a__239_abf_"; bytes bad = hex"ghjkl"; bytes bad1 = hex"123ghjkl"; bytes bad2 = hex"ghjkl123"; bytes bad3 = hex"BADgh01_23_46jkl123"; /** EXAMPLE: bytes with length */ bytes0 b0; bytes1 b1; bytes2 b2; bytes3 b3; bytes4 b4; bytes5 b5; bytes6 b6; bytes7 b7; bytes8 b8; bytes9 b9; bytes10 b10; bytes11 b11; bytes12 b12; bytes13 b13; bytes14 b14; bytes15 b15; bytes16 b16; bytes17 b17; bytes18 b18; bytes19 b19; bytes20 b20; bytes21 b21; bytes22 b22; bytes23 b23; bytes24 b24; bytes25 b25; bytes26 b26; bytes27 b27; bytes28 b28; bytes29 b29; bytes30 b30; bytes31 b31; bytes32 b32; bytes33 b33; bytes34 b34; bytes100 b100; /** EXAMPLE: bytes, byte */ bytes byteArray = "abba"; int index = 0; byte a0 = byteArray[index]; bytes byteArray = "01234567890123456789"; bytes slice = byteArray[5:10]; bytes etalon = "56789"; require(slice == etalon); slice = byteArray[10:]; etalon = "0123456789"; require(slice == etalon); slice = byteArray[:10]; require(slice == etalon); slice = byteArray[:]; require(slice == byteArray); require(byteArray[:10] == etalon); require(etalon == byteArray[:10]); bytes byteArray = "1234"; bytes4 bb = byteArray; /** EXAMPLE: string */ string long = "0123456789"; string a = long.substr(1, 2); // a = "12" string b = long.substr(6); // b = "6789" string str = "01234567890"; optional(uint32) a = str.find(byte('0')); require(a.hasValue()); require(a.get() == 0); byte symbol = 'a'; optional(uint32) b = str.findLast(symbol); require(!b.hasValue()); string sub = "111"; optional(uint32) c = str.find(symbol); require(!c.hasValue()); /** EXAMPLE: string escape */ string escaped = "escaped: \\ backslash, \' single quote, \" double quote"; string escape2 = "escaped: \n newline, \r carriage return, \t tab"; string escapeold = "not escaped, deprecated: \b \f \v"; string escapehex = "escaped: \x01 \xab \xCD \xaD, but: \x1 \xabc \x12345, \xg \x-12"; string escapeunicode = "escaped: \u1223 \uabCD, but: \u1 \u22 \u333 \u12345 \uABCDEF, \u123G \uAB-CD"; /** EXAMPLE: string format */ string str = format("Hello {} 0x{:X} {} {}.{} tons", 123, 255, address.makeAddrStd(-33,0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE), 100500, 32); require(str == "Hello 123 0xFF -21:7fffffffffffffffffffffffffffffffffffffffffffffffff123456789abcde 100500.32 tons", 101); require(format("Hello {}", 123) == "Hello 123", 102); require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103); require(format("{}", -123) == "-123", 103); require(format("{}", address.makeAddrStd(127,0)) == "7f:0000000000000000000000000000000000000000000000000000000000000000", 104); require(format("{}", address.makeAddrStd(-128,0)) == "-80:0000000000000000000000000000000000000000000000000000000000000000", 105); require(format("{:6}", 123) == " 123", 106); require(format("{:06}", 123) == "000123", 107); require(format("{:06d}", 123) == "000123", 108); require(format("{:06X}", 123) == "00007B", 109); require(format("{:6x}", 123) == " 7b", 110); uint128 a = 1 ton; require(format("{:t}", a) == "1.000000000", 101); a = 123; require(format("{:t}", a) == "0.000000123", 103); fixed32x3 v = 1.5; require(format("{}", v) == "1.500", 106); fixed256x10 vv = -987123.4567890321; require(format("{}", vv) == "-987123.4567890321", 108); /** EXAMPLE: address */ address addrNone = address.makeAddrNone(); uint addrNumber; uint bitCnt; address addrExtern = address.makeAddrExtern(addrNumber, bitCnt); (int8 wid, uint addr) = address(this).unpack(); /** EXAMPLE: transfer */ address dest = ...; uint128 value = ...; bool bounce = ...; uint16 flag = ...; TvmCell body = ...; ExtraCurrencyCollection c = ...; // sequential order of parameters addr.transfer(value); addr.transfer(value, bounce); addr.transfer(value, bounce, flag); addr.transfer(value, bounce, flag, body); addr.transfer(value, bounce, flag, body, c); // using named parameters destination.transfer({value: 1 ton, bounce: false, flag: 128, body: cell, currencies: c}); destination.transfer({bounce: false, value: 1 ton, flag: 128, body: cell}); /** EXAMPLE: mapping */ struct Point { uint x; uint y; uint z; } mapping(Point => address) map; function test(uint x, uint y, uint z, address addr) public { Point p = Point(x, y, z); map[p] = addr; } KeyType key; // init key optional(KeyType, ValueType) nextPair = map.next(key); optional(KeyType, ValueType) prevPair = map.prev(key); if (nextPair.hasValue()) { (KeyType nextKey, ValueType nextValue) = nextPair.get(); // unpack optional value // using nextKey and nextValue } mapping(uint8 => uint) m; optional(uint8, uint) = m.next(-1); // ok, param for next/prev can be negative optional(uint8, uint) = m.prev(65537); // ok, param for next/prev can not possibly fit to KeyType (uint8 in this case) /** EXAMPLE: function */ function getSum(int a, int b) internal pure returns (int) { return a + b; } function getSub(int a, int b) internal pure returns (int) { return a - b; } function process(int a, int b, uint8 mode) public returns (int) { function (int, int) returns (int) fun; if (mode == 0) { fun = getSum; } else if (mode == 1) { fun = getSub; } return fun(a, b); // if `fun` isn't initialized then exception is thrown } /** EXAMPLE: require, revert */ uint a = 5; require(a == 5); // ok require(a == 6); // throws an exception with code 100 require(a == 6, 101); // throws an exception with code 101 require(a == 6, 101, "a is not equal to six"); // throws an exception with code 101 and string require(a == 6, 101, a); // throws an exception with code 101 and number a revert(); // throw exception 100 revert(101); // throw exception 101 revert(102, "We have a some problem"); // throw exception 102 and string revert(101, a); // throw exception 101 and number a /** EXAMPLE: constant, static */ uint128 constant public GRAMS_OVERHEAD = 0.2 nanoton; contract MyContract { uint constant COST = 100; uint constant COST2 = COST + GRAMS_OVERHEAD; address constant dest = address.makeAddrStd(-1, 0x89abcde); } contract C { uint static a; // ok // uint static b = 123; // error } /** EXAMPLE: contract functions */ contract Sink { uint public counter = 0; uint public msgWithPayload = 0; receive() external { ++counter; // if the inbound internal message has payload then we can get it using `msg.data` TvmSlice s = msg.data; if (!s.empty()) { ++msgWithPayload; } } } contract ContractA { uint public counter = 0; function f(uint a, uint b) public pure { /*...*/ } fallback() external { ++counter; } onBounce(TvmSlice body) external { /*...*/ } onTickTock(bool isTock) external { /*...*/ } } /** EXAMPLE: pure view */ contract Test { uint a; event MyEvent(uint val); // pure mutability function f() public pure { emit MyEvent(123); } // view mutability function g() public view { emit MyEvent(a); } // default mutability (not set) function e(uint newA) public { a = newA; } } /** EXAMPLE: inline, externalMsg and internalMsg */ // This function is called as usual function. function getSum(uint a, uint b) public returns (uint) { return sum(a, b); } // Code of this function is inserted to the place of call. function sum(uint a, uint b) private inline returns (uint) { return a + b; } function f() public externalMsg { // this function receives only external messages /*...*/ } // Note: keyword `external` specifies function visibility function ff() external externalMsg { // this function receives only external messages also /*...*/ } function g() public internalMsg { // this function receives only internal messages /*...*/ } /** EXAMPLE: functionID */ // These function receives internal and external messages. function fun() public { /*...*/ } function f() public pure functionID(123) { /*...*/ } /** EXAMPLE: emit event */ event SomethingIsReceived(uint a, uint b, uint sum); // ... address addr = address.makeAddrExtern(...); emit SomethingIsReceived{dest: addr}(2, 8, 10); // dest address is set emit SomethingIsReceived(10, 15, 25); // dest address == addr_none /** EXAMPLE: return options */ function f(uint n) public pure { return n <= 1? 1 : n * f(n - 1); } function f(uint n) public responsible pure { return{value: 0, flag: 64} n <= 1? 1 : n * f(n - 1); } /** EXAMPLE: external call */ interface IContract { function f(uint a) external; } contract Caller { function callExt(address addr) public { IContract(addr).f(123); // attached default value: 0.01 ton IContract(addr).f{value: 10 ton}(123); IContract(addr).f{value: 10 ton, flag: 3}(123); IContract(addr).f{value: 10 ton, bounce: true}(123); IContract(addr).f{value: 1 micro, bounce: false, flag: 128}(123); ExtraCurrencyCollection cc; cc[12] = 1000; IContract(addr).f{value: 10 ton, currencies:cc}(123); } } contract RemoteContract { // Note this function is marked as responsible to call callback function function getCost(uint x) public pure responsible returns (uint) { uint cost = x == 0 ? 111 : 222; // return `cost` and set option for outbound internal message. return{value: 0, bounce: false, flag: 64} cost; } } contract Caller { function test(address addr, uint x) public pure { // `getCost` returns result to `onGetCost` RemoteContract(addr).getCost{value: 1 ton, callback: Caller.onGetCost}(x); } function onGetCost(uint cost) public { // check that msg.sender is expected address // we get cost TODO value, we can handle this value /* `cost` is uint, `_item` is global, `0sdf` is incorrect */ } } /** EXAMPLE: highlight variables and names in comments */ contract Caller { function test(address addr, uint x) public pure { // `getCost` returns result to `onGetCost` RemoteContract(addr).getCost{value: 1 ton, callback: Caller.onGetCost}(x); } function onGetCost(uint cost) public { // TODO: check that `msg.sender` is expected address // we get cost value, we can handle this value /* `cost` is uint, `_item` is global, `0sdf` is incorrect */ } } /** EXAMPLE: await */ interface IContract { function getNum(uint a) external responsible returns (uint) ; } contract Caller { function call(address addr) public pure { // ... uint res = IContract(addr).getNum(123).await; require(res == 124, 101); // ... } } /** EXAMPLE: delete */ int a = 5; delete a; require(a == 0); uint[] arr; arr.push(11); arr.push(22); arr.push(33); delete arr[1]; require(arr[0] == 11); require(arr[1] == 0); require(arr[2] == 33); delete arr; require(arr.length == 0); mapping(uint => uint) l_map; l_map[1] = 2; delete l_map[1]; require(!l_map.exists(1)); l_map[1] = 2; delete l_map; require(!l_map.exists(1)); struct DataStruct { uint m_uint; bool m_bool; } DataStruct l_struct; l_struct.m_uint = 1; delete l_struct; require(l_struct.m_uint == 0); TvmBuilder b; uint i = 0x54321; b.store(i); TvmCell c = b.toCell(); delete c; TvmCell empty; require(tvm.hash(empty) == tvm.hash(c)); b.store(c); TvmSlice slice = b.toSlice(); require(slice.bits() == 256); require(slice.refs() == 1); delete slice; require(slice.bits() == 0); require(slice.refs() == 0); require(b.bits() == 256); require(b.refs() == 1); delete b; require(b.bits() == 0); require(b.refs() == 0); /** EXAMPLE: tvm */ tvm.log("Hello,world!"); logtvm("99_Bottles"); string s = "Some_text"; tvm.log(s); uint256 hash = tvm.hash(TvmCell cellTree); uint256 hash = tvm.hash(string); uint256 hash = tvm.hash(bytes); // 1) tvm.buildStateInit(TvmCell code, TvmCell data) returns (TvmCell stateInit); // 2) tvm.buildStateInit(TvmCell code, TvmCell data, uint8 splitDepth) returns (TvmCell stateInit); // 3) tvm.buildStateInit({code: TvmCell code, data: TvmCell data, splitDepth: uint8 splitDepth, pubkey: uint256 pubkey, contr: contract Contract, varInit: {VarName0: varValue0, ...}}); TvmCell code = ...; address newWallet = new SimpleWallet{value: 1 ton, code: code}(arg0, arg1, ...); /** EXAMPLE: extMsg */ interface Foo { function bar(uint a, uint b) external pure; } contract Test { function test7() public { address addr = address.makeAddrStd(0, 0x0123456789012345678901234567890123456789012345678901234567890123); Foo(addr).bar{expire: 0x12345, time: 0x123}(123, 45).extMsg; optional(uint) pubkey; optional(uint32) signBox; Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey}(123, 45).extMsg; Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey, sign: true}(123, 45).extMsg; pubkey.set(0x95c06aa743d1f9000dd64b75498f106af4b7e7444234d7de67ea26988f6181df); Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey, sign: true}(123, 45).extMsg; Foo(addr).bar{expire: 0x12345, time: 0x123, sign: true, signBoxHandle: signBox}(123, 45).extMsg; } } /** EXAMPLE: tvm, math, rnd */ // The following functions are only colored differently from normal functions // if theme supports "support.function". You can check with "Kimble Dark" theme tvm.accept(); tvm.unknownFunction(); int a = math.abs(-4123); // 4123 int b = -333; int c = math.abs(b); // 333 math.unknownFunction(); rnd.shuffle(/*uint someNumber*/ 123); rnd.shuffle(); uint256 r0 = rnd.next(); // 0..2^256-1 uint8 r1 = rnd.next(100); // 0..99 int8 r2 = rnd.next(int8(100)); // 0..99 int8 r3 = rnd.next(int8(-100)); // -100..-1 rnd.unknownFunction(); selfdestruct(/*address*/ dest_addr); sha256(/*TvmSlice*/ slice);// returns (uint256) sha256(/*bytes*/ b);// returns (uint256) sha256(/*string*/ str);// returns (uint256) gasToValue(/*uint128*/ gas, /*int8*/ wid);// returns (uint128 value) valueToGas(/*uint128*/ value, /*int8*/ wid);// returns (uint128 gas) sha257(someBytes); sha256(someBytes); /** EXAMPLE: bitSize, uBitSize */ require(bitSize(12) == 5); // 12 == 1100(in bin sys) require(bitSize(1) == 2); require(bitSize(-1) == 1); require(bitSize(0) == 0); require(uBitSize(10) == 4); require(uBitSize(1) == 1); require(uBitSize(0) == 0); require(ubitSize(0) == 0); // wrong /** EXAMPLE: TvmSlice, TvmBuilder, TvmCell */ TvmSlice slice = ...; (uint8 a, uint16 b) = slice.decode(uint8, uint16); (uint16 num0, uint32 num1, address addr) = slice.decode(uint16, uint32, address); uint256 a = 11; int16 b = 22; TvmBuilder builder; builder.store(a, b, uint(33)); function afterSignatureCheck(TvmSlice body, TvmCell message) private inline returns (TvmSlice) { /*...*/ } /** EXAMPLE: natspec */ /** @title A simulator for trees @author Larry A. Gardner @notice You can use this contract for only the most basic simulation @dev All function calls are currently implemented without side effects */ contract Tree { /// @author Mary A. Botanist /// @notice Calculate tree age in years, rounded up, for live trees /// @dev The Alexandr N. Tetearing algorithm could increase precision /// @param rings The number of rings from dendrochronological sample /// @return age in years, rounded up for partial years function age(uint256 rings) external pure returns (uint256) { return rings + 1; } } //// pragma ton-solidity >= 0.35.5 < 0.35.7; // Check compiler version equal to 0.35.5 or 0.35.6 pragma AbiHeader time; pragma msgValue 10 ton; int a = math.abs(-4123); // 4123 TvmBuilder b; b.store(a); TvmCell c = b.toCell(); int8 r = rnd.next(int8(-100)); uint9 b = 123; // error type; rnd.unknownFunction(); selfdestruct(address(dest_addr)); gasToValue(gas, wid);// returns (uint128 `value`) sha257("String with\nescapes: \x12 \u1234"); sha256("String with\rescapes:\t\x12 \u1234\""); vector(uint) vect; mapping(uint32 => uint) map = /*...*/; for ((uint32 key, ) : map) { // value is omitted repeat(5) {keySum += key;} } bytes b = hex"0DE_001a_239_abf"; // initialised with hex data bytes bad_ = hex"_0DE_001a__239_abf_"; bytes bad = hex"0123ghjklABCD"; require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103); return{value: 0, flag: 64} n <= 1? 1 : n * f(n - 1);
this function receives only external messages also
function ff() external externalMsg {
15,790,524
[ 1, 2211, 445, 17024, 1338, 3903, 2743, 2546, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 6875, 1435, 3903, 3903, 3332, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x7f3BB8dB336ff50120E290e5C8eC78B20f619D01/sources/contracts/SuStrategyV2.sol
* @notice Calculate Snowball tokens for a given amount of LP tokens @dev If contract is empty, use 1:1 ratio @dev Could return zero shares for very low amounts of LP tokens @param amount LP tokens @return Snowball tokens/
function getSharesForLPTokens(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return amount; } return amount.mul(totalSupply).div(totalDeposits); }
4,589,303
[ 1, 8695, 31040, 19067, 2430, 364, 279, 864, 3844, 434, 511, 52, 2430, 225, 971, 6835, 353, 1008, 16, 999, 404, 30, 21, 7169, 225, 14312, 327, 3634, 24123, 364, 8572, 4587, 30980, 434, 511, 52, 2430, 225, 3844, 511, 52, 2430, 327, 31040, 19067, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1322, 3395, 455, 1290, 48, 1856, 3573, 12, 11890, 3844, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 565, 309, 261, 4963, 3088, 1283, 18, 16411, 12, 4963, 758, 917, 1282, 13, 422, 374, 13, 288, 203, 1377, 327, 3844, 31, 203, 565, 289, 203, 565, 327, 3844, 18, 16411, 12, 4963, 3088, 1283, 2934, 2892, 12, 4963, 758, 917, 1282, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // /** * @dev 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); } } // /** * @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)); } } // /** * @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); } } } } // /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // /** * @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); } // /** * @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; } } // /** * @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 { } } // /** * @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). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @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 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 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 () internal { _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. * * 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()); } } // /** * @dev ERC20 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 ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // /** * @dev {ERC20} 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 * * 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 ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // /** * @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"); } } } // // Using these will cause _mint to be not found in Pool // Using these seems to work //import "./interfaces/IERC20.sol"; //import "./libraries/SafeERC20.sol"; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakingToken; uint256 public startTime; // Developer fund uint256 public devFund; uint256 public devCount; mapping(uint256 => address) public devIDs; mapping(address => uint256) public devAllocations; // Staking balances uint256 public _totalSupply; mapping(address => uint256) public _balances; uint256 public _totalSupplyAccounting; mapping(address => uint256) public _balancesAccounting; constructor(uint256 _startTime) public { startTime = _startTime; devCount = 8; // Set dev fund allocation percentages devIDs[0] = 0xAd1CC47416C2c8C9a1B91BFf41Ea627718e80074; devAllocations[0xAd1CC47416C2c8C9a1B91BFf41Ea627718e80074] = 16; devIDs[1] = 0x8EDac59Ea229a52380D181498C5901a764ad1c40; devAllocations[0x8EDac59Ea229a52380D181498C5901a764ad1c40] = 16; devIDs[2] = 0xeBc3992D9a2ef845224F057637da84927FDACf95; devAllocations[0xeBc3992D9a2ef845224F057637da84927FDACf95] = 9; devIDs[3] = 0x59Cc100B954f609c21dA917d6d4A1bD1e50dFE93; devAllocations[0x59Cc100B954f609c21dA917d6d4A1bD1e50dFE93] = 8; devIDs[4] = 0x416C75cFE45b951a411B23FC55904aeC383FFd6F; devAllocations[0x416C75cFE45b951a411B23FC55904aeC383FFd6F] = 9; devIDs[5] = 0xA103D9a54E0dE29886b077654e01D15F80Dad20c; devAllocations[0xA103D9a54E0dE29886b077654e01D15F80Dad20c] = 16; devIDs[6] = 0x73b6f43c9c86E7746a582EBBcB918Ab1Ad49bBD8; devAllocations[0x73b6f43c9c86E7746a582EBBcB918Ab1Ad49bBD8] = 16; devIDs[7] = 0x1A345cb683B3CB6F62F5A882022849eeAF47DFB3; devAllocations[0x1A345cb683B3CB6F62F5A882022849eeAF47DFB3] = 10; } // Returns the total staked tokens within the contract function totalSupply() public view returns (uint256) { return _totalSupply; } // Returns staking balance of the account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // Set the staking token for the contract function setStakingToken(address stakingTokenAddress) internal { stakingToken = IERC20(stakingTokenAddress); } // Stake funds into the pool function stake(uint256 amount) public virtual { // Calculate tax and after-tax amount uint256 taxRate = calculateTax(); uint256 taxedAmount = amount.mul(taxRate).div(100); uint256 stakedAmount = amount.sub(taxedAmount); // Increment sender's balances and total supply _balances[msg.sender] = _balances[msg.sender].add(stakedAmount); _totalSupply = _totalSupply.add(stakedAmount); // Increment dev fund by tax devFund = devFund.add(taxedAmount); // Transfer funds stakingToken.safeTransferFrom(msg.sender, address(this), amount); } // Withdraw staked funds from the pool function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); } // Distributes the dev fund to the developer addresses, callable by anyone function distributeDevFund() public virtual { // Reset dev fund to 0 before distributing any funds uint256 totalDistributionAmount = devFund; devFund = 0; // Distribute dev fund according to percentages for (uint256 i = 0; i < devCount; i++) { uint256 devPercentage = devAllocations[devIDs[i]]; uint256 allocation = totalDistributionAmount.mul(devPercentage).div( 100 ); if (allocation > 0) { stakingToken.safeTransfer(devIDs[i], allocation); } } } // Return the tax amount according to current block time function calculateTax() public view returns (uint256) { // Pre-pool start time = 5% tax if (block.timestamp < startTime) { return 5; // 0-60 minutes after pool start time = 8% tax } else if ( block.timestamp.sub(startTime) >= 0 minutes && block.timestamp.sub(startTime) <= 60 minutes ) { return 8; // 60-90 minutes after pool start time = 5% tax } else if ( block.timestamp.sub(startTime) > 60 minutes && block.timestamp.sub(startTime) <= 90 minutes ) { return 5; // 90+ minutes after pool start time = 3% tax } else if (block.timestamp.sub(startTime) > 90 minutes) { return 3; } } } // /* * Copyright (c) 2020 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject tog the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ /* ______ __ __ / ________ __________ ___ ____ _____ ____ ____/ ____/ ____ ____ / /_ / __ `/ ___/ __ `__ \/ __ `/ __ `/ _ \/ __ / __ / __ \/ __ \ / __/ / /_/ / / / / / / / / /_/ / /_/ / __/ /_/ / /_/ / /_/ / / / / /_/ \__,_/_/ /_/ /_/ /_/\__,_/\__, /\___/\__,_/\__,_/\____/_/ /_/ /____/ * FARMAFINANCE: MintablePool.sol * https://farma.finance * telegram: TBA */ contract UsdtEthGrowBurst is LPTokenWrapper, Ownable { using SafeERC20 for ERC20PresetMinterPauser; using SafeERC20 for IERC20; ERC20PresetMinterPauser public rewardToken; IERC20 public multiplierToken; uint256 public DURATION; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public deployedTime; uint256 public multiplierTokenDevFund; uint256 public constant boostLevelOneCost = 12000000000000000; uint256 public constant boostLevelTwoCost = 40000000000000000; uint256 public constant boostLevelThreeCost = 120000000000000000; uint256 public constant boostLevelFourCost = 240000000000000000; uint256 public constant FivePercentBonus = 50000000000000000; uint256 public constant TwentyPercentBonus = 200000000000000000; uint256 public constant FourtyPercentBonus = 400000000000000000; uint256 public constant HundredPercentBonus = 1000000000000000000; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public spentMultiplierTokens; mapping(address => uint256) public boostLevel; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Boost(uint256 level); constructor( address _stakingToken, address _rewardToken, address _multiplierToken, uint256 _startTime, uint256 _duration ) public LPTokenWrapper(_startTime) { setStakingToken(_stakingToken); rewardToken = ERC20PresetMinterPauser(_rewardToken); multiplierToken = IERC20(_multiplierToken); deployedTime = block.timestamp; DURATION = _duration; } function setOwner(address _newOwner) external onlyOwner { super.transferOwnership(_newOwner); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } // Returns the current rate of rewards per token (doh) function rewardPerToken() public view returns (uint256) { // Do not distribute rewards before games begin if (block.timestamp < startTime) { return 0; } if (_totalSupply == 0) { return rewardPerTokenStored; } // Effective total supply takes into account all the multipliers bought. uint256 effectiveTotalSupply = _totalSupply.add(_totalSupplyAccounting); return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(effectiveTotalSupply) ); } // Returns the current reward tokens that the user can claim. function earned(address account) public view returns (uint256) { // Each user has it's own effective balance which is just the staked balance multiplied by boost level multiplier. uint256 effectiveBalance = _balances[account].add( _balancesAccounting[account] ); return effectiveBalance .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // Staking function which updates the user balances in the parent contract function stake(uint256 amount) public override { updateReward(msg.sender); require(amount > 0, "Cannot stake 0"); super.stake(amount); // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier. if (boostLevel[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; // Adjust total accounting supply accordingly uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Staked(msg.sender, amount); } // Withdraw function to remove stake from the pool function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); super.withdraw(amount); // Users who have bought multipliers will have their accounting balances readjusted. if (boostLevel[msg.sender] > 0) { // The previous extra balance user had uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; // Subtract the withdrawn amount from the accounting balance // If all tokens are withdrawn the balance will be 0. uint256 diffBalancesAccounting = prevBalancesAccounting.sub( newBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.sub( diffBalancesAccounting ); } emit Withdrawn(msg.sender, amount); } // Get the earned rewards and withdraw staked tokens function exit() external { getReward(); withdraw(balanceOf(msg.sender)); } // Sends out the reward tokens to the user. function getReward() public { updateReward(msg.sender); uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.mint(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } // Called to start the pool with the reward amount it should distribute // The reward period will be the duration of the pool. function notifyRewardAmount(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } // Notify the reward amount without updating time; function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } emit RewardAdded(reward); } // Returns the users current multiplier level function getLevel(address account) external view returns (uint256) { return boostLevel[account]; } // Return the amount spent on multipliers, used for subtracting for future purchases. function getSpent(address account) external view returns (uint256) { return spentMultiplierTokens[account]; } // Calculate the cost for purchasing a boost. function calculateCost(uint256 level) public pure returns (uint256) { if (level == 1) { return boostLevelOneCost; } else if (level == 2) { return boostLevelTwoCost; } else if (level == 3) { return boostLevelThreeCost; } else if (level == 4) { return boostLevelFourCost; } } // Purchase a multiplier level, same level cannot be purchased twice. function purchase(uint256 level) external { require( boostLevel[msg.sender] <= level, "Cannot downgrade level or same level" ); uint256 cost = calculateCost(level); // Cost will be reduced by the amount already spent on multipliers. uint256 finalCost = cost.sub(spentMultiplierTokens[msg.sender]); // Transfer tokens to the contract multiplierToken.safeTransferFrom(msg.sender, address(this), finalCost); // Update balances and level multiplierTokenDevFund = multiplierTokenDevFund.add(finalCost); spentMultiplierTokens[msg.sender] = spentMultiplierTokens[msg.sender] .add(finalCost); boostLevel[msg.sender] = level; // If user has staked balances, then set their new accounting balance if (_balances[msg.sender] > 0) { // Get the previous accounting balance uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; // Get the new multiplier uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); // Calculate new accounting balance uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); // Set the accounting balance _balancesAccounting[msg.sender] = newBalancesAccounting; // Get the difference for adjusting the total accounting balance uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); // Adjust the global accounting balance. _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Boost(level); } // Returns the multiplier for user. function getTotalMultiplier(address account) public view returns (uint256) { uint256 boostMultiplier = 0; if (boostLevel[account] == 1) { boostMultiplier = FivePercentBonus; } else if (boostLevel[account] == 2) { boostMultiplier = TwentyPercentBonus; } else if (boostLevel[account] == 3) { boostMultiplier = FourtyPercentBonus; } else if (boostLevel[account] == 4) { boostMultiplier = HundredPercentBonus; } return boostMultiplier.add(1 * 10**18); } // Distributes the dev fund for accounts function distributeDevFund() public override { uint256 totalMulitplierDistributionAmount = multiplierTokenDevFund; multiplierTokenDevFund = 0; // Distribute multiplier dev fund according to percentages for (uint256 i = 0; i < devCount; i++) { uint256 devPercentage = devAllocations[devIDs[i]]; uint256 allocation = totalMulitplierDistributionAmount .mul(devPercentage) .div(100); if (allocation > 0) { multiplierToken.safeTransfer(devIDs[i], allocation); } } // Distribute the staking token rewards super.distributeDevFund(); } // Ejects any remaining tokens from the pool. // Callable only after the pool has started and the pools reward distribution period has finished. function eject() external onlyOwner { require( startTime < block.timestamp && block.timestamp >= periodFinish, "Cannot eject before period finishes or pool has started" ); uint256 currBalance = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(msg.sender, currBalance); } // Forcefully retire a pool // Only sets the period finish to 0 // This will prevent more rewards from being disbursed function kill() external onlyOwner { periodFinish = block.timestamp; } function updateRewardPerTokenStored() internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); } function updateReward(address account) internal { updateRewardPerTokenStored(); rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } }
FARMAFINANCE: MintablePool.sol telegram: TBA/
contract UsdtEthGrowBurst is LPTokenWrapper, Ownable { using SafeERC20 for ERC20PresetMinterPauser; using SafeERC20 for IERC20; ERC20PresetMinterPauser public rewardToken; IERC20 public multiplierToken; uint256 public DURATION; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public deployedTime; uint256 public multiplierTokenDevFund; uint256 public constant boostLevelOneCost = 12000000000000000; uint256 public constant boostLevelTwoCost = 40000000000000000; uint256 public constant boostLevelThreeCost = 120000000000000000; uint256 public constant boostLevelFourCost = 240000000000000000; uint256 public constant FivePercentBonus = 50000000000000000; uint256 public constant TwentyPercentBonus = 200000000000000000; uint256 public constant FourtyPercentBonus = 400000000000000000; uint256 public constant HundredPercentBonus = 1000000000000000000; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public spentMultiplierTokens; mapping(address => uint256) public boostLevel; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Boost(uint256 level); constructor( address _stakingToken, address _rewardToken, address _multiplierToken, uint256 _startTime, uint256 _duration ______ __ __ ) public LPTokenWrapper(_startTime) { setStakingToken(_stakingToken); rewardToken = ERC20PresetMinterPauser(_rewardToken); multiplierToken = IERC20(_multiplierToken); deployedTime = block.timestamp; DURATION = _duration; } function setOwner(address _newOwner) external onlyOwner { super.transferOwnership(_newOwner); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (block.timestamp < startTime) { return 0; } if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(effectiveTotalSupply) ); } function rewardPerToken() public view returns (uint256) { if (block.timestamp < startTime) { return 0; } if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(effectiveTotalSupply) ); } function rewardPerToken() public view returns (uint256) { if (block.timestamp < startTime) { return 0; } if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(effectiveTotalSupply) ); } uint256 effectiveTotalSupply = _totalSupply.add(_totalSupplyAccounting); function earned(address account) public view returns (uint256) { uint256 effectiveBalance = _balances[account].add( _balancesAccounting[account] ); return effectiveBalance .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function stake(uint256 amount) public override { updateReward(msg.sender); require(amount > 0, "Cannot stake 0"); super.stake(amount); if (boostLevel[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Staked(msg.sender, amount); } function stake(uint256 amount) public override { updateReward(msg.sender); require(amount > 0, "Cannot stake 0"); super.stake(amount); if (boostLevel[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); super.withdraw(amount); if (boostLevel[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = prevBalancesAccounting.sub( newBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.sub( diffBalancesAccounting ); } emit Withdrawn(msg.sender, amount); } function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); super.withdraw(amount); if (boostLevel[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = prevBalancesAccounting.sub( newBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.sub( diffBalancesAccounting ); } emit Withdrawn(msg.sender, amount); } function exit() external { getReward(); withdraw(balanceOf(msg.sender)); } function getReward() public { updateReward(msg.sender); uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.mint(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function getReward() public { updateReward(msg.sender); uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.mint(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } function notifyRewardAmount(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } } else { function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } emit RewardAdded(reward); } function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } emit RewardAdded(reward); } } else { function getLevel(address account) external view returns (uint256) { return boostLevel[account]; } function getSpent(address account) external view returns (uint256) { return spentMultiplierTokens[account]; } function calculateCost(uint256 level) public pure returns (uint256) { if (level == 1) { return boostLevelOneCost; return boostLevelTwoCost; return boostLevelThreeCost; return boostLevelFourCost; } } function calculateCost(uint256 level) public pure returns (uint256) { if (level == 1) { return boostLevelOneCost; return boostLevelTwoCost; return boostLevelThreeCost; return boostLevelFourCost; } } } else if (level == 2) { } else if (level == 3) { } else if (level == 4) { function purchase(uint256 level) external { require( boostLevel[msg.sender] <= level, "Cannot downgrade level or same level" ); uint256 cost = calculateCost(level); uint256 finalCost = cost.sub(spentMultiplierTokens[msg.sender]); multiplierToken.safeTransferFrom(msg.sender, address(this), finalCost); multiplierTokenDevFund = multiplierTokenDevFund.add(finalCost); spentMultiplierTokens[msg.sender] = spentMultiplierTokens[msg.sender] .add(finalCost); boostLevel[msg.sender] = level; if (_balances[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Boost(level); } function purchase(uint256 level) external { require( boostLevel[msg.sender] <= level, "Cannot downgrade level or same level" ); uint256 cost = calculateCost(level); uint256 finalCost = cost.sub(spentMultiplierTokens[msg.sender]); multiplierToken.safeTransferFrom(msg.sender, address(this), finalCost); multiplierTokenDevFund = multiplierTokenDevFund.add(finalCost); spentMultiplierTokens[msg.sender] = spentMultiplierTokens[msg.sender] .add(finalCost); boostLevel[msg.sender] = level; if (_balances[msg.sender] > 0) { uint256 prevBalancesAccounting = _balancesAccounting[msg.sender]; uint256 accTotalMultiplier = getTotalMultiplier(msg.sender); uint256 newBalancesAccounting = _balances[msg.sender] .mul(accTotalMultiplier) .div(1e18) .sub(_balances[msg.sender]); _balancesAccounting[msg.sender] = newBalancesAccounting; uint256 diffBalancesAccounting = newBalancesAccounting.sub( prevBalancesAccounting ); _totalSupplyAccounting = _totalSupplyAccounting.add( diffBalancesAccounting ); } emit Boost(level); } function getTotalMultiplier(address account) public view returns (uint256) { uint256 boostMultiplier = 0; if (boostLevel[account] == 1) { boostMultiplier = FivePercentBonus; boostMultiplier = TwentyPercentBonus; boostMultiplier = FourtyPercentBonus; boostMultiplier = HundredPercentBonus; } return boostMultiplier.add(1 * 10**18); } function getTotalMultiplier(address account) public view returns (uint256) { uint256 boostMultiplier = 0; if (boostLevel[account] == 1) { boostMultiplier = FivePercentBonus; boostMultiplier = TwentyPercentBonus; boostMultiplier = FourtyPercentBonus; boostMultiplier = HundredPercentBonus; } return boostMultiplier.add(1 * 10**18); } } else if (boostLevel[account] == 2) { } else if (boostLevel[account] == 3) { } else if (boostLevel[account] == 4) { function distributeDevFund() public override { uint256 totalMulitplierDistributionAmount = multiplierTokenDevFund; multiplierTokenDevFund = 0; for (uint256 i = 0; i < devCount; i++) { uint256 devPercentage = devAllocations[devIDs[i]]; uint256 allocation = totalMulitplierDistributionAmount .mul(devPercentage) .div(100); if (allocation > 0) { multiplierToken.safeTransfer(devIDs[i], allocation); } } } function distributeDevFund() public override { uint256 totalMulitplierDistributionAmount = multiplierTokenDevFund; multiplierTokenDevFund = 0; for (uint256 i = 0; i < devCount; i++) { uint256 devPercentage = devAllocations[devIDs[i]]; uint256 allocation = totalMulitplierDistributionAmount .mul(devPercentage) .div(100); if (allocation > 0) { multiplierToken.safeTransfer(devIDs[i], allocation); } } } function distributeDevFund() public override { uint256 totalMulitplierDistributionAmount = multiplierTokenDevFund; multiplierTokenDevFund = 0; for (uint256 i = 0; i < devCount; i++) { uint256 devPercentage = devAllocations[devIDs[i]]; uint256 allocation = totalMulitplierDistributionAmount .mul(devPercentage) .div(100); if (allocation > 0) { multiplierToken.safeTransfer(devIDs[i], allocation); } } } super.distributeDevFund(); function eject() external onlyOwner { require( startTime < block.timestamp && block.timestamp >= periodFinish, "Cannot eject before period finishes or pool has started" ); uint256 currBalance = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(msg.sender, currBalance); } function kill() external onlyOwner { periodFinish = block.timestamp; } function updateRewardPerTokenStored() internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); } function updateReward(address account) internal { updateRewardPerTokenStored(); rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } }
1,448,590
[ 1, 42, 985, 5535, 7263, 4722, 30, 490, 474, 429, 2864, 18, 18281, 282, 268, 19938, 30, 399, 12536, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 587, 6427, 88, 41, 451, 30948, 38, 18593, 353, 511, 52, 1345, 3611, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 18385, 49, 2761, 16507, 1355, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 4232, 39, 3462, 18385, 49, 2761, 16507, 1355, 1071, 19890, 1345, 31, 203, 565, 467, 654, 39, 3462, 1071, 15027, 1345, 31, 203, 203, 565, 2254, 5034, 1071, 31794, 31, 203, 565, 2254, 5034, 1071, 3879, 11641, 31, 203, 565, 2254, 5034, 1071, 19890, 4727, 31, 203, 565, 2254, 5034, 1071, 1142, 1891, 950, 31, 203, 565, 2254, 5034, 1071, 19890, 2173, 1345, 18005, 31, 203, 565, 2254, 5034, 1071, 19357, 950, 31, 203, 565, 2254, 5034, 1071, 15027, 1345, 8870, 42, 1074, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 14994, 2355, 3335, 8018, 273, 2593, 12648, 17877, 31, 203, 565, 2254, 5034, 1071, 5381, 14994, 2355, 11710, 8018, 273, 1059, 12648, 12648, 31, 203, 565, 2254, 5034, 1071, 5381, 14994, 2355, 28019, 8018, 273, 2593, 12648, 12648, 31, 203, 565, 2254, 5034, 1071, 5381, 14994, 2355, 42, 477, 8018, 273, 4248, 12648, 12648, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 478, 688, 8410, 38, 22889, 273, 1381, 12648, 12648, 31, 203, 565, 2254, 5034, 1071, 5381, 12694, 319, 93, 8410, 38, 22889, 273, 576, 12648, 2787, 11706, 31, 203, 565, 2254, 5034, 1071, 5381, 478, 477, 4098, 8410, 38, 22889, 273, 1059, 12648, 2787, 11706, 31, 203, 565, 2254, 5034, 1071, 2 ]
./full_match/80001/0xB447B59d547Ba4BCD85269d6b700a84A01bb381f/sources/contracts/Battle.sol
Populate the CharacterProxy for player 1
createCharacterProxies(_characterTokenId, msg.sender, battleId);
852,419
[ 1, 19097, 326, 6577, 3886, 364, 7291, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 752, 7069, 21488, 24899, 11560, 1345, 548, 16, 1234, 18, 15330, 16, 324, 4558, 298, 548, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xf2709c559785CF4D1AA9C9a0ad6E0BB413afdF7a/sources/DarkNyanV2.sol
* @notice Swaps an amount dNyan for dNyanV2. @param _amount Amount of dNyanV1 to swap./DNyanV2 swap event
function swapDNyanV1(uint256 _amount) public delegatedOnly { IERC20(dNyanV1).safeTransferFrom(msg.sender, address(this), _amount); uint256 bonus = _amount.mul(2000).div(10000); _mint(msg.sender, _amount.add(bonus)); totalDNyanSwapped = totalDNyanSwapped.add(_amount); }
11,031,610
[ 1, 6050, 6679, 392, 3844, 302, 50, 93, 304, 364, 302, 50, 93, 304, 58, 22, 18, 225, 389, 8949, 16811, 434, 302, 50, 93, 304, 58, 21, 358, 7720, 18, 19, 8609, 93, 304, 58, 22, 7720, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 8609, 93, 304, 58, 21, 12, 11890, 5034, 389, 8949, 13, 1071, 30055, 3386, 288, 203, 3639, 467, 654, 39, 3462, 12, 72, 50, 93, 304, 58, 21, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 2254, 5034, 324, 22889, 273, 389, 8949, 18, 16411, 12, 17172, 2934, 2892, 12, 23899, 1769, 203, 4202, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 8949, 18, 1289, 12, 18688, 407, 10019, 203, 4202, 2078, 8609, 93, 304, 12521, 1845, 273, 2078, 8609, 93, 304, 12521, 1845, 18, 1289, 24899, 8949, 1769, 203, 3639, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x14a733278d2C792d1b93DEF58C30CC16AED0DcCD/sources/Squries.sol
check allowed Contracts
function checkAllowedContracts(address addr) public view returns (bool) { return allowedContracts[addr]; }
729,072
[ 1, 1893, 2935, 30131, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 5042, 20723, 12, 2867, 3091, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 1377, 327, 2935, 20723, 63, 4793, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9dc3beC75bd375E1a64279894F780ba7634ea53e/sources/Ethermaze.sol
* @dev Close old contract interaction/
function oldETHMazeSyncClosed() external { require(address(oldETHMaze) != address(0), "Initialize already closed"); require(msg.sender == ownerAddress, "Access denied"); oldETHMaze = Ethermaze(0); }
2,834,708
[ 1, 4605, 1592, 6835, 13581, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1592, 1584, 44, 49, 1561, 73, 4047, 7395, 1435, 3903, 288, 203, 3639, 2583, 12, 2867, 12, 1673, 1584, 44, 49, 1561, 73, 13, 480, 1758, 12, 20, 3631, 315, 7520, 1818, 4375, 8863, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1887, 16, 315, 1862, 15338, 8863, 203, 203, 3639, 1592, 1584, 44, 49, 1561, 73, 273, 512, 451, 1035, 1561, 73, 12, 20, 1769, 203, 565, 289, 203, 377, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; /** * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ####################################### ###################################### * ##################################### #################################### * ################################### ################################## * ################################# ################################ * ################################################################################ * ################################################################################ * ################ #### ### ############### * ################ #### ############# #### ############### * ################ #### ########### #### ############### * ################ ### ## ####### ## #### ############### * ################ #### ###### ##### ###### #### ############### * ################ #### #### ############### * #################### ######### ################### * ################ ####### ############### * ################ ############### ############## ################ * ################# ############# ############ ################# * ################### ########## ########## ################## * #################### ####### ####### ################### * ###################### ### ### ###################### * ########################## ######################### * ############################# ############################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * * The Mutytes have invaded Ethernia! We hereby extend access to the lab and * its facilities to any individual or party that may locate and retrieve a * Mutyte sample. We believe their mutated Bit Signatures hold the key to * unraveling many great mysteries. * Join our efforts in understanding these creatures and witness Ethernia's * future unfold. * * Founders: @nftyte & @tuyumoo */ import "./token/ERC721GeneticData.sol"; import "./access/Reservable.sol"; import "./access/ProxyOperated.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./mutations/IMutationInterpreter.sol"; interface ILabArchive { function getMutyteInfo(uint256 tokenId) external view returns (string memory name, string memory info); function getMutationInfo(uint256 mutationId) external view returns (string memory name, string memory info); } interface IBineticSplicer { function getSplices(uint256 tokenId) external view returns (uint256[] memory); } contract Mutytes is ERC721GeneticData, IERC721Metadata, Reservable, ProxyOperated { string constant NAME = "Mutytes"; string constant SYMBOL = "TYTE"; uint256 constant MINT_PER_ADDR = 10; uint256 constant MINT_PER_ADDR_EQ = MINT_PER_ADDR + 1; // Skip the equator uint256 constant MINT_PRICE = 0.1 ether; address public labArchiveAddress; address public bineticSplicerAddress; string public externalURL; constructor( string memory externalURL_, address interpreter, address proxyRegistry, uint8 reserved ) Reservable(reserved) ProxyOperated(proxyRegistry) MutationRegistry(interpreter) { externalURL = externalURL_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165) returns (bool) { return interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function mint(uint256 count) external payable { uint256 id = maxSupply; require(id > 0, "Mutytes: public mint not open"); require( id + count < MAX_SUPPLY_EQ - reserved, "Mutytes: amount exceeds available supply" ); require( count > 0 && _getBalance(_msgSender()) + count < MINT_PER_ADDR_EQ, "Mutytes: invalid token count" ); require( msg.value == count * MINT_PRICE, "Mutytes: incorrect amount of ether sent" ); _mint(_msgSender(), id, count); } function mintReserved(uint256 count) external fromAllowance(count) { _mint(_msgSender(), maxSupply, count); } function setLabArchiveAddress(address archive) external onlyOwner { labArchiveAddress = archive; } function setBineticSplicerAddress(address splicer) external onlyOwner { bineticSplicerAddress = splicer; } function setExternalURL(string calldata url) external onlyOwner { externalURL = url; } /** * @dev See {IERC721Metadata-name}. */ function name() public pure override returns (string memory) { return NAME; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public pure override returns (string memory) { return SYMBOL; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override tokenExists(tokenId) returns (string memory) { uint256 mutationId = getTokenMutation(tokenId); IMutationInterpreter interpreter = IMutationInterpreter( getMutation(mutationId).interpreter ); IMutationInterpreter.TokenData memory token; token.id = tokenId; IMutationInterpreter.MutationData memory mutation; mutation.id = mutationId; mutation.count = _countTokenMutations(tokenId); if (bineticSplicerAddress != address(0)) { IBineticSplicer splicer = IBineticSplicer(bineticSplicerAddress); token.dna = getTokenDNA(tokenId, splicer.getSplices(tokenId)); } else { token.dna = getTokenDNA(tokenId); } if (labArchiveAddress != address(0)) { ILabArchive archive = ILabArchive(labArchiveAddress); (token.name, token.info) = archive.getMutyteInfo(tokenId); (mutation.name, mutation.info) = archive.getMutationInfo( mutationId ); } return interpreter.tokenURI(token, mutation, externalURL); } function burn(uint256 tokenId) public onlyApprovedOrOwner(tokenId) { _burn(tokenId); } function isApprovedForAll(address owner, address operator) public view override(ERC721Enumerable, IERC721) returns (bool) { return _isProxyApprovedForAll(owner, operator) || super.isApprovedForAll(owner, operator); } function withdraw() public payable onlyOwner { (bool owner, ) = payable(owner()).call{value: address(this).balance}( "" ); require(owner, "Mutytes: withdrawal failed"); } function _mint( address to, uint256 tokenId, uint256 count ) private { uint256 inventory = _getOrSubscribeInventory(to); bytes32 dna; unchecked { uint256 max = tokenId + count; while (tokenId < max) { if (dna == 0) { dna = keccak256( abi.encodePacked( tokenId, inventory, block.number, block.difficulty, reserved ) ); } _tokenToInventory[tokenId] = uint16(inventory); _tokenBaseGenes[tokenId] = uint64(bytes8(dna)); dna <<= 64; emit Transfer(address(0), to, tokenId++); } } _increaseBalance(to, count); maxSupply = tokenId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Enumerable.sol"; import "./IERC721GeneticData.sol"; import "../mutations/MutationRegistry.sol"; /** * @dev An ERC721 extension that provides access to storage and expansion of token information. * Initial data is stored in the base genes map. Newly introduced data will be stored in the extended genes map. * Token information may be extended whenever a token unlocks new mutations from the mutation registry. * Mutation catalysts may forcefully unlock or cause mutations. * Implementation inspired by nftchance's Mimetic Metadata concept. */ abstract contract ERC721GeneticData is ERC721Enumerable, MutationRegistry, IERC721GeneticData { // Mapping from token ID to base genes uint64[MAX_SUPPLY] internal _tokenBaseGenes; // Mapping from token ID to extended genes uint8[][MAX_SUPPLY] private _tokenExtendedGenes; // Mapping from token ID to active mutation uint8[MAX_SUPPLY] private _tokenMutation; // Mapping from token ID to unlocked mutations bool[MAX_MUTATIONS][MAX_SUPPLY] public tokenUnlockedMutations; // List of mutation catalysts mapping(address => bool) public mutationCatalysts; modifier onlyMutationCatalyst() { require( mutationCatalysts[_msgSender()], "ERC721GeneticData: caller is not catalyst" ); _; } /** * @dev Returns the token's active mutation. */ function getTokenMutation(uint256 tokenId) public view override tokenExists(tokenId) returns (uint256) { return _tokenMutation[tokenId]; } /** * @dev Returns the token's DNA sequence. */ function getTokenDNA(uint256 tokenId) public view override returns (uint256[] memory) { uint256[] memory splices; return getTokenDNA(tokenId, splices); } /** * @dev Returns the token's DNA sequence. * @param splices DNA customizations to apply */ function getTokenDNA(uint256 tokenId, uint256[] memory splices) public view override tokenExists(tokenId) returns (uint256[] memory) { uint8[] memory genes = _tokenExtendedGenes[tokenId]; uint256 geneCount = genes.length; uint256 spliceCount = splices.length; uint256[] memory dna = new uint256[](geneCount + 1); dna[0] = uint256(keccak256(abi.encodePacked(_tokenBaseGenes[tokenId]))); for (uint256 i; i < geneCount; i++) { // Expand genes and add to DNA sequence dna[i + 1] = uint256(keccak256(abi.encodePacked(dna[i], genes[i]))); // Splice previous genes if (i < spliceCount) { dna[i] ^= splices[i]; } } // Splice final genes if (spliceCount == geneCount + 1) { dna[geneCount] ^= splices[geneCount]; } return dna; } /** * @dev Gets the number of unlocked token mutations. */ function countTokenMutations(uint256 tokenId) external view override tokenExists(tokenId) returns (uint256) { return _countTokenMutations(tokenId); } /** * @dev Checks whether the token has unlocked a mutation. * note base mutation is always unlocked. */ function isMutationUnlocked(uint256 tokenId, uint256 mutationId) external view override tokenExists(tokenId) mutationExists(mutationId) returns (bool) { return _isMutationUnlocked(tokenId, mutationId); } /** * @dev Checks whether the token can mutate to a mutation safely. */ function canMutate(uint256 tokenId, uint256 mutationId) external view override tokenExists(tokenId) mutationExists(mutationId) returns (bool) { return _canMutate(tokenId, mutationId); } /** * @dev Toggles a mutation catalyst's state. */ function toggleMutationCatalyst(address catalyst) external onlyOwner { mutationCatalysts[catalyst] = !mutationCatalysts[catalyst]; } /** * @dev Unlocks a mutation for the token. * @param force unlocks mutation even if it can't be mutated to. */ function safeCatalystUnlockMutation( uint256 tokenId, uint256 mutationId, bool force ) external override tokenExists(tokenId) mutationExists(mutationId) { require( !_isMutationUnlocked(tokenId, mutationId), "ERC721GeneticData: unlock to unlocked mutation" ); require( force || _canMutate(tokenId, mutationId), "ERC721GeneticData: unlock to unavailable mutation" ); catalystUnlockMutation(tokenId, mutationId); } /** * @dev Unlocks a mutation for the token. */ function catalystUnlockMutation(uint256 tokenId, uint256 mutationId) public override onlyMutationCatalyst { _unlockMutation(tokenId, mutationId); } /** * @dev Changes a token's active mutation if it's unlocked. */ function safeCatalystMutate(uint256 tokenId, uint256 mutationId) external override tokenExists(tokenId) mutationExists(mutationId) { require( _tokenMutation[tokenId] != mutationId, "ERC721GeneticData: mutate to active mutation" ); require( _isMutationUnlocked(tokenId, mutationId), "ERC721GeneticData: mutate to locked mutation" ); catalystMutate(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function catalystMutate(uint256 tokenId, uint256 mutationId) public override onlyMutationCatalyst { _mutate(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function mutate(uint256 tokenId, uint256 mutationId) external payable override onlyApprovedOrOwner(tokenId) mutationExists(mutationId) { if (_isMutationUnlocked(tokenId, mutationId)) { require( _tokenMutation[tokenId] != mutationId, "ERC721GeneticData: mutate to active mutation" ); } else { require( _canMutate(tokenId, mutationId), "ERC721GeneticData: mutate to unavailable mutation" ); require( msg.value == getMutation(mutationId).cost, "ERC721GeneticData: incorrect amount of ether sent" ); _unlockMutation(tokenId, mutationId); } _mutate(tokenId, mutationId); } /** * @dev Allows owner to regenerate cloned genes. */ function unclone(uint256 tokenA, uint256 tokenB) external onlyOwner { require(tokenA != tokenB, "ERC721GeneticData: unclone of same token"); uint256 genesA = _tokenBaseGenes[tokenA]; require( genesA == _tokenBaseGenes[tokenB], "ERC721GeneticData: unclone of uncloned tokens" ); _tokenBaseGenes[tokenA] = uint64(bytes8(_getGenes(tokenA, genesA))); } /** * @dev Gets the number of unlocked token mutations. */ function _countTokenMutations(uint256 tokenId) internal view returns (uint256) { uint256 count = 1; bool[MAX_MUTATIONS] memory mutations = tokenUnlockedMutations[tokenId]; for (uint256 i = 1; i < MAX_MUTATIONS; i++) { if (mutations[i]) { count++; } } return count; } /** * @dev Checks whether the token has unlocked a mutation. * note base mutation is always unlocked. */ function _isMutationUnlocked(uint256 tokenId, uint256 mutationId) private view returns (bool) { return mutationId == 0 || tokenUnlockedMutations[tokenId][mutationId]; } /** * @dev Checks whether the token can mutate to a mutation. */ function _canMutate(uint256 tokenId, uint256 mutationId) private view returns (bool) { uint256 activeMutationId = _tokenMutation[tokenId]; uint256 nextMutationId = getMutation(activeMutationId).next; Mutation memory mutation = getMutation(mutationId); return mutation.enabled && (nextMutationId == 0 || nextMutationId == mutationId) && (mutation.prev == 0 || mutation.prev == activeMutationId); } /** * @dev Unlocks a token's mutation. */ function _unlockMutation(uint256 tokenId, uint256 mutationId) private { tokenUnlockedMutations[tokenId][mutationId] = true; _addGenes(tokenId, getMutation(mutationId).geneCount); emit UnlockMutation(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function _mutate(uint256 tokenId, uint256 mutationId) private { _tokenMutation[tokenId] = uint8(mutationId); emit Mutate(tokenId, mutationId); } /** * @dev Adds new genes to the token's DNA sequence. */ function _addGenes(uint256 tokenId, uint256 maxGeneCount) private { uint8[] storage genes = _tokenExtendedGenes[tokenId]; uint256 geneCount = genes.length; bytes32 newGenes; while (geneCount < maxGeneCount) { if (newGenes == 0) { newGenes = _getGenes(tokenId, geneCount); } genes.push(uint8(bytes1(newGenes))); newGenes <<= 8; unchecked { geneCount++; } } } /** * @dev Gets new genes for a token's DNA sequence. */ function _getGenes(uint256 tokenId, uint256 seed) private view returns (bytes32) { return keccak256( abi.encodePacked( tokenId, seed, ownerOf(tokenId), block.number, block.difficulty ) ); } function _burn(uint256 tokenId) internal override { delete _tokenMutation[tokenId]; delete _tokenBaseGenes[tokenId]; delete _tokenExtendedGenes[tokenId]; delete tokenUnlockedMutations[tokenId]; super._burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev An extension to manage token allowances. */ contract Reservable is Ownable { uint256 public reserved; mapping(address => uint256) public allowances; modifier fromAllowance(uint256 count) { require( count > 0 && count <= allowances[_msgSender()] && count <= reserved, "Reservable: reserved tokens mismatch" ); _; unchecked { allowances[_msgSender()] -= count; reserved -= count; } } constructor(uint256 reserved_) { reserved = reserved_; } function reserve(address[] calldata addresses, uint256[] calldata allowance) external onlyOwner { uint256 count = addresses.length; require(count == allowance.length, "Reservable: data mismatch"); do { count--; allowances[addresses[count]] = allowance[count]; } while (count > 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev An extension that grants approvals to proxy operators. * Inspired by NuclearNerds' implementation. */ contract ProxyOperated is Ownable { address public proxyRegistryAddress; mapping(address => bool) public projectProxy; constructor(address proxy) { proxyRegistryAddress = proxy; } function toggleProxyState(address proxy) external onlyOwner { projectProxy[proxy] = !projectProxy[proxy]; } function setProxyRegistryAddress(address proxy) external onlyOwner { proxyRegistryAddress = proxy; } function _isProxyApprovedForAll(address owner, address operator) internal view returns (bool) { bool isApproved; if (proxyRegistryAddress != address(0)) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( proxyRegistryAddress ); isApproved = address(proxyRegistry.proxies(owner)) == operator; } return isApproved || projectProxy[operator]; } } contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // 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 pragma solidity ^0.8.0; interface IMutationInterpreter { struct TokenData { uint256 id; string name; string info; uint256[] dna; } struct MutationData { uint256 id; string name; string info; uint256 count; } function tokenURI( TokenData calldata token, MutationData calldata mutation, string calldata externalURL ) external view returns (string memory); } // SPDX-License-Identifier: MIT // Modified from OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./TokenInventories.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Enumerable extension, but not including the Metadata extension. This implementation was modified to * make use of a token inventories layer instead of the original data-structures. */ abstract contract ERC721Enumerable is Context, TokenInventories, ERC165, IERC721Enumerable { using Address for address; // Number of tokens minted uint256 public maxSupply; // Number of tokens burned uint256 public burned; // Mapping from token ID to inventory uint16[MAX_SUPPLY] internal _tokenToInventory; // 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; modifier tokenExists(uint256 tokenId) { require( _exists(tokenId), "ERC721Enumerable: query for nonexistent token" ); _; } modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Enumerable: caller is not owner nor approved" ); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return maxSupply - burned; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < totalSupply(), "ERC721Enumerable: global index out of bounds" ); uint256 i; for (uint256 j; true; i++) { if (_tokenToInventory[i] != 0 && j++ == index) { break; } } return i; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721Enumerable: balance query for the zero address" ); return _getBalance(owner); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override tokenExists(tokenId) returns (address) { return _getInventoryOwner(_tokenToInventory[tokenId]); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < balanceOf(owner), "ERC721Enumerable: index query for nonexistent token" ); uint256 i; for (uint256 count; count <= index; i++) { if (_getInventoryOwner(_tokenToInventory[i]) == owner) { count++; } } return i - 1; } /** * @dev Returns the owner's tokens. */ function walletOfOwner(address owner) public view virtual returns (uint256[] memory) { uint256 balance = balanceOf(owner); if (balance == 0) { return new uint256[](0); } uint256[] memory tokens = new uint256[](balance); for (uint256 j; balance > 0; j++) { if (ownerOf(j) == owner) { tokens[tokens.length - balance--] = j; } } return tokens; } /** * @dev Checks if multiple tokens belong to an owner. */ function isOwnerOf(address owner, uint256[] memory tokenIds) public view virtual returns (bool) { for (uint256 i; i < tokenIds.length; i++) { if (ownerOf(tokenIds[i]) != owner) { return false; } } return true; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721Enumerable: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721Enumerable: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override tokenExists(tokenId) returns (address) { return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override onlyApprovedOrOwner(tokenId) { _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 onlyApprovedOrOwner(tokenId) { _safeTransfer(from, to, tokenId, _data); } function batchTransferFrom( address from, address to, uint256[] memory tokenIds ) public virtual { for (uint256 i; i < tokenIds.length; i++) { transferFrom(from, to, tokenIds[i]); } } function batchSafeTransferFrom( address from, address to, uint256[] memory tokenIds, bytes memory data_ ) public virtual { for (uint256 i; i < tokenIds.length; i++) { safeTransferFrom(from, to, tokenIds[i], 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), "ERC721Enumerable: 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 tokenId < MAX_SUPPLY && _tokenToInventory[tokenId] != 0; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual tokenExists(tokenId) returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @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); // Clear approvals _approve(address(0), tokenId); delete _tokenToInventory[tokenId]; _decreaseBalance(owner, 1); burned++; 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( ownerOf(tokenId) == from, "ERC721Enumerable: transfer from incorrect owner" ); require( to != address(0), "ERC721Enumerable: transfer to the zero address" ); // Clear approvals from the previous owner _approve(address(0), tokenId); _decreaseBalance(from, 1); _tokenToInventory[tokenId] = uint16(_getOrSubscribeInventory(to)); _increaseBalance(to, 1); 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(ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721Enumerable: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721Enumerable: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../mutations/IMutationRegistry.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IERC721GeneticData is IERC721Enumerable, IMutationRegistry { event UnlockMutation(uint256 tokenId, uint256 mutationId); event Mutate(uint256 tokenId, uint256 mutationId); function getTokenMutation(uint256 tokenId) external view returns (uint256); function getTokenDNA(uint256 tokenId) external view returns (uint256[] memory); function getTokenDNA(uint256 tokenId, uint256[] memory splices) external view returns (uint256[] memory); function countTokenMutations(uint256 tokenId) external view returns (uint256); function isMutationUnlocked(uint256 tokenId, uint256 mutationId) external view returns (bool); function canMutate(uint256 tokenId, uint256 mutationId) external view returns (bool); function safeCatalystUnlockMutation( uint256 tokenId, uint256 mutationId, bool force ) external; function catalystUnlockMutation(uint256 tokenId, uint256 mutationId) external; function safeCatalystMutate(uint256 tokenId, uint256 mutationId) external; function catalystMutate(uint256 tokenId, uint256 mutationId) external; function mutate(uint256 tokenId, uint256 mutationId) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IMutationRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev Mutation data storage and operations. */ contract MutationRegistry is Ownable, IMutationRegistry { uint256 constant MAX_MUTATIONS = 256; // List of mutations mapping(uint256 => Mutation) private _mutations; modifier mutationExists(uint256 mutationId) { require( _mutations[mutationId].interpreter != address(0), "MutationRegistry: query for nonexistent mutation" ); _; } /** * @dev Initialize a new instance with an active base mutation. */ constructor(address interpreter) { loadMutation(0, true, false, 0, 0, 0, interpreter, 0); } /** * @dev Retrieves a mutation. */ function getMutation(uint256 mutationId) public view override returns (Mutation memory) { return _mutations[mutationId]; } /** * @dev Loads a new mutation. * @param enabled mutation can be mutated to * @param finalized mutation can't be updated * @param prev mutation link, 0 is any * @param next mutation link, 0 is any * @param geneCount required for the mutation * @param interpreter address for the mutation * @param cost of unlocking the mutation */ function loadMutation( uint8 mutationId, bool enabled, bool finalized, uint8 prev, uint8 next, uint8 geneCount, address interpreter, uint256 cost ) public onlyOwner { require( _mutations[mutationId].interpreter == address(0), "MutationRegistry: load to existing mutation" ); require( interpreter != address(0), "MutationRegistry: invalid interpreter" ); _mutations[mutationId] = Mutation( enabled, finalized, prev, next, geneCount, interpreter, cost ); } /** * @dev Toggles a mutation's enabled state. * note finalized mutations can't be toggled. */ function toggleMutation(uint256 mutationId) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( !mutation.finalized, "MutationRegistry: toggle to finalized mutation" ); mutation.enabled = !mutation.enabled; } /** * @dev Marks a mutation as finalized, preventing it from being updated in the future. * note this action can't be reverted. */ function finalizeMutation(uint256 mutationId) external onlyOwner mutationExists(mutationId) { _mutations[mutationId].finalized = true; } /** * @dev Updates a mutation's interpreter. * note finalized mutations can't be updated. */ function updateMutationInterpreter(uint256 mutationId, address interpreter) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( interpreter != address(0), "MutationRegistry: zero address interpreter" ); require( !mutation.finalized, "MutationRegistry: update to finalized mutation" ); mutation.interpreter = interpreter; } /** * @dev Updates a mutation's links. * note finalized mutations can't be updated. */ function updateMutationLinks( uint8 mutationId, uint8 prevMutationId, uint8 nextMutationId ) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( !mutation.finalized, "MutationRegistry: update to finalized mutation" ); mutation.prev = prevMutationId; mutation.next = nextMutationId; } } // 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); } // 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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 pragma solidity ^0.8.0; /** * @dev A subscription-based inventory system that can be used as a middle layer between owners and tokens. * There may be MAX_SUPPLY + 1 inventory owners in total, as the zero-address owns the first inventory. * Inventory IDs are packed together with inventory balances to save storage. * Implementation inspired by Azuki's batch-minting technique. */ contract TokenInventories { uint256 constant MAX_SUPPLY = 10101; uint256 constant MAX_SUPPLY_EQ = MAX_SUPPLY + 1; uint16[] private _vacantInventories; address[] private _inventoryToOwner; mapping(address => uint256) private _ownerToInventory; constructor() { _inventoryToOwner.push(address(0)); } function _getInventoryOwner(uint256 inventory) internal view returns (address) { return _inventoryToOwner[inventory]; } function _getInventoryId(address owner) internal view returns (uint256) { return _ownerToInventory[owner] & 0xFFFF; } function _getBalance(address owner) internal view returns (uint256) { return _ownerToInventory[owner] >> 16; } function _setBalance(address owner, uint256 balance) internal { _ownerToInventory[owner] = _getInventoryId(owner) | (balance << 16); } function _increaseBalance(address owner, uint256 count) internal { unchecked { _setBalance(owner, _getBalance(owner) + count); } } /** * @dev Decreases an owner's inventory balance and unsubscribes from the inventory when it's empty. * @param count must be equal to owner's balance at the most */ function _decreaseBalance(address owner, uint256 count) internal { uint256 balance = _getBalance(owner); if (balance == count) { _unsubscribeInventory(owner); } else { unchecked { _setBalance(owner, balance - count); } } } /** * @dev Returns an owner's inventory ID. If the owner doesn't have an inventory they are assigned a * vacant one. */ function _getOrSubscribeInventory(address owner) internal returns (uint256) { uint256 id = _getInventoryId(owner); return id == 0 ? _subscribeInventory(owner) : id; } /** * @dev Subscribes an owner to a vacant inventory and returns its ID. * The inventory list's length has to be MAX_SUPPLY + 1 before inventories from the vacant inventories * list are assigned. */ function _subscribeInventory(address owner) private returns (uint256) { if (_inventoryToOwner.length < MAX_SUPPLY_EQ) { _ownerToInventory[owner] = _inventoryToOwner.length; _inventoryToOwner.push(owner); } else if (_vacantInventories.length > 0) { unchecked { uint256 id = _vacantInventories[_vacantInventories.length - 1]; _vacantInventories.pop(); _ownerToInventory[owner] = id; _inventoryToOwner[id] = owner; } } return _ownerToInventory[owner]; } /** * @dev Unsubscribes an owner from their inventory and updates the vacant inventories list. */ function _unsubscribeInventory(address owner) private { uint256 id = _getInventoryId(owner); delete _ownerToInventory[owner]; delete _inventoryToOwner[id]; _vacantInventories.push(uint16(id)); } } // 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 (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 pragma solidity ^0.8.0; interface IMutationRegistry { struct Mutation { bool enabled; bool finalized; uint8 prev; uint8 next; uint8 geneCount; address interpreter; uint256 cost; } function getMutation(uint256 mutationId) external view returns (Mutation memory); } // 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); } }
* @dev Unlocks a mutation for the token. @param force unlocks mutation even if it can't be mutated to./
function safeCatalystUnlockMutation( uint256 tokenId, uint256 mutationId, bool force ) external override tokenExists(tokenId) mutationExists(mutationId) { require( !_isMutationUnlocked(tokenId, mutationId), "ERC721GeneticData: unlock to unlocked mutation" ); require( force || _canMutate(tokenId, mutationId), "ERC721GeneticData: unlock to unavailable mutation" ); catalystUnlockMutation(tokenId, mutationId); }
257,003
[ 1, 7087, 87, 279, 11934, 364, 326, 1147, 18, 225, 2944, 7186, 87, 11934, 5456, 309, 518, 848, 1404, 506, 27414, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 39, 3145, 1094, 7087, 20028, 12, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 11934, 548, 16, 203, 3639, 1426, 2944, 203, 565, 262, 3903, 3849, 1147, 4002, 12, 2316, 548, 13, 11934, 4002, 12, 28868, 548, 13, 288, 203, 3639, 2583, 12, 203, 5411, 401, 67, 291, 20028, 7087, 329, 12, 2316, 548, 16, 11934, 548, 3631, 203, 5411, 315, 654, 39, 27, 5340, 7642, 7943, 751, 30, 7186, 358, 25966, 11934, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 2944, 747, 389, 4169, 7420, 340, 12, 2316, 548, 16, 11934, 548, 3631, 203, 5411, 315, 654, 39, 27, 5340, 7642, 7943, 751, 30, 7186, 358, 15781, 11934, 6, 203, 3639, 11272, 203, 203, 3639, 276, 3145, 1094, 7087, 20028, 12, 2316, 548, 16, 11934, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicense pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./BancorBondingCurve.sol"; import "./Vision.sol"; /// @notice Controlling bonding curve for vision token. contract VisionVault is ReentrancyGuard { using SafeMath for uint; /// @notice Vision ERC777 token contract. Vision public vision; /// @notice Address Vision ERC777 token contract. address public visionAddress; /// @notice Stake token for Vision pool. IERC20 public stakeToken; /// @notice Total supply of Vision. Note this needs to start with 1 for minting. uint public mintedVision = 1; /// @notice Total StakeToken in Vision Pool. Note this needs to start with 1 for minting. uint public totalStakeInVisionVault = 1; /// @notice Initializiation boolean. bool public initialized; /// @notice Bancor bonding curve contract. IBancorBondingCurve public bondingCurve; constructor(address _stakeTokenAddress, address _monitorAddress, address _bondingCurveAddress) public { stakeToken = IERC20(_stakeTokenAddress); vision = new Vision(); visionAddress = address(vision); bondingCurve = IBancorBondingCurve(_bondingCurveAddress); } /// @notice Event capturing minted vision, cost, and address. event VisionMinted(uint minted, uint cost, address addr); /// @notice Mints new Vision based on the current price, using the amount deposited. /// @param amountDeposited Amount of stake to deposit. /// @dev Note you must supply the amount of Stake Token to produce new Vision. /// @dev Must approve stake token. function mintVision(uint amountDeposited) public nonReentrant { require(totalStakeInVisionVault != 0, "totalStakeInVisionVault should not be 0."); uint visionRate = mintedVision.div(totalStakeInVisionVault); uint visionToMint = visionRate.mul(amountDeposited); mintedVision = mintedVision.add(visionToMint); totalStakeInVisionVault = totalStakeInVisionVault.add(amountDeposited); vision.mint(msg.sender, visionToMint); stakeToken.transferFrom(msg.sender, address(this), amountDeposited); emit VisionMinted(visionToMint, amountDeposited, msg.sender); } /// @notice Event capturing burned vision, cost, and address. event VisionBurned(uint burned, uint cost, address addr); /// @notice Burns Vision based on the current price and returns 99% of allocated stake. /// @param visionToBurn Amount of vision to burn. /// @dev Invariant - totalStakeInVisionVault cannot be less than 1. /// @dev Invariant - mintedVision cannot be less than 1. /// @dev Note vision does not need to be approved to be burnt. function burnVision(uint visionToBurn) public nonReentrant { uint stakeRate = totalStakeInVisionVault.div(mintedVision); uint stakeToReturn = bondingCurve.mulDiv(stakeRate.mul(visionToBurn), 990000, 1000000); mintedVision = mintedVision.sub(visionToBurn); totalStakeInVisionVault = totalStakeInVisionVault.sub(stakeToReturn); require(totalStakeInVisionVault > 1, "Total Stake In Vision Vault must be greater than 1."); require(mintedVision > 1, "Minted Vision must be greater than 1."); vision.burn(msg.sender, visionToBurn); stakeToken.transfer(msg.sender, stakeToReturn); emit VisionBurned(visionToBurn, stakeToReturn, msg.sender); } }
@notice Event capturing burned vision, cost, and address.
event VisionBurned(uint burned, uint cost, address addr);
6,463,105
[ 1, 1133, 28789, 18305, 329, 331, 1951, 16, 6991, 16, 471, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 776, 1951, 38, 321, 329, 12, 11890, 18305, 329, 16, 2254, 6991, 16, 1758, 3091, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4 .4; /* This is the smart contract for the ERC 20 standard Tratok token. During development of the smart contract, active attention was paid to make the contract as simple as possible. As the majority of functions are simple addition and subtraction of existing balances, we have been able to make the contract very lightweight. This has the added advantage of reducing gas costs and ensuring that transaction fees remain low. The smart contract has been made publically available, keeping with the team's philosophy of transparency. @version "1.0" @developer "Tratok Team" @date "12 February 2017" @thoughts "207 lines that can change the travel and tourism industry!. Good luck!" */ /* * Use of the SafeMath Library prevents malicious input. For security consideration, the * smart contaract makes use of .add() and .sub() rather than += and -= */ library SafeMath { //Ensures that b is greater than a to handle negatives. function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } //Ensures that the sum of two values is greater than the intial value. function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * ERC20 Standard will be used * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { //the total supply of tokens uint public totalSupply; //@return Returns the total amount of Tratok tokens in existence. The amount remains capped at the pre-created 100 Billion. function totalSupply() constant returns(uint256 supply){} /* @param _owner The address of the wallet which needs to be queried for the amount of Tratok held. @return Returns the balance of Tratok tokens for the relevant address. */ function balanceOf(address who) constant returns(uint); /* The transfer function which takes the address of the recipient and the amount of Tratok needed to be sent and complete the transfer @param _to The address of the recipient (usually a "service provider") who will receive the Tratok. @param _value The amount of Tratok that needs to be transferred. @return Returns a boolean value to verify the transaction has succeeded or failed. */ function transfer(address to, uint value) returns(bool ok); /* This function will, conditional of being approved by the holder, send a determined amount of tokens to a specified address @param _from The address of the Tratok sender. @param _to The address of the Tratok recipient. @param _value The volume (amount of Tratok which will be sent). @return Returns a boolean value to verify the transaction has succeeded or failed. */ function transferFrom(address from, address to, uint value) returns(bool ok); /* This function approves the transaction and costs @param _spender The address of the account which is able to transfer the tokens @param _value The amount of wei to be approved for transfer @return Whether the approval was successful or not */ function approve(address spender, uint value) returns(bool ok); /* This function determines how many Tratok remain and how many can be spent. @param _owner The address of the account owning the Tratok tokens @param _spender The address of the account which is authorized to spend the Tratok tokens @return Amount of Tratok tokens which remain available and therefore, which can be spent */ function allowance(address owner, address spender) constant returns(uint); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /* *This is a basic contract held by one owner and prevents function execution if attempts to run are made by anyone other than the owner of the contract */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract StandardToken is ERC20, Ownable { using SafeMath for uint256; function transfer(address _to, uint256 _value) returns(bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns(uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns(bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; uint256 public totalSupply; } contract Tratok is StandardToken { function() { throw; } /* * The public variables of the token. Inclduing the name, the symbol and the number of decimals. */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; /* * Declaring the customized details of the token. The token will be called Tratok, with a total supply of 100 billion tokens. * It will feature five decimal places and have the symbol TRAT. */ function Tratok() { //we will create 100 Billion Coins and send them to the creating wallet. balances[msg.sender] = 10000000000000000; totalSupply = 10000000000000000; name = "Tratok"; decimals = 5; symbol = "TRAT"; } /* *Approve and enact the contract. * */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns(bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //If the call fails, result to "vanilla" approval. if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
the total supply of tokens@return Returns the total amount of Tratok tokens in existence. The amount remains capped at the pre-created 100 Billion.
contract ERC20 { uint public totalSupply; @param _owner The address of the wallet which needs to be queried for the amount of Tratok held. @return Returns the balance of Tratok tokens for the relevant address. function balanceOf(address who) constant returns(uint); The transfer function which takes the address of the recipient and the amount of Tratok needed to be sent and complete the transfer @param _to The address of the recipient (usually a "service provider") who will receive the Tratok. @param _value The amount of Tratok that needs to be transferred. @return Returns a boolean value to verify the transaction has succeeded or failed. function transfer(address to, uint value) returns(bool ok); This function will, conditional of being approved by the holder, send a determined amount of tokens to a specified address @param _from The address of the Tratok sender. @param _to The address of the Tratok recipient. @param _value The volume (amount of Tratok which will be sent). @return Returns a boolean value to verify the transaction has succeeded or failed. function transferFrom(address from, address to, uint value) returns(bool ok); This function approves the transaction and costs @param _spender The address of the account which is able to transfer the tokens @param _value The amount of wei to be approved for transfer @return Whether the approval was successful or not function approve(address spender, uint value) returns(bool ok); This function determines how many Tratok remain and how many can be spent. @param _owner The address of the account owning the Tratok tokens @param _spender The address of the account which is authorized to spend the Tratok tokens @return Amount of Tratok tokens which remain available and therefore, which can be spent function allowance(address owner, address spender) constant returns(uint); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); function totalSupply() constant returns(uint256 supply){} }
13,074,228
[ 1, 5787, 2078, 14467, 434, 2430, 2463, 2860, 326, 2078, 3844, 434, 840, 270, 601, 2430, 316, 15782, 18, 1021, 3844, 22632, 3523, 1845, 622, 326, 675, 17, 4824, 2130, 605, 737, 285, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 288, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 203, 203, 1377, 632, 891, 389, 8443, 1021, 1758, 434, 326, 9230, 1492, 4260, 358, 506, 23264, 364, 326, 3844, 434, 840, 270, 601, 15770, 18, 7010, 1377, 632, 2463, 2860, 326, 11013, 434, 840, 270, 601, 2430, 364, 326, 9368, 1758, 18, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 5381, 1135, 12, 11890, 1769, 203, 203, 4202, 1021, 7412, 445, 1492, 5530, 326, 1758, 434, 326, 8027, 471, 326, 3844, 434, 840, 270, 601, 3577, 358, 506, 3271, 471, 3912, 326, 7412, 203, 4202, 632, 891, 389, 869, 1021, 1758, 434, 326, 8027, 261, 407, 3452, 279, 315, 3278, 2893, 7923, 10354, 903, 6798, 326, 840, 270, 601, 18, 203, 4202, 632, 891, 389, 1132, 1021, 3844, 434, 840, 270, 601, 716, 4260, 358, 506, 906, 4193, 18, 203, 4202, 632, 2463, 2860, 279, 1250, 460, 358, 3929, 326, 2492, 711, 15784, 578, 2535, 18, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 13, 1135, 12, 6430, 1529, 1769, 203, 203, 4202, 1220, 445, 903, 16, 11139, 434, 3832, 20412, 635, 326, 10438, 16, 1366, 279, 11383, 3844, 434, 2430, 358, 279, 1269, 1758, 203, 4202, 632, 891, 389, 2080, 1021, 1758, 434, 326, 840, 270, 601, 5793, 18, 203, 4202, 632, 891, 389, 869, 1021, 1758, 434, 326, 840, 270, 601, 8027, 18, 203, 4202, 632, 891, 389, 1132, 1021, 3940, 261, 8949, 434, 840, 270, 601, 1492, 903, 506, 3271, 2934, 203, 4202, 2 ]
// 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 Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271Upgradeable { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // 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 "../../utils/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.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-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; /** * @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 "../../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; 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 "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] 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; /** * @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 "../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; /** * @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; import "./ECDSAUpgradeable.sol"; import "../AddressUpgradeable.sol"; import "../../interfaces/IERC1271Upgradeable.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureCheckerUpgradeable { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature); if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector); } } // 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.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.9; /// @title INiftyForge721 /// @author Simon Fremaux (@dievardump) interface INiftyForge721 { struct ModuleInit { address module; bool enabled; bool minter; } /// @notice totalSupply access function totalSupply() external view returns (uint256); /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() external view returns (bool); /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external; /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory tokenIds); /// @notice Mint `tokenId` to to` with `uri` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify _maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify _maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory); /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param canModuleMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool canModuleMint ) external; /// @dev Allows owner to enable a module /// @param module to enable /// @param canModuleMint if the module has to be given the minter role function enableModule(address module, bool canModuleMint) external; /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external; /// @notice function that returns a string that can be used to render the current token /// @param tokenId tokenId /// @return the URI to render token function renderTokenURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoles.sol'; import './ERC721WithRoyalties.sol'; import './ERC721WithPermit.sol'; import './ERC721WithMutableURI.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / URIStorage / Royalties /// This contract does not use ERC721enumerable because Enumerable adds quite some /// gas to minting costs and I am trying to make this cheap for creators. /// Also, since all NiftyForge contracts will be fully indexed in TheGraph it will easily /// Be possible to get tokenIds of an owner off-chain, before passing them to a contract /// which can verify ownership at the processing time /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721BurnableUpgradeable, ERC721URIStorageUpgradeable, ERC721WithRoles, ERC721WithRoyalties, ERC721WithPermit, ERC721WithMutableURI { bytes32 public constant ROLE_EDITOR = keccak256('EDITOR'); bytes32 public constant ROLE_MINTER = keccak256('MINTER'); // base token uri string public baseURI; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual { require(canMint(minter), '!NOT_MINTER!'); _; } /// @notice only editor modifier onlyEditor(address sender) virtual override { require(canEdit(sender), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Full_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal { __ERC721Ownable_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); __ERC721WithPermit_init(name_); } // receive() external payable {} /// @notice This is a generic function that allows this contract's owner to withdraw /// any balance / ERC20 / ERC721 / ERC1155 it can have /// this contract has no payable nor receive function so it should not get any nativ token /// but this could save some ERC20, 721 or 1155 /// @param token the token to withdraw from. address(0) means native chain token /// @param amount the amount to withdraw if native token, erc20 or erc1155 - must be 0 for ERC721 /// @param tokenId the tokenId to withdraw for ERC1155 and ERC721 function withdraw( address token, uint256 amount, uint256 tokenId ) external onlyOwner { if (token == address(0)) { require( amount == 0 || address(this).balance >= amount, '!WRONG_VALUE!' ); (bool success, ) = msg.sender.call{value: amount}(''); require(success, '!TRANSFER_FAILED!'); } else { // if token is ERC1155 if ( IERC165Upgradeable(token).supportsInterface( type(IERC1155Upgradeable).interfaceId ) ) { IERC1155Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, amount, '' ); } else if ( IERC165Upgradeable(token).supportsInterface( type(IERC721Upgradeable).interfaceId ) ) { //else if ERC721 IERC721Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, '' ); } else { // we consider it's an ERC20 require( IERC20Upgradeable(token).transfer(msg.sender, amount), '!TRANSFER_FAILED!' ); } } } /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // all moved here to have less "jumps" when checking an interface return interfaceId == type(IERC721WithMutableURI).interfaceId || interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId || interfaceId == type(IFoundationSecondarySales).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721Upgradeable, ERC721Ownable) returns (bool) { return super.isApprovedForAll(owner_, operator); } /// @inheritdoc ERC721URIStorageUpgradeable function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canEdit(address user) public view virtual returns (bool) { return isEditor(user) || owner() == user; } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canMint(address user) public view virtual returns (bool) { return isMinter(user) || canEdit(user); } /// @notice Helper to know if an address is editor /// @param user the address to check function isEditor(address user) public view returns (bool) { return hasRole(ROLE_EDITOR, user); } /// @notice Helper to know if an address is minter /// @param user the address to check function isMinter(address user) public view returns (bool) { return hasRole(ROLE_MINTER, user); } /// @notice Allows to get approved using a permit and transfer in the same call /// @dev this supposes that the permit is for msg.sender /// @param from current owner /// @param to recipient /// @param tokenId the token id /// @param _data optional data to add /// @param deadline the deadline for the permit to be used /// @param signature of permit function safeTransferFromWithPermit( address from, address to, uint256 tokenId, bytes memory _data, uint256 deadline, bytes memory signature ) external { // use the permit to get msg.sender approved permit(msg.sender, tokenId, deadline, signature); // do the transfer safeTransferFrom(from, to, tokenId, _data); } /// @notice Set the base token URI /// @dev only an editor can do that (account or module) /// @param baseURI_ the new base token uri used in tokenURI() function setBaseURI(string memory baseURI_) external onlyEditor(msg.sender) { baseURI = baseURI_; } /// @notice Set the base mutable meta URI for tokens /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function setBaseMutableURI(string memory baseMutableURI_) external onlyEditor(msg.sender) { _setBaseMutableURI(baseMutableURI_); } /// @notice Set the mutable URI for a token /// @dev Mutable URI work like tokenURI /// -> if there is a baseMutableURI and a mutableURI, concat baseMutableURI + mutableURI /// -> else if there is only mutableURI, return mutableURI //. -> else if there is only baseMutableURI, concat baseMutableURI + tokenId /// @dev only an editor (account or module) can call this /// @param tokenId the token to set the mutable URI for /// @param mutableURI_ the mutable URI function setMutableURI(uint256 tokenId, string memory mutableURI_) external onlyEditor(msg.sender) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); _setMutableURI(tokenId, mutableURI_); } /// @notice Helper for the owner to add new editors /// @dev needs to be owner /// @param users list of new editors function addEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for the owner to remove editors /// @dev needs to be owner /// @param users list of removed editors function removeEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to add new minter /// @dev needs to be owner /// @param users list of new minters function addMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to remove minters /// @dev needs to be owner /// @param users list of removed minters function removeMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Allows to change the default royalties recipient /// @dev an editor can call this /// @param recipient new default royalties recipient function setDefaultRoyaltiesRecipient(address recipient) external onlyEditor(msg.sender) { require(!hasPerTokenRoyalties(), '!PER_TOKEN_ROYALTIES!'); _setDefaultRoyaltiesRecipient(recipient); } /// @notice Allows a royalty recipient of a token to change their recipient address /// @dev only the current token royalty recipient can change the address /// @param tokenId the token to change the recipient for /// @param recipient new default royalties recipient function setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) external { require(hasPerTokenRoyalties(), '!CONTRACT_WIDE_ROYALTIES!'); (address currentRecipient, ) = _getTokenRoyalty(tokenId); require(msg.sender == currentRecipient, '!NOT_ALLOWED!'); _setTokenRoyaltiesRecipient(tokenId, recipient); } /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721WithPermit) { super._transfer(from, to, tokenId); } /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { // remove royalties _removeRoyalty(tokenId); // remove mutableURI _setMutableURI(tokenId, ''); // burn ERC721URIStorage super._burn(tokenId); } /// @inheritdoc ERC721Upgradeable function _baseURI() internal view virtual override returns (string memory) { return baseURI; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is OwnableUpgradeable, ERC721Upgradeable, BaseOpenSea { /// @notice modifier that allows higher level contracts to define /// editors that are not only the owner modifier onlyEditor(address sender) virtual { require(sender == owner(), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Ownable_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal initializer { __Ownable_init(); __ERC721_init_unchained(name_, symbol_); // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } // transferOwnership if needed if (address(0) != owner_) { transferOwnership(owner_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721Upgradeable function isApprovedForAll(address owner_, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea return super.isApprovedForAll(owner_, operator) || isOwnersOpenSeaProxy(owner_, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyEditor(msg.sender) { _setContractURI(contractURI_); } /// @notice Helper for the owner to set OpenSea's proxy (allowing or not gas-less trading) /// @dev needs to be owner /// @param osProxyRegistry new opensea proxy registry function setOpenSeaRegistry(address osProxyRegistry) external onlyEditor(msg.sender) { _setOpenSeaRegistry(osProxyRegistry); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import './IERC721WithMutableURI.sol'; /// @dev This is a contract used to add mutableURI to the contract /// @author Simon Fremaux (@dievardump) contract ERC721WithMutableURI is IERC721WithMutableURI, ERC721Upgradeable { using StringsUpgradeable for uint256; // base mutable meta URI string public baseMutableURI; mapping(uint256 => string) private _tokensMutableURIs; /// @notice See {ERC721WithMutableURI-mutableURI}. function mutableURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); string memory _tokenMutableURI = _tokensMutableURIs[tokenId]; string memory base = _baseMutableURI(); // If both are set, concatenate the baseURI and mutableURI (via abi.encodePacked). if (bytes(base).length > 0 && bytes(_tokenMutableURI).length > 0) { return string(abi.encodePacked(base, _tokenMutableURI)); } // If only token mutable URI is set if (bytes(_tokenMutableURI).length > 0) { return _tokenMutableURI; } // else return base + tokenId return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ''; } /// @dev helper to get the base for mutable meta /// @return the base for mutable meta uri function _baseMutableURI() internal view returns (string memory) { return baseMutableURI; } /// @dev Set the base mutable meta URI /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function _setBaseMutableURI(string memory baseMutableURI_) internal { baseMutableURI = baseMutableURI_; } /// @dev Set the mutable URI for a token /// @param tokenId the token id /// @param mutableURI_ the new mutableURI for tokenId function _setMutableURI(uint256 tokenId, string memory mutableURI_) internal { if (bytes(mutableURI_).length == 0) { if (bytes(_tokensMutableURIs[tokenId]).length > 0) { delete _tokensMutableURIs[tokenId]; } } else { _tokensMutableURIs[tokenId] = mutableURI_; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; /// @title ERC721WithPermit /// @author Simon Fremaux (@dievardump) /// @notice This implementation differs from what I can see everywhere else /// My take on Permits for NFTs is that the nonce should be linked to the tokens /// and not to an owner. /// Whenever a token is transfered, its nonce should increase. /// This allows to emit a lot of Permit (for sales for example) but ensure they /// will get invalidated after the token is transfered /// This also allows an owner to emit several Permit on different tokens /// and not have Permit to be used one after the other /// Example: /// An owner sign a Permit of sale on OpenSea and on Rarible at the same time /// Only the first one that will sell the item will be able to use the permit /// The nonce being incremented, this Permits won't be usable anymore abstract contract ERC721WithPermit is ERC721Upgradeable { bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)' ); bytes32 public DOMAIN_SEPARATOR; mapping(uint256 => uint256) private _nonces; // function to initialize the contract function __ERC721WithPermit_init(string memory name_) internal { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(name_)), keccak256(bytes('1')), block.chainid, address(this) ) ); } /// @notice Allows to retrieve current nonce for token /// @param tokenId token id /// @return current nonce function nonce(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); return _nonces[tokenId]; } function makePermitDigest( address spender, uint256 tokenId, uint256 nonce_, uint256 deadline ) public view returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash( DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, spender, tokenId, nonce_, deadline ) ) ); } /// @notice function to be called by anyone to approve `spender` using a Permit signature /// @dev Anyone can call this to approve `spender`, even a third-party /// @param spender the actor to approve /// @param tokenId the token id /// @param deadline the deadline for the permit to be used /// @param signature permit function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) public { require(deadline >= block.timestamp, '!PERMIT_DEADLINE_EXPIRED!'); // this will revert if token is burned address owner_ = ownerOf(tokenId); bytes32 digest = makePermitDigest( spender, tokenId, _nonces[tokenId], deadline ); (address recoveredAddress, ) = ECDSAUpgradeable.tryRecover( digest, signature ); require( ( // no need to check for recoveredAddress == 0 // because if it's 0, it won't work (recoveredAddress == owner_ || isApprovedForAll(owner_, recoveredAddress)) ) || // if owner is a contract, try to recover signature using SignatureChecker SignatureCheckerUpgradeable.isValidSignatureNow( owner_, digest, signature ), '!INVALID_PERMIT_SIGNATURE!' ); _approve(spender, tokenId); } /// @dev helper to easily increment a nonce for a given tokenId /// @param tokenId the tokenId to increment the nonce for function _incrementNonce(uint256 tokenId) internal { _nonces[tokenId]++; } /// @dev _transfer override to be able to increment the nonce /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // increment the permit nonce linked to this tokenId. // this will ensure that a Permit can not be used on a token // if it were to leave the owner's hands and come back later // this if saves 20k on the mint, which is already expensive enough if (from != address(0)) { _incrementNonce(tokenId); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; /// @title ERC721WithRoles /// @author Simon Fremaux (@dievardump) abstract contract ERC721WithRoles { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// @notice emitted when a role is given to a user /// @param role the granted role /// @param user the user that got a role granted event RoleGranted(bytes32 indexed role, address indexed user); /// @notice emitted when a role is givrevoked from a user /// @param role the revoked role /// @param user the user that got a role revoked event RoleRevoked(bytes32 indexed role, address indexed user); mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /// @notice Helper to know is an address has a role /// @param role the role to check /// @param user the address to check function hasRole(bytes32 role, address user) public view returns (bool) { return _roleMembers[role].contains(user); } /// @notice Helper to list all users in a role /// @return list of role members function listRole(bytes32 role) external view returns (address[] memory list) { uint256 count = _roleMembers[role].length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = _roleMembers[role].at(i); } } /// @notice internal helper to grant a role to a user /// @param role role to grant /// @param user to grant role to function _grantRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].add(user)) { emit RoleGranted(role, user); return true; } return false; } /// @notice Helper to revoke a role from a user /// @param role role to revoke /// @param user to revoke role from function _revokeRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].remove(user)) { emit RoleRevoked(role, user); return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '../Royalties/ERC2981/ERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; import '../Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is ERC2981Royalties, IRaribleSecondarySales, IFoundationSecondarySales { /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory recipients, uint256[] memory fees) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); fees = new uint256[](1); fees[0] = amount; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @dev This is the interface for NFT extension mutableURI /// @author Simon Fremaux (@dievardump) interface IERC721WithMutableURI { function mutableURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's /// gas-less trading and contractURI support contract BaseOpenSea { event NewContractURI(string contractURI); string private _contractURI; address private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Returns the current OS proxyRegistry address registered function proxyRegistry() public view returns (address) { return _proxyRegistry; } /// @notice Helper allowing OpenSea gas-less trading by verifying who's operator /// for owner /// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby /// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { address proxyRegistry_ = _proxyRegistry; // if we have a proxy registry if (proxyRegistry_ != address(0)) { // on ethereum mainnet or rinkeby use "ProxyRegistry" to // get owner's proxy if (block.chainid == 1 || block.chainid == 4) { return address(ProxyRegistry(proxyRegistry_).proxies(owner)) == operator; } else if (block.chainid == 137 || block.chainid == 80001) { // on Polygon and Mumbai just try with OpenSea's proxy contract // https://docs.opensea.io/docs/polygon-basic-integration return proxyRegistry_ == operator; } } return false; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; emit NewContractURI(contractURI_); } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = proxyRegistryAddress; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './IERC2981Royalties.sol'; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Royalties is IERC2981Royalties { struct RoyaltyData { address recipient; uint96 amount; } // this variable is set to true, whenever "contract wide" royalties are set // this can not be undone and this takes precedence to any other royalties already set. bool private _useContractRoyalties; // those are the "contract wide" royalties, used for collections that all pay royalties to // the same recipient, with the same value // once set, like any other royalties, it can not be modified RoyaltyData private _contractRoyalties; mapping(uint256 => RoyaltyData) private _royalties; function hasPerTokenRoyalties() public view returns (bool) { return !_useContractRoyalties; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { // get base values (receiver, royaltyAmount) = _getTokenRoyalty(tokenId); // calculate due amount if (royaltyAmount != 0) { royaltyAmount = (value * royaltyAmount) / 10000; } } /// @dev Sets token royalties /// @param id the token id fir which we register the royalties function _removeRoyalty(uint256 id) internal { delete _royalties[id]; } /// @dev Sets token royalties /// @param id the token id for which we register the royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setTokenRoyalty( uint256 id, address recipient, uint256 value ) internal { // you can't set per token royalties if using "contract wide" ones require( !_useContractRoyalties, '!ERC2981Royalties:ROYALTIES_CONTRACT_WIDE!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _royalties[id] = RoyaltyData(recipient, uint96(value)); } /// @dev Gets token royalties /// @param id the token id for which we check the royalties function _getTokenRoyalty(uint256 id) internal view virtual returns (address, uint256) { RoyaltyData memory data; if (_useContractRoyalties) { data = _contractRoyalties; } else { data = _royalties[id]; } return (data.recipient, uint256(data.amount)); } /// @dev set contract royalties; /// This can only be set once, because we are of the idea that royalties /// Amounts should never change after they have been set /// Once default values are set, it will be used for all royalties inquiries /// @param recipient the default royalties recipient /// @param value the default royalties value function _setDefaultRoyalties(address recipient, uint256 value) internal { require( _useContractRoyalties == false, '!ERC2981Royalties:DEFAULT_ALREADY_SET!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _useContractRoyalties = true; _contractRoyalties = RoyaltyData(recipient, uint96(value)); } /// @dev allows to set the default royalties recipient /// @param recipient the new recipient function _setDefaultRoyaltiesRecipient(address recipient) internal { _contractRoyalties.recipient = recipient; } /// @dev allows to set a tokenId royalties recipient /// @param tokenId the token Id /// @param recipient the new recipient function _setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) internal { _royalties[tokenId].recipient = recipient; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @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 _value - 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 value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IFoundationSecondarySales { /// @notice returns a list of royalties recipients and the amount /// @param tokenId the token Id to check for /// @return all the recipients and their basis points, for tokenId function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './Modules/INFModuleWithEvents.sol'; /// @title INiftyForgeBase /// @author Simon Fremaux (@dievardump) interface INiftyForgeModules { enum ModuleStatus { UNKNOWN, ENABLED, DISABLED } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view returns (address[] memory list, uint256[] memory status); /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external; /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol'; interface INFModule is IERC165Upgradeable { /// @notice Called by a Token Registry whenever the module is Attached /// @return if the attach worked function onAttach() external returns (bool); /// @notice Called by a Token Registry whenever the module is Enabled /// @return if the enabling worked function onEnable() external returns (bool); /// @notice Called by a Token Registry whenever the module is Disabled function onDisable() external; /// @notice returns an URI with information about the module /// @return the URI where to find information about the module function contractURI() external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleMutableURI is INFModule { function mutableURI(uint256 tokenId) external view returns (string memory); function mutableURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleRenderTokenURI is INFModule { function renderTokenURI(uint256 tokenId) external view returns (string memory); function renderTokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleTokenURI is INFModule { function tokenURI(uint256 tokenId) external view returns (string memory); function tokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithEvents is INFModule { enum Events { MINT, TRANSFER, BURN } /// @dev callback received from a contract when an event happens /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function onEvent( Events eventType, uint256 tokenId, address from, address to ) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithRoyalties is INFModule { /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(uint256 tokenId) external view returns (address recipient, uint256 basisPoint); /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param registry registry to check id of /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(address registry, uint256 tokenId) external view returns (address recipient, uint256 basisPoint); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; import './Modules/INFModule.sol'; import './Modules/INFModuleWithEvents.sol'; import './INiftyForgeModules.sol'; /// @title NiftyForgeBase /// @author Simon Fremaux (@dievardump) /// @notice These modules can be attached to a contract and enabled/disabled later /// They can be used to mint elements (need Minter Role) but also can listen /// To events like MINT, TRANSFER and BURN /// /// To module developers: /// Remember cross contract calls have a high cost, and reads too. /// Do not abuse of Events and only use them if there is a high value to it /// Gas is not cheap, always think of users first. contract NiftyForgeModules is INiftyForgeModules { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // event emitted whenever a module status changed event ModuleChanged(address module); // 3 types of events Mint, Transfer and Burn EnumerableSetUpgradeable.AddressSet[3] private _listeners; // modules list // should create a module role instead? EnumerableSetUpgradeable.AddressSet internal modules; // modules status mapping(address => ModuleStatus) public modulesStatus; modifier onlyEnabledModule() { require( modulesStatus[msg.sender] == ModuleStatus.ENABLED, '!MODULE_NOT_ENABLED!' ); _; } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view override returns (address[] memory list, uint256[] memory status) { uint256 count = modules.length(); list = new address[](count); status = new uint256[](count); for (uint256 i; i < count; i++) { list[i] = modules.at(i); status[i] = uint256(modulesStatus[list[i]]); } } /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].add(msg.sender); } /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].remove(msg.sender); } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default function _attachModule(address module, bool enabled) internal { require( modulesStatus[module] == ModuleStatus.UNKNOWN, '!ALREADY_ATTACHED!' ); // add to modules list modules.add(module); // tell the module it's attached // making sure module can be attached to this contract require(INFModule(module).onAttach(), '!ATTACH_FAILED!'); if (enabled) { _enableModule(module); } else { _disableModule(module, true); } } /// @dev Allows owner to enable a module (needs to be disabled) /// @param module to enable function _enableModule(address module) internal { require( modulesStatus[module] != ModuleStatus.ENABLED, '!NOT_DISABLED!' ); modulesStatus[module] = ModuleStatus.ENABLED; // making sure module can be enabled on this contract require(INFModule(module).onEnable(), '!ENABLING_FAILED!'); emit ModuleChanged(module); } /// @dev Disables a module /// @param module the module to disable /// @param keepListeners a boolean to know if the module can still listen to events /// meaning the module can not interact with the contract anymore but is still working /// for example: a module that transfers an ERC20 to people Minting function _disableModule(address module, bool keepListeners) internal virtual { require( modulesStatus[module] != ModuleStatus.DISABLED, '!NOT_ENABLED!' ); modulesStatus[module] = ModuleStatus.DISABLED; // we do a try catch without checking return or error here // because owners should be able to disable a module any time without the module being ok // with it or not try INFModule(module).onDisable() {} catch {} // remove all listeners if not explicitely asked to keep them if (!keepListeners) { _listeners[uint256(INFModuleWithEvents.Events.MINT)].remove(module); _listeners[uint256(INFModuleWithEvents.Events.TRANSFER)].remove( module ); _listeners[uint256(INFModuleWithEvents.Events.BURN)].remove(module); } emit ModuleChanged(module); } /// @dev fire events to listeners /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function _fireEvent( INFModuleWithEvents.Events eventType, uint256 tokenId, address from, address to ) internal { EnumerableSetUpgradeable.AddressSet storage listeners = _listeners[ uint256(eventType) ]; uint256 length = listeners.length(); for (uint256 i; i < length; i++) { INFModuleWithEvents(listeners.at(i)).onEvent( eventType, tokenId, from, to ); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './NFT/ERC721Helpers/ERC721Full.sol'; import './NiftyForge/Modules/INFModuleWithEvents.sol'; import './NiftyForge/Modules/INFModuleTokenURI.sol'; import './NiftyForge/Modules/INFModuleRenderTokenURI.sol'; import './NiftyForge/Modules/INFModuleWithRoyalties.sol'; import './NiftyForge/Modules/INFModuleMutableURI.sol'; import './NiftyForge/NiftyForgeModules.sol'; import './INiftyForge721.sol'; /// @title NiftyForge721 /// @author Simon Fremaux (@dievardump) contract NiftyForge721 is INiftyForge721, NiftyForgeModules, ERC721Full { /// @dev This contains the last token id that was created uint256 public lastTokenId; uint256 public totalSupply; bool private _mintingOpenToAll; // this can be set only once by the owner of the contract // this is used to ensure a max token creation that can be used // for example when people create a series of XX elements // since this contract works with "Minters", it is good to // be able to set in it that there is a max number of elements // and that this can not change uint256 public maxTokenId; mapping(uint256 => address) public tokenIdToModule; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual override { require(isMintingOpenToAll() || canMint(minter), '!NOT_MINTER!'); _; } /// @notice this is the constructor of the contract, called at the time of creation /// Although it uses what are called upgradeable contracts, this is only to /// be able to make deployment cheap using a Proxy but NiftyForge contracts /// ARE NOT UPGRADEABLE => the proxy used is not an upgradeable proxy, the implementation is immutable /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership /// @param modulesInit_ modules to add / enable directly at creation /// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties" /// @param contractRoyaltiesValue the value, modules to add / enable directly at creation function initialize( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_, ModuleInit[] memory modulesInit_, address contractRoyaltiesRecipient, uint256 contractRoyaltiesValue ) external initializer { __ERC721Full_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); for (uint256 i; i < modulesInit_.length; i++) { _attachModule(modulesInit_[i].module, modulesInit_[i].enabled); if (modulesInit_[i].enabled && modulesInit_[i].minter) { _grantRole(ROLE_MINTER, modulesInit_[i].module); } } // here, if contractRoyaltiesRecipient is not address(0) but // contractRoyaltiesValue is 0, this will mean that this contract will // NEVER have royalties, because whenever default royalties are set, it is // always used for every tokens. if ( contractRoyaltiesRecipient != address(0) || contractRoyaltiesValue != 0 ) { _setDefaultRoyalties( contractRoyaltiesRecipient, contractRoyaltiesValue ); } } /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() public view override returns (bool) { return _mintingOpenToAll; } /// @notice returns a tokenURI /// @dev This function will first check if there is a tokenURI registered for this token in the contract /// if not it will check if the token comes from a Module, and if yes, try to get the tokenURI from it /// /// @param tokenId a parameter just like in doxygen (must be followed by parameter name) /// @return uri the tokenURI /// @inheritdoc ERC721Upgradeable function tokenURI(uint256 tokenId) public view virtual override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleTokenURI).interfaceId ); if (support) { uri = INFModuleTokenURI(module).tokenURI(tokenId); } // if uri not set, get it with the normal tokenURI if (bytes(uri).length == 0) { uri = super.tokenURI(tokenId); } } /// @notice function that returns a string that can be used to render the current token /// this can be an URL but also any other data uri /// This is something that I would like to present as an EIP later to allow dynamique /// render URL /// @param tokenId tokenId /// @return uri the URI to render token function renderTokenURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // Try to get the URI from the module that might have created this token (bool support, address module) = _moduleSupports( tokenId, type(INFModuleRenderTokenURI).interfaceId ); if (support) { uri = INFModuleRenderTokenURI(module).renderTokenURI(tokenId); } } /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external override onlyEditor(msg.sender) { _mintingOpenToAll = isOpen; } /// @notice allows owner to set maxTokenId /// @dev be careful, this is a one time call function. /// When set, the maxTokenId can not be reverted nor changed /// @param maxTokenId_ the max token id possible function setMaxTokenId(uint256 maxTokenId_) external onlyEditor(msg.sender) { require(maxTokenId == 0, '!MAX_TOKEN_ALREADY_SET!'); maxTokenId = maxTokenId_; } /// @notice function that returns a string that can be used to add metadata on top of what is in tokenURI /// This function has been added because sometimes, we want some metadata to be completly immutable /// But to have others that aren't (for example if a token is linked to a physical token, and the physical /// token state can change over time) /// This way we can reflect those changes without risking breaking the base meta (tokenURI) /// @param tokenId tokenId /// @return uri the URI where mutable can be found function mutableURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleMutableURI).interfaceId ); if (support) { uri = INFModuleMutableURI(module).mutableURI(tokenId); } // if uri not set, get it with the normal mutableURI if (bytes(uri).length == 0) { uri = super.mutableURI(tokenId); } } /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256 tokenId) { tokenId = lastTokenId + 1; lastTokenId = mint( to, uri, tokenId, feeRecipient, feeAmount, transferTo ); } /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory tokenIds) { require( to.length == uris.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 tokenId = lastTokenId; tokenIds = new uint256[](to.length); // verify that we don't overflow // done here instead of in _mint so we do one read // instead of to.length _verifyMaxTokenId(tokenId + to.length); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { tokenId++; _mint( to[i], uris[i], tokenId, feeRecipients[i], feeAmounts[i], isModule ); tokenIds[i] = tokenId; } // setting lastTokenId after will ensure that any reEntrancy will fail // to mint, because the minting will throw with a duplicate id lastTokenId = tokenId; } /// @notice Mint `tokenId` to to` with `uri` and transfer to transferTo if not null /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId_ token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256) { // minting will throw if the tokenId_ already exists // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(tokenId_); _mint( to, uri, tokenId_, feeRecipient, feeAmount, modulesStatus[msg.sender] == ModuleStatus.ENABLED ); if (transferTo != address(0)) { _transfer(to, transferTo, tokenId_); } return tokenId_; } /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory) { // minting will throw if any tokenIds[i] already exists require( to.length == uris.length && to.length == tokenIds.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 highestId; for (uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } } // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(highestId); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } _mint( to[i], uris[i], tokenIds[i], feeRecipients[i], feeAmounts[i], isModule ); } return tokenIds; } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param moduleCanMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool moduleCanMint ) external override onlyEditor(msg.sender) { // give the minter role if enabled and moduleCanMint if (moduleCanMint && enabled) { _grantRole(ROLE_MINTER, module); } _attachModule(module, enabled); } /// @dev Allows owner to enable a module /// @param module to enable /// @param moduleCanMint if the module has to be given the minter role function enableModule(address module, bool moduleCanMint) external override onlyEditor(msg.sender) { // give the minter role if moduleCanMint if (moduleCanMint) { _grantRole(ROLE_MINTER, module); } _enableModule(module); } /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external override onlyEditor(msg.sender) { _disableModule(module, keepListeners); } /// @dev Internal mint function /// @param to token recipient /// @param uri token uri /// @param tokenId token Id /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amounts. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param isModule if the minter is a module function _mint( address to, string memory uri, uint256 tokenId, address feeRecipient, uint256 feeAmount, bool isModule ) internal { _safeMint(to, tokenId, ''); if (bytes(uri).length > 0) { _setTokenURI(tokenId, uri); } if (feeAmount > 0) { _setTokenRoyalty(tokenId, feeRecipient, feeAmount); } if (isModule) { tokenIdToModule[tokenId] = msg.sender; } } // here we override _mint, _transfer and _burn because we want the event to be fired // only after the action is done // else we would have done that in _beforeTokenTransfer /// @dev _mint override to be able to fire events /// @inheritdoc ERC721Upgradeable function _mint(address to, uint256 tokenId) internal virtual override { super._mint(to, tokenId); totalSupply++; _fireEvent(INFModuleWithEvents.Events.MINT, tokenId, address(0), to); } /// @dev _transfer override to be able to fire events /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); if (to == address(0xdEaD)) { _fireEvent(INFModuleWithEvents.Events.BURN, tokenId, from, to); } else { _fireEvent(INFModuleWithEvents.Events.TRANSFER, tokenId, from, to); } } /// @dev _burn override to be able to fire event /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override { address owner_ = ownerOf(tokenId); super._burn(tokenId); totalSupply--; _fireEvent( INFModuleWithEvents.Events.BURN, tokenId, owner_, address(0) ); } function _disableModule(address module, bool keepListeners) internal override { // always revoke the minter role when disabling a module _revokeRole(ROLE_MINTER, module); super._disableModule(module, keepListeners); } /// @dev Verifies that we do not create more token ids than the max if set /// @param tokenId the tokenId to verify function _verifyMaxTokenId(uint256 tokenId) internal view { uint256 maxTokenId_ = maxTokenId; require(maxTokenId_ == 0 || tokenId <= maxTokenId_, '!MAX_TOKEN_ID!'); } /// @dev Gets token royalties taking modules into account /// @param tokenId the token id for which we check the royalties function _getTokenRoyalty(uint256 tokenId) internal view override returns (address royaltyRecipient, uint256 royaltyAmount) { (royaltyRecipient, royaltyAmount) = super._getTokenRoyalty(tokenId); // if there are no royalties set either contract wide or per token if (royaltyAmount == 0) { // try to see if the token was created by a module that manages royalties (bool support, address module) = _moduleSupports( tokenId, type(INFModuleWithRoyalties).interfaceId ); if (support) { (royaltyRecipient, royaltyAmount) = INFModuleWithRoyalties( module ).royaltyInfo(tokenId); } } } function _moduleSupports(uint256 tokenId, bytes4 interfaceId) internal view returns (bool support, address module) { module = tokenIdToModule[tokenId]; support = module != address(0) && IERC165Upgradeable(module).supportsInterface(interfaceId); } }
@title ERC721WithRoles @author Simon Fremaux (@dievardump)
abstract contract ERC721WithRoles { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; event RoleGranted(bytes32 indexed role, address indexed user); event RoleRevoked(bytes32 indexed role, address indexed user); mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; pragma solidity ^0.8.9; function hasRole(bytes32 role, address user) public view returns (bool) { return _roleMembers[role].contains(user); } function listRole(bytes32 role) external view returns (address[] memory list) { uint256 count = _roleMembers[role].length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = _roleMembers[role].at(i); } } function listRole(bytes32 role) external view returns (address[] memory list) { uint256 count = _roleMembers[role].length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = _roleMembers[role].at(i); } } function _grantRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].add(user)) { emit RoleGranted(role, user); return true; } return false; } function _grantRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].add(user)) { emit RoleGranted(role, user); return true; } return false; } function _revokeRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].remove(user)) { emit RoleRevoked(role, user); return true; } return false; } function _revokeRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].remove(user)) { emit RoleRevoked(role, user); return true; } return false; } }
1,626,357
[ 1, 654, 39, 27, 5340, 1190, 6898, 225, 9587, 265, 478, 266, 2540, 2616, 261, 36, 72, 1385, 90, 1060, 2801, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 1190, 6898, 288, 203, 565, 1450, 6057, 25121, 694, 10784, 429, 364, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 31, 203, 203, 565, 871, 6204, 14570, 12, 3890, 1578, 8808, 2478, 16, 1758, 8808, 729, 1769, 203, 203, 565, 871, 6204, 10070, 14276, 12, 3890, 1578, 8808, 2478, 16, 1758, 8808, 729, 1769, 203, 203, 565, 2874, 12, 3890, 1578, 516, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 13, 203, 3639, 3238, 389, 4615, 6918, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 565, 445, 28335, 12, 3890, 1578, 2478, 16, 1758, 729, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 4615, 6918, 63, 4615, 8009, 12298, 12, 1355, 1769, 203, 565, 289, 203, 203, 565, 445, 666, 2996, 12, 3890, 1578, 2478, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8526, 3778, 666, 13, 203, 565, 288, 203, 3639, 2254, 5034, 1056, 273, 389, 4615, 6918, 63, 4615, 8009, 2469, 5621, 203, 3639, 666, 273, 394, 1758, 8526, 12, 1883, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 1056, 31, 277, 27245, 288, 203, 5411, 666, 63, 77, 65, 273, 389, 4615, 6918, 63, 4615, 8009, 270, 12, 77, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 666, 2996, 12, 3890, 1578, 2478, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8526, 3778, 666, 13, 203, 565, 288, 203, 3639, 2 ]
./full_match/1/0x5D30dCD259651d44978F20CBD88AaEd3b7Eee9cA/sources/src/periphery/StrategyExecutor.sol
useful when the previous function calls adds back strategy token to rebalance
function _run( BaseStrategy strategy, uint256 maxBentoBoxAmountIncreaseInBips, uint256 maxBentoBoxChangeAmountInBips, bytes[] calldata calls, bool postRebalanceEnabled ) private { IBentoBoxV1 bentoBox = strategy.bentoBox(); IERC20 strategyToken = strategy.strategyToken(); uint128 totals = bentoBox.totals(strategyToken).elastic; uint256 maxBalance = totals + ((totals * BIPS) / maxBentoBoxAmountIncreaseInBips); uint256 maxChangeAmount = (maxBalance * maxBentoBoxChangeAmountInBips) / BIPS; strategy.safeHarvest(maxBalance, true, maxChangeAmount, false); for (uint256 i = 0; i < calls.length; i++) { address(strategy).functionCall(calls[i], "call failed"); } if (postRebalanceEnabled) { strategy.safeHarvest(maxBalance, true, 0, false); } lastExecution[strategy] = uint64(block.timestamp); }
3,045,020
[ 1, 1202, 2706, 1347, 326, 2416, 445, 4097, 4831, 1473, 6252, 1147, 358, 283, 12296, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2681, 12, 203, 3639, 3360, 4525, 6252, 16, 203, 3639, 2254, 5034, 943, 38, 29565, 3514, 6275, 382, 11908, 382, 38, 7146, 16, 203, 3639, 2254, 5034, 943, 38, 29565, 3514, 3043, 6275, 382, 38, 7146, 16, 203, 3639, 1731, 8526, 745, 892, 4097, 16, 203, 3639, 1426, 1603, 426, 12296, 1526, 203, 565, 262, 3238, 288, 203, 3639, 23450, 29565, 3514, 58, 21, 324, 29565, 3514, 273, 6252, 18, 70, 29565, 3514, 5621, 203, 3639, 467, 654, 39, 3462, 6252, 1345, 273, 6252, 18, 14914, 1345, 5621, 203, 3639, 2254, 10392, 19489, 273, 324, 29565, 3514, 18, 3307, 1031, 12, 14914, 1345, 2934, 22318, 31, 203, 3639, 2254, 5034, 943, 13937, 273, 19489, 397, 14015, 3307, 1031, 380, 605, 2579, 55, 13, 342, 943, 38, 29565, 3514, 6275, 382, 11908, 382, 38, 7146, 1769, 203, 3639, 2254, 5034, 943, 3043, 6275, 273, 261, 1896, 13937, 380, 943, 38, 29565, 3514, 3043, 6275, 382, 38, 7146, 13, 342, 605, 2579, 55, 31, 203, 3639, 6252, 18, 4626, 44, 297, 26923, 12, 1896, 13937, 16, 638, 16, 943, 3043, 6275, 16, 629, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4097, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 12, 14914, 2934, 915, 1477, 12, 12550, 63, 77, 6487, 315, 1991, 2535, 8863, 203, 3639, 289, 203, 203, 3639, 309, 261, 2767, 426, 12296, 1526, 13, 288, 203, 5411, 6252, 18, 4626, 44, 297, 26923, 12, 1896, 13937, 16, 638, 16, 374, 16, 629, 1769, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // IERC721 is the ERC721 interface that we´ll use to make Maniac´s NFT ERC721 import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // IERC721Receiver must be implemented to accept safe transfers // It is included on the ERC721 standard import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // ERC165 is used to declare interface support for IERC721 import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // SafeMath will be used for every math operation import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // Address will provide functions such as .isContract verification import "@openzeppelin/contracts/utils/Address.sol"; // The "is" keywork is used to inherit functions and keywords from external contracts. // In this case "Artwork" inherits from the "IERC721" and "ERC165" contracts. // Interface that will ingerits to the contracts will be looking for a problem... contract Artwork is ERC165, IERC721 { // Uses OpenZeppelin´s SafeMath library to perform arithmetic operations safely. using SafeMath for uint256; // Use OpenZeppelin´s address library to validate whether an address is // is a contract or not using Address for address; // 161 take a reference to the three first numbers // from number phi (1,61803) uint256 constant artDigits = 161; uint256 constant artModuls = 161**artDigits; //ERC165 indentifier to ERC721 got from // bytes4(keccak256("onERC721Received(address,adress,uint256,bytes)")) bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; struct Maniac { string name; uint art; } // Creates an empty array of Artwork structs Artwork[] public NFTmaniac; // Mapping from id of Artwork to it´s owner´s address mapping(uint256 => address) public NFTmaniacToOwner; // Mapping from owner´s address to number of owned token mapping(address => uint256) public ownerNFTmaniacCount; // Mapping to validate that art is not already taken mapping(uint256 => bool) public artNFTmaniacExists; // Mapping from Token ID to approved address mapping(uint256 => address) NFTmaniacApprovals; // Owner to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; // Check if Artwork is unique and does not exist yet modifier isUnique(uint256 _art) { require( !artArtworkExists[_art], "Nft with such art already exist." ); _; } // Creates a random Artwork from string (name) function createRandomArtwork(string memory _name) public { uint256 randArt = generateRandomArt(_name, msg.sender); _createArtwork(_name, randArt); } // Generates random ART from string (name) and address of the owner (creator) function generateRandomArt(string memory _str, address _owner) public pure returns ( // Function marked as "pure" promise not to read from or modify the state uint256 ) { // Generates random uint from string (name) + address (owner) uint256 rand = uint256(keccak256(abi.encodePacked(_str))) + uint256(uint160(address(_owner))); rand = rand.mod(artModulus); return rand; } // Internal function to create a random Artwork from string (name) and Art function _createArtwork(string memory _name, uint256 _art) internal // The "internal" keyword means this fucntion is only visible // Within this contract and contracts that derive this contract // "isUnique" is a function modifier that checks if the Artwork already exists isUnique(_art) { // Adds Artwork to array of Artworks and get ID NFTmaniac.pus(Artwork(_name, _art)); uint256 id = (NFTmaniac.length.sub(1)); // Mark as existent NFTmaniac name and art artArtworkExists[_art] = true; // Checks that Artwork owner is the same as current user assert(NFTmaniacToOwner[id] == address(0)); // Maps the Artwork to the owner NFTmaniacToOwner[id] = msg.sender; ownerArtworkCount[msg.sender] = ownerArtworkCount[msg.sender].add( 1 ); } // Returns array of Artwork found by owner function getArtworkByOwner(address _owner) public view returns ( // Functions marked as "view" promise not to modify state uint256[] memory ) { // Uses the "memory" storage location to store values only for the // lifecycle of this function call uint256 [] memory result = new uint256[](ownerArtworkCount[_owner]); uint256 counter = 0; for (uint256 i = 0; i < NFTmaniac.length; i++) { if (NFTmaniacToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } // Returns count if Artwork by address function balanceOf(address _owner) public override view returns (uint256 _balance) { return ownerArtworkCount[_owner]; } // Returns owner of the Artwork found by id function ownerOf(uint256 _NFTmaniacId) public override view returns (uint256 _balance) { address owner = NFTmaniacToOwner[_NFTmaniacId]; require(owner != address(0), "Invalid Artwork ID"); return owner; } // Safely transfer the ownership of a given tojen ID to another address // If the target address is a contract, it must implement "onERC721Received", // wich is called upon a dafe transfer, and return the magic value // "bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))"; // otherwise, the transfer is reverted. function safeTransferFrom ( address from, address to, uint256 NFTmaniacId ) public override { // solium-disable-next-line arg-overflow safeTranferFrom(from, to, NFTmaniacId, ""); } // Transfers Artwork and ownership of the other address function transferFrom( address _from, address _to, uint256 _NFTmaniacId ) public override { require(_from != address(0) && _to != address(0), "Invalid address."); require(_exists(_NFTmaniacId), "Artwork does not exist."); require(_from != _to, "Cannot transfer to the same address.") ; require( _isApproveOrOwner(msg.sender, _NFTmaniacId), "Address is not approved." ); ownerArtworkCount[_to] = ownerArtworkCount[_to].add(1); ownerArtworkCount[_from] = ownerArtworkCount[_from].sub(1); NFTmaniacToOwner[_NFTmaniacId] = _to; // Emits event defined in the imported IERC721 contract emit Transfer(_from, _to, _NFTmaniacId); _clearApproval(_to, NFTmaniacId); } // Checks if Artwork exists function _exists(uint256 NFTmaniacId) internal view returns (bool) { address owner = NFTmaniacToOwner[NFTmaniacId]; return owner != address(0); } // Checks if address is owner or is approved to transfer Artwork function _isApprovedOrOwner(address spender, uint256 NFTmaniacId) internal view returns(bool) { address owner = NFTmaniacToOwner[NFTmaniacId]; // Disable solium check because of // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(NFTmaniacId) == spender || isApprovedForAll(owner, spender)); } /** - Private function to clear current approval of a given token ID - Reverts if the given address is not indeed the owner of the token */ function _clearApproval(address owner, uint256 _avatheeerId) private { require( NFTmaniacToOwner[_NFTmaniacId] == owner, "Must be NFTmaniac owner." ); require(_exists(_NFTmaniacId), "Artwork does not exist,"); if(NFTmaniacApprovals[_NFTmaniacId] != address(0)) { NFTmaniacApprovals[_NFTmaniacId] = address(0); } } // Approves other address to transfer awnership of Artwork function approve(address _to, uin256 _NFTmaniacId) public override { require( msg.sender == NFTmaniacToOwner[_NFTmaniacId], "Must be the Artwork owner." ); NFTmaniacApprovals[_NFTmaniacId] = _to; emit Approval(msg.sender, _to, _NFTmaniacId); } // Returns approved address for specific Artwork function getApproved(uint256 _NFTmaniacId) public override view returns (address operator) { require(_exists(_NFTmaniacId), "Artwork does not exist."); return NFTmaniacApprovals[_NFTmaniacId]; } // Sets or unsets the approval of a given operator // An operator is allowed to transfer all tokens of the sender on their behalf function setApprovalForAll(address to, bool approved) public override { require(to != msg.sender, "Cannor approve own address"); operatorApprovals[mag.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } // Tells whether am operator is approved by a given owner function isApprovedForAll(address owner, address operator) public override view returns (bool) { return operatorApprovals[owner][operator]; } /** * Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * otherwise, the transfer is reverted. */ function safeTransferFrom( address from, address to, uint256 NFTmaniacId, bytes memory _data ) public override { transferFrom(from, to, NFTmaniacId); require( _checkOnERC721Received(from, to, NFTmaniacId, _data), "Must implement on ERC721Received." ); } //Internal function to invoke `onERC721Received` on a target address // The call is not executed if the target address is not a contract function _checkOnERC721Received( address from, address to, uint256 NFTmaniacId, bytes memory _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, NFTmaniacId, _data ); return (retval == _ERC721_RECEIVED); } // Burns a Artwork - destroys Token completely // The `external` function modifier means this function is // part of the contract interface and other contracts can call it function burn(uint256 _NFTmaniacId) external { require(msg.sender != address(0), "Invalid address."); require(_exists(_NFTmaniacId), "Artwork does not exist."); require( _isApprovedOrOwner(msg.sender, _NFTmaniacId), "Address is not approved." ); ownerArtworkCount[msg.sender] = ownerArtworkCount[msg.sender].sub( 1 ); NFTmaniacToOwner[_NFTmaniacId] = address(0); } // Takes ownership of Arwork - only for approved users function takeOwnership(uint256 _NFTmaniacId) public { require( _isApprovedOrOwner(msg.sender, _NFTmaniacId), "Address is not approved." ); address owner = ownerOf(_NFTmaniacId); transferFrom(owner, msg.sender, _NFTmaniacId); } // Is estimated than the ERC721SmartContractManiac finished here, by the way, maybe in the future it will change some things in the contract }
Returns approved address for specific Artwork
function getApproved(uint256 _NFTmaniacId) public override view returns (address operator) { require(_exists(_NFTmaniacId), "Artwork does not exist."); return NFTmaniacApprovals[_NFTmaniacId]; }
12,536,977
[ 1, 1356, 20412, 1758, 364, 2923, 9042, 1252, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 31639, 12, 11890, 5034, 389, 50, 4464, 4728, 77, 1077, 548, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 3726, 13, 203, 565, 288, 203, 3639, 2583, 24899, 1808, 24899, 50, 4464, 4728, 77, 1077, 548, 3631, 315, 4411, 1252, 1552, 486, 1005, 1199, 1769, 203, 3639, 327, 423, 4464, 4728, 77, 1077, 12053, 4524, 63, 67, 50, 4464, 4728, 77, 1077, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2CF4abb70f2732B522DC59cb644b560eE2BF43e6/sources/foraging-contracts/Nom.sol
Base reward per block of time.
uint256 _baseReward;
3,029,787
[ 1, 2171, 19890, 1534, 1203, 434, 813, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 389, 1969, 17631, 1060, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/100/0xFDC429d598676580814563B405F6c866DEbfBeBc/sources/BattleMtnData.sol
array featuring all connections.
Node[65] ValidPaths;
16,669,093
[ 1, 1126, 11002, 4017, 777, 5921, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2029, 63, 9222, 65, 2364, 4466, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity =0.4.24; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 6; // 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 */ constructor( uint256 _initialSupply, string _tokenName, string _tokenSymbol, address _initAddr ) public { totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[_initAddr] = totalSupply; // Give the creator all initial tokens name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes emit Transfer(address(0), _initAddr, totalSupply); } /** * 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] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _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] + 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` 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) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); 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; 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) 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; } }
* Constructor function Initializes contract with initial supply tokens to the creator of the contract/
) public { emit Transfer(address(0), _initAddr, totalSupply); }
1,447,697
[ 1, 6293, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 288, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 2738, 3178, 16, 2078, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at FtmScan.com on 2021-10-26 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } /** * @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 ); } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding ); } interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding ); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require( msg.sender == strategist || msg.sender == governance(), "!authorized" ); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require( msg.sender == vault.management() || msg.sender == governance(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require( HealthCheck(healthCheck).check( profit, loss, debtPayment, debtOutstanding, totalDebt ), "!healthcheck" ); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer( governance(), IERC20(_token).balanceOf(address(this)) ); } } abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper ); emit Cloned(newStrategy); } } interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest( uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows ); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor( uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa ); /** * @notice Event emitted when the reserves are added */ event ReservesAdded( address benefactor, uint256 addAmount, uint256 newTotalReserves ); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced( address admin, uint256 reduceAmount, uint256 newTotalReserves ); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval( address indexed owner, address indexed spender, uint256 amount ); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated function compSupplySpeeds(address ctoken) external view returns (uint256); function compBorrowSpeeds(address ctoken) external view returns (uint256); function oracle() external view returns (address); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } contract LevCompFactory { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) public { Strategy _original = new Strategy( _vault, _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); emit Deployed(address(_original)); original = address(_original); _original.setStrategist(msg.sender); } function name() external view returns (string memory) { return string( abi.encodePacked( "Factory", Strategy(payable(original)).name(), "@", Strategy(payable(original)).apiVersion() ) ); } function cloneLevComp( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) external returns (address payable newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); Strategy(newStrategy).setRewards(msg.sender); Strategy(newStrategy).setStrategist(msg.sender); emit Cloned(newStrategy); } } /** * @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); } } /** * @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" ); } } } /** * @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; } } interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); } contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Comptroller address for compound.finance ComptrollerI public compound; //Only three tokens we use address public comp; address public weth; CErc20I public cToken; uint256 private secondsPerBlock; //1 for fantom. 13 for ethereum IUniswapV2Router02 public currentRouter; //uni v2 forks only uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18) uint256 private blocksToLiquidationDangerZone; // minimum number of blocks before liquidation uint256 public minWant; // minimum amount of want to act on // Rewards handling bool public dontClaimComp; // enable/disables COMP claiming uint256 public minCompToSell; // minimum amount of COMP to be sold uint256 public iterations; //number of loops we do bool public forceMigrate; bool public withdrawChecks; bool public splitCompDistribution; constructor( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) public BaseStrategy(_vault) { _initializeThis( _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); } function approveTokenMax(address token, address spender) internal { IERC20(token).safeApprove(spender, type(uint256).max); } function name() external view override returns (string memory) { return "GenLevCompV3NoFlash"; } function initialize( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) external { _initialize(_vault, msg.sender, msg.sender, msg.sender); _initializeThis( _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); } function _initializeThis( address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) internal { cToken = CErc20I(_cToken); comp = _comp; weth = _weth; secondsPerBlock = _secondsPerBlock; compound = ComptrollerI(_comptroller); require(IERC20Extended(address(want)).decimals() <= 18); // dev: want not supported currentRouter = IUniswapV2Router02(_router); //pre-set approvals approveTokenMax(comp, address(currentRouter)); approveTokenMax(address(want), address(cToken)); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100_000; // multiple before triggering harvest debtThreshold = 1e30; iterations = 6; //standard 6 // set minWant to 1e-5 want minWant = uint256( uint256(10)**uint256((IERC20Extended(address(want))).decimals()) ).div(1e5); minCompToSell = 0.1 ether; //may need to be changed depending on what comp is collateralTarget = 0.73 ether; blocksToLiquidationDangerZone = 46500; } /* * Control Functions */ function setWithdrawChecks(bool _withdrawChecks) external management { withdrawChecks = _withdrawChecks; } function setDontClaimComp(bool _dontClaimComp) external management { dontClaimComp = _dontClaimComp; } function setRouter(address _currentV2Router) external onlyGovernance { currentRouter = IUniswapV2Router02(_currentV2Router); } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setSplitCompDistribution(bool _split) external management { splitCompDistribution = _split; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setIterations(uint256 _iterations) external management { require(_iterations > 0 && _iterations <= 100); iterations = _iterations; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public view override returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = balanceOfToken(comp); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck( comp, address(want), _claimableComp.add(currentComp) ); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return balanceOfToken(address(want)) .add(deposits) .add(conservativeWant) .sub(borrows); } function balanceOfToken(address token) internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets.sub(debt); } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public view override returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck( address start, address end, uint256 _amount ) public view returns (uint256) { if (_amount == 0) { return 0; } if (start == end) { return _amount; } uint256[] memory amounts = currentRouter.getAmountsOut( _amount, getTokenOutPathV2(start, end) ); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit = deposits .mul(collateralFactorMantissa) .div(1e18); uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1.sub(denom2); //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } uint256 distributionPerBlockSupply; uint256 distributionPerBlockBorrow; if (splitCompDistribution) { distributionPerBlockSupply = compound.compSupplySpeeds( address(cToken) ); distributionPerBlockBorrow = compound.compBorrowSpeeds( address(cToken) ); } else { //pre 062 forks distributionPerBlockSupply = compound.compSpeeds(address(cToken)); distributionPerBlockBorrow = distributionPerBlockSupply; } uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken .mul(cToken.exchangeRateStored()) .div(1e18); uint256 blockShareSupply = 0; if (totalSupply > 0) { blockShareSupply = deposits.mul(distributionPerBlockSupply).div( totalSupply ); } uint256 blockShareBorrow = 0; if (totalBorrow > 0) { blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div( totalBorrow ); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast = (block.timestamp.sub(lastReport)).div( secondsPerBlock ); return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { ( , uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate ) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; // for clarity. also reduces bytesize if (balanceOfToken(address(cToken)) == 0) { uint256 wantBalance = balanceOfToken(address(want)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = balanceOfToken(address(want)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance.sub(debt); if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)) { _debtPayment = _debtOutstanding; } else { _debtPayment = wantBalance.sub(_profit); } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt.sub(balance); _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = balanceOfToken(address(want)); if (_wantBal < _debtOutstanding) { //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(_debtOutstanding.sub(_wantBal)); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition( _wantBal.sub(_debtOutstanding), true ); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation uint256 i = 0; while (position > minWant) { position = position.sub(_noFlashLoan(position, deficit)); if (i >= iterations) { break; } i++; } } /************* * Very important function * Input: amount we want to withdraw * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition( _amount, false ); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= iterations) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if (tempColla == 0) { tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if (depositBalance >= reservedAmount) { uint256 redeemable = depositBalance.sub(reservedAmount); uint256 balan = cToken.balanceOf(address(this)); if (balan > 1) { if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } } if ( collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance ) { cToken.repayBorrow(borrowBalance); } } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if (balance > unwoundDeposit) { balance = unwoundDeposit; } desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow.sub(1e5); } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow.sub(borrows); } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = balanceOfToken(address(want)); uint256 assets = netBalanceLent().add(_balance); (uint256 deposits, uint256 borrows) = getLivePosition(); if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can //1 token causes rounding error with withdrawUnderlying if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { _amountFreed = _amountNeeded; } } // To prevent the vault from moving on to the next strategy in the queue // when we return the amountRequested minus dust, take a dust sized loss if (_amountFreed < _amountNeeded) { uint256 diff = _amountNeeded.sub(_amountFreed); if (diff <= minWant) { _loss = diff; } } if (withdrawChecks) { require(_amountNeeded == _amountFreed.add(_loss)); // dev: fourThreeProtection } } function _claimComp() internal { if (dontClaimComp) { return; } CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = balanceOfToken(comp); if (_comp < minCompToSell) { return; } currentRouter.swapExactTokensForTokens( _comp, 0, getTokenOutPathV2(comp, address(want)), address(this), now ); } function getTokenOutPathV2(address _tokenIn, address _tokenOut) internal view returns (address[] memory _path) { bool isWeth = _tokenIn == address(weth) || _tokenOut == address(weth); _path = new address[](isWeth ? 2 : 3); _path[0] = _tokenIn; if (isWeth) { _path[1] = _tokenOut; } else { _path[1] = address(weth); _path[2] = _tokenOut; } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if (!forceMigrate) { (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot( address(this) ); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint256 _compB = balanceOfToken(address(_comp)); if (_compB > 0) { _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } if (lent == 0) { cToken.mint(balanceOfToken(address(want))); (lent, borrowed) = getCurrentPosition(); } (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); if (deficit) { amount = _normalDeleverage( max, lent, borrowed, collateralFactorMantissa ); } else { amount = _normalLeverage( max, lent, borrowed, collateralFactorMantissa ); } } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if (collatRatio != 0) { theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn * 1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if ( deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10 ) { deleveragedAmount = deleveragedAmount.sub(uint256(10)); cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if (leveragedAmount > 10) { leveragedAmount = leveragedAmount.sub(uint256(10)); cToken.borrow(leveragedAmount); cToken.mint(balanceOfToken(address(want))); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management { require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance { require(cToken.redeemUnderlying(amount) == 0); // dev: !manual-release-want } function protectedTokens() internal view override returns (address[] memory) {} //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } // -- Internal Helper functions -- // function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return priceCheck(weth, address(want), _amtInWei); } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(vault.debtOutstanding()); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 position = deposits.sub(borrows); //we want to revert if we can't liquidateall if (!forceMigrate) { require(position < minWant); } } function mgtm_check() internal view { require( msg.sender == governance() || msg.sender == vault.management() || msg.sender == strategist, "!authorized" ); } modifier management() { mgtm_check(); _; } }
WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck( address start, address end, uint256 _amount ) public view returns (uint256) { if (_amount == 0) { return 0; } if (start == end) { return _amount; } uint256[] memory amounts = currentRouter.getAmountsOut( _amount, getTokenOutPathV2(start, end) ); return amounts[amounts.length - 1]; }
12,945,583
[ 1, 9511, 18, 13441, 332, 8163, 471, 4143, 7502, 18, 5098, 999, 364, 4183, 4186, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6205, 1564, 12, 203, 3639, 1758, 787, 16, 203, 3639, 1758, 679, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 8949, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 261, 1937, 422, 679, 13, 288, 203, 5411, 327, 389, 8949, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 783, 8259, 18, 588, 6275, 87, 1182, 12, 203, 5411, 389, 8949, 16, 203, 5411, 9162, 1182, 743, 58, 22, 12, 1937, 16, 679, 13, 203, 3639, 11272, 203, 203, 3639, 327, 30980, 63, 8949, 87, 18, 2469, 300, 404, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x298F37fFd4B31d216B8954968cEe7EC5273CB891/sources/src/Drips.sol
@notice Transfers withdrawable funds to an address. The withdrawable funds are held by the Drips contract, but not used in the protocol, so they are free to be transferred out. Anybody can call `withdraw`, so all withdrawable funds should be withdrawn or used in the protocol before any 3rd parties have a chance to do that. @param erc20 The used ERC-20 token. It must preserve amounts, so if some amount of tokens is transferred to an address, then later the same amount must be transferable from that address. Tokens which rebase the holders' balances, collect taxes on transfers, or impose any restrictions on holding or transferring tokens are not supported. If you use such tokens in the protocol, they can get stuck or lost. @param receiver The address to send withdrawn funds to. @param amt The withdrawn amount. It must be at most the difference between the balance of the token held by the Drips contract address and the sum of balances managed by the protocol as indicated by `balances`.
function withdraw(IERC20 erc20, address receiver, uint256 amt) public { (uint128 streamsBalance, uint128 splitsBalance) = balances(erc20); uint256 withdrawable = _tokenBalance(erc20) - streamsBalance - splitsBalance; require(amt <= withdrawable, "Withdrawal amount too high"); emit Withdrawn(erc20, receiver, amt); erc20.safeTransfer(receiver, amt); }
3,819,332
[ 1, 1429, 18881, 598, 9446, 429, 284, 19156, 358, 392, 1758, 18, 1021, 598, 9446, 429, 284, 19156, 854, 15770, 635, 326, 463, 566, 1121, 6835, 16, 1496, 486, 1399, 316, 326, 1771, 16, 1427, 2898, 854, 4843, 358, 506, 906, 4193, 596, 18, 5502, 3432, 848, 745, 1375, 1918, 9446, 9191, 1427, 777, 598, 9446, 429, 284, 19156, 1410, 506, 598, 9446, 82, 578, 1399, 316, 326, 1771, 1865, 1281, 890, 13623, 1087, 606, 1240, 279, 17920, 358, 741, 716, 18, 225, 6445, 71, 3462, 1021, 1399, 4232, 39, 17, 3462, 1147, 18, 2597, 1297, 9420, 30980, 16, 1427, 309, 2690, 3844, 434, 2430, 353, 906, 4193, 358, 392, 1758, 16, 1508, 5137, 326, 1967, 3844, 1297, 506, 7412, 429, 628, 716, 1758, 18, 13899, 1492, 283, 1969, 326, 366, 4665, 11, 324, 26488, 16, 3274, 5320, 281, 603, 29375, 16, 578, 709, 4150, 1281, 17499, 603, 19918, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 598, 9446, 12, 45, 654, 39, 3462, 6445, 71, 3462, 16, 1758, 5971, 16, 2254, 5034, 25123, 13, 1071, 288, 203, 3639, 261, 11890, 10392, 8205, 13937, 16, 2254, 10392, 11019, 13937, 13, 273, 324, 26488, 12, 12610, 3462, 1769, 203, 3639, 2254, 5034, 598, 9446, 429, 273, 389, 2316, 13937, 12, 12610, 3462, 13, 300, 8205, 13937, 300, 11019, 13937, 31, 203, 3639, 2583, 12, 301, 88, 1648, 598, 9446, 429, 16, 315, 1190, 9446, 287, 3844, 4885, 3551, 8863, 203, 3639, 3626, 3423, 9446, 82, 12, 12610, 3462, 16, 5971, 16, 25123, 1769, 203, 3639, 6445, 71, 3462, 18, 4626, 5912, 12, 24454, 16, 25123, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT import { Ownable } from "./abstract/Ownable.sol"; pragma solidity 0.8.6; contract Parameterized is Ownable { uint256 internal constant WEEK = 7 days; uint256 internal constant MONTH = 30 days; struct StakeParameters { uint256 value; uint256 lastChange; uint256 minDelay; } /// @notice time to allow to be Super Staker (30*24*60*60) StakeParameters public timeToSuper; /// @notice time to wait for unstake (7*24*60*60) StakeParameters public timeToUnstake; /// @notice fee for premature unstake in 1/10 percent, /// @dev value 1000 = 10% StakeParameters public unstakeFee; function _minusFee(uint256 val) internal view returns (uint256) { return val - ((val * unstakeFee.value) / 10000); } function updateFee(uint256 val) external onlyOwner { require(block.timestamp > unstakeFee.lastChange + unstakeFee.minDelay, "Soon"); require(val <= 2500, "max fee is 25%"); unstakeFee.lastChange = block.timestamp; unstakeFee.value = val; } function updateTimeToUnstake(uint256 val) external onlyOwner { require(block.timestamp > timeToUnstake.lastChange + timeToUnstake.minDelay, "Soon"); require(val <= 2 * WEEK, "Max delay is 14 days"); timeToUnstake.lastChange = block.timestamp; timeToUnstake.value = val; } function updateTimeToSuper(uint256 val) external onlyOwner { require(block.timestamp > timeToSuper.lastChange + timeToSuper.minDelay, "Soon"); require(val <= 3 * MONTH && val >= WEEK, "Delay is 1 week - 3 months"); timeToSuper.lastChange = block.timestamp; timeToSuper.value = val; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { ReentrancyGuard } from "./external/openzeppelin/ReentrancyGuard.sol"; import { RewardsDistribution } from "./abstract/RewardsDistribution.sol"; import { StableMath } from "./libraries/StableMath.sol"; import { SafeERC20, IERC20 } from "./libraries/SafeERC20.sol"; import { Parameterized } from "./Parameterized.sol"; /** * @title SynapseStaking * @notice Rewards stakers of SNP token and a given LP token with rewards in form of SNP token, on a pro-rata basis. * @dev Uses an ever increasing 'rewardPerTokenStored' variable to distribute rewards * each time a write action is called in the contract. This allows for passive reward accrual. */ contract SynapseStaking is RewardsDistribution, ReentrancyGuard, Parameterized { using StableMath for uint256; using SafeERC20 for IERC20; /// @notice stake/reward token address address public tokenAddress; /// @notice LP stake token address address public liquidityAddress; /// @notice vesting contract address address public vestingAddress; /// @notice timestamp for current period finish uint256 public periodFinish; /// @notice timestamp for current super period finish uint256 public superPeriodFinish; struct Data { uint256 depositedTokens; // deposited tokens amount uint256 depositedLiquidity; // deposited lp amount uint256 totalRewardsAdded; // accumulated amount of rewards added to token and liquidity staking uint256 totalRewardsClaimed; // accumulated amount of rewards claimed uint256 totalRewardsFromFees; // accumulated amount of rewards collected from fee-on-transfer } Data public data; struct StakingData { uint256 rewardRate; // rewardRate for the rest of the period uint256 superRewardRate; // superRewardRate for the rest of the super period uint256 lastUpdateTime; // last time any user took action uint256 lastSuperUpdateTime; // last time super staker took action uint256 rewardPerTokenStored; // accumulated per token reward since the beginning of time uint256 superRewardPerTokenStored; // super accumulated per token reward since the beginning of time uint256 stakedTokens; // amount of tokens that is used in reward per token calculation uint256 stakedSuperTokens; // amount of tokens that is used in super reward per token calculation } StakingData public tokenStaking; StakingData public lpStaking; struct Stake { uint256 stakeStart; // timestamp of stake creation uint256 superStakerPossibleAt; // timestamp after which user can claim super staker status // uint256 rewardPerTokenPaid; // user accumulated per token rewards uint256 superRewardPerTokenPaid; // user accumulated per token super staker rewards // uint256 tokens; // total tokens staked by user snp or lp uint256 rewards; // current not-claimed rewards from last update // uint256 withdrawalPossibleAt; // timestamp after which stake can be removed without fee bool isWithdrawing; // true = user call to remove stake bool isSuperStaker; // true = user is super staker } /// @dev each holder have one stake /// @notice token stakes storage mapping(address => Stake) public tokenStake; /// @notice LP token stakes storage mapping(address => Stake) public liquidityStake; /// @dev events event Claimed(address indexed user, uint256 amount); event StakeAdded(address indexed user, uint256 amount); event StakeLiquidityAdded(address indexed user, uint256 amount); event StakeRemoveRequested(address indexed user); event StakeLiquidityRemoveRequested(address indexed user); event StakeRemoved(address indexed user, uint256 amount); event StakeLiquidityRemoved(address indexed user, uint256 amount); event Recalculation(uint256 reward, uint256 lpReward); event SuperRecalculation(uint256 superReward, uint256 superLpReward); /** * @param _timeToSuper time needed to become a super staker * @param _timeToUnstake time needed to unstake without fee */ constructor(uint256 _timeToSuper, uint256 _timeToUnstake) { timeToSuper.value = _timeToSuper; timeToUnstake.value = _timeToUnstake; timeToSuper.lastChange = block.timestamp; timeToUnstake.lastChange = block.timestamp; timeToSuper.minDelay = WEEK; timeToUnstake.minDelay = WEEK; unstakeFee.value = 1000; } /** * @dev One time initialization function * @param _token SNP token address * @param _liquidity SNP/USDC LP token address * @param _vesting public vesting contract address */ function init( address _token, address _liquidity, address _vesting ) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); require(_liquidity != address(0), "_liquidity address cannot be 0"); require(_vesting != address(0), "_vesting address cannot be 0"); require(tokenAddress == address(0), "Init already done"); tokenAddress = _token; liquidityAddress = _liquidity; vestingAddress = _vesting; } /** * @dev Updates the reward for a given address, * for token and LP pool, before executing function * @param _account address of staker for which rewards will be updated */ modifier updateRewards(address _account) { _updateReward(_account, false); _updateReward(_account, true); _; } /** * @dev Updates the reward for a given address, * for given pool, before executing function * @param _account address for which rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ modifier updateReward(address _account, bool _lp) { _updateReward(_account, _lp); _; } /** * @dev Updates the super rewards for a given address, * for token and LP pool, before executing function * @param _account address of super staker for which super rewards will be updated */ modifier updateSuperRewards(address _account) { bool success = _updateSuperReward(_account, false); success = _updateSuperReward(_account, true) || success; if (success) { _calculateSuperRewardAmount(); } _; } /** * @dev guards that the given address has selected stake * @param _account address to check * @param _lp true=lpStaking, false=tokenStaking */ modifier hasPoolStake(address _account, bool _lp) { bool accountHasStake = _lp ? (liquidityStake[_account].tokens > 0) : (tokenStake[_account].tokens > 0); require(accountHasStake, "Nothing staked"); _; } /** * @dev guards that the msg.sender has token or LP stake */ modifier hasStake() { require((liquidityStake[msg.sender].tokens > 0) || (tokenStake[msg.sender].tokens > 0), "Nothing staked"); _; } /** * @dev guards that the given address can be a super staker in selected stake * @param _account address to check * @param _lp true=lpStaking, false=tokenStaking */ modifier canBeSuper(address _account, bool _lp) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); require(!s.isSuperStaker, "Already super staker"); require(block.timestamp >= s.superStakerPossibleAt, "Too soon"); _; } /** * @dev checks if the msg.sender can withdraw requested unstake */ modifier canUnstake() { require(_canUnstake(), "Cannot unstake"); _; } /** * @dev checks if for the msg.sender there is possibility to * withdraw staked tokens without fee. */ modifier cantUnstake() { require(!_canUnstake(), "Unstake first"); _; } /*************************************** ACTIONS ****************************************/ /** * @dev Updates reward in selected pool * @param _account address for which rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ function _updateReward(address _account, bool _lp) internal { uint256 newRewardPerTokenStored = currentRewardPerTokenStored(_lp); // if statement protects against loss in initialization case if (newRewardPerTokenStored > 0) { StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.rewardPerTokenStored = newRewardPerTokenStored; sd.lastUpdateTime = lastTimeRewardApplicable(); // setting of personal vars based on new globals if (_account != address(0)) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isWithdrawing) { s.rewards = _earned(_account, _lp); s.rewardPerTokenPaid = newRewardPerTokenStored; } } } } /** * @dev Updates super reward in selected pool * @param _account address of super staker for which super rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ function _updateSuperReward(address _account, bool _lp) internal returns (bool success) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; // save gas for non super stakers if (s.isSuperStaker || _account == address(0)) { uint256 newSuperRewardPerTokenStored = currentSuperRewardPerTokenStored(_lp); // if statement protects against loss in initialization case if (newSuperRewardPerTokenStored > 0) { StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.superRewardPerTokenStored = newSuperRewardPerTokenStored; sd.lastSuperUpdateTime = lastTimeSuperRewardApplicable(); // setting of personal vars based on new globals if (_account != address(0)) { // setting of personal vars based on new globals if (!s.isWithdrawing) { s.rewards = _earnedSuper(_account, _lp); s.superRewardPerTokenPaid = newSuperRewardPerTokenStored; } } } success = true; } } /** * @dev Add tokens for staking from vesting contract * @param _account address that call claimAndStake in vesting * @param _amount number of tokens sent to contract */ function onClaimAndStake(address _account, uint256 _amount) external nonReentrant updateReward(_account, false) updateSuperRewards(_account) { require(msg.sender == vestingAddress, "Only vesting contract"); require(!tokenStake[_account].isWithdrawing, "Cannot when withdrawing"); require(_amount > 0, "Zero Amount"); Stake storage s = tokenStake[_account]; StakingData storage sd = tokenStaking; if (s.stakeStart == 0) { // new stake s.stakeStart = block.timestamp; s.superStakerPossibleAt = s.stakeStart + timeToSuper.value; } // update account stake data s.tokens += _amount; // update pool staking data sd.stakedTokens += _amount; if (s.isSuperStaker) { sd.stakedSuperTokens += _amount; } // update global data data.depositedTokens += _amount; emit StakeAdded(_account, _amount); } /** * @dev Add tokens to staking contract * @param _amount of tokens to stake */ function addTokenStake(uint256 _amount) external { _addStake(msg.sender, _amount, false); emit StakeAdded(msg.sender, _amount); } /** * @dev Add tokens to staking contract by using permit to set allowance * @param _amount of tokens to stake * @param _deadline of permit signature * @param _approveMax allowance for the token */ function addTokenStakeWithPermit( uint256 _amount, uint256 _deadline, bool _approveMax, uint8 v, bytes32 r, bytes32 s ) external { uint256 value = _approveMax ? type(uint256).max : _amount; IERC20(tokenAddress).permit(msg.sender, address(this), value, _deadline, v, r, s); _addStake(msg.sender, _amount, false); emit StakeAdded(msg.sender, _amount); } /** * @dev Add liquidity tokens to staking contract * @param _amount of LP tokens to stake */ function addLiquidityStake(uint256 _amount) external { _addStake(msg.sender, _amount, true); emit StakeLiquidityAdded(msg.sender, _amount); } /** * @dev Add liquidity tokens to staking contract * @param _amount of tokens to stake * @param _deadline of permit signature * @param _approveMax allowance for the token */ function addLiquidityStakeWithPermit( uint256 _amount, uint256 _deadline, bool _approveMax, uint8 v, bytes32 r, bytes32 s ) external { uint256 value = _approveMax ? type(uint256).max : _amount; IERC20(liquidityAddress).permit(msg.sender, address(this), value, _deadline, v, r, s); _addStake(msg.sender, _amount, true); emit StakeLiquidityAdded(msg.sender, _amount); } /** * @dev Internal add stake function * @param _account selected staked tokens are credited to this address * @param _amount of staked tokens * @param _lp true=LP token, false=SNP token */ function _addStake( address _account, uint256 _amount, bool _lp ) internal nonReentrant updateReward(_account, _lp) updateSuperRewards(_account) { require(_amount > 0, "Zero Amount"); Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); address token = _lp ? liquidityAddress : tokenAddress; // check for fee-on-transfer and proceed with received amount _amount = _transferFrom(token, msg.sender, _amount); if (s.stakeStart == 0) { // new stake s.stakeStart = block.timestamp; s.superStakerPossibleAt = s.stakeStart + timeToSuper.value; } StakingData storage sd = _lp ? lpStaking : tokenStaking; // update account stake data s.tokens += _amount; // update pool staking data sd.stakedTokens += _amount; if (s.isSuperStaker) { sd.stakedSuperTokens += _amount; } // update global data if (_lp) { data.depositedLiquidity += _amount; } else { data.depositedTokens += _amount; } } /** * @dev Restake earned tokens and add them to token stake (instead of claiming) * If have LP stake but not token stake - token stake will be created. */ function restake() external hasStake updateRewards(msg.sender) updateSuperRewards(msg.sender) { Stake storage ts = tokenStake[msg.sender]; Stake storage ls = liquidityStake[msg.sender]; require(!ts.isWithdrawing, "Cannot when withdrawing"); uint256 rewards = ts.rewards + ls.rewards; require(rewards > 0, "Nothing to restake"); delete ts.rewards; delete ls.rewards; if (ts.stakeStart == 0) { // new stake ts.stakeStart = block.timestamp; ts.superStakerPossibleAt = ts.stakeStart + timeToSuper.value; } // update account stake data ts.tokens += rewards; // update pool staking data tokenStaking.stakedTokens += rewards; if (ts.isSuperStaker) { tokenStaking.stakedSuperTokens += rewards; } data.totalRewardsClaimed += rewards; data.depositedTokens += rewards; emit Claimed(msg.sender, rewards); emit StakeAdded(msg.sender, rewards); } /** * @dev Claims rewards for the msg.sender. */ function claim() external { _claim(msg.sender, msg.sender); } /** * @dev Claim msg.sender rewards to provided address * @param _recipient address where claimed tokens should be sent */ function claimTo(address _recipient) external { _claim(msg.sender, _recipient); } /** * @dev Internal claim function. First updates rewards in normal and super pools * and then transfers. * @param _account claim rewards for this address * @param _recipient claimed tokens are sent to this address */ function _claim(address _account, address _recipient) internal nonReentrant hasStake updateRewards(_account) updateSuperRewards(_account) { uint256 rewards = tokenStake[_account].rewards + liquidityStake[_account].rewards; require(rewards > 0, "Nothing to claim"); delete tokenStake[_account].rewards; delete liquidityStake[_account].rewards; data.totalRewardsClaimed += rewards; _transfer(tokenAddress, _recipient, rewards); emit Claimed(_account, rewards); } /** * @dev Request unstake for deposited tokens. Marks user token stake as withdrawing, * and start withdrawing period. */ function requestUnstake() external { _requestUnstake(msg.sender, false); emit StakeRemoveRequested(msg.sender); } /** * @dev Request unstake for deposited LP tokens. Marks user lp stake as withdrawing * and start withdrawing period. */ function requestUnstakeLp() external { _requestUnstake(msg.sender, true); emit StakeLiquidityRemoveRequested(msg.sender); } /** * @dev Internal request unstake function. Update normal and super rewards for the user first. * @param _account User address * @param _lp true=it is LP stake */ function _requestUnstake(address _account, bool _lp) internal hasPoolStake(_account, _lp) updateReward(_account, _lp) updateSuperRewards(_account) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); StakingData storage sd = _lp ? lpStaking : tokenStaking; // update account stake data s.isWithdrawing = true; s.withdrawalPossibleAt = block.timestamp + timeToUnstake.value; // update pool staking data sd.stakedTokens -= s.tokens; if (s.isSuperStaker) { delete s.isSuperStaker; sd.stakedSuperTokens -= s.tokens; } } /** * @dev Withdraw stake for msg.sender from both stakes (if possible) */ function unstake() external nonReentrant hasStake canUnstake { bool success; uint256 reward; uint256 tokens; uint256 rewards; (reward, success) = _unstake(msg.sender, false); rewards += reward; if (success) { tokens += tokenStake[msg.sender].tokens; data.depositedTokens -= tokenStake[msg.sender].tokens; emit StakeRemoved(msg.sender, tokenStake[msg.sender].tokens); delete tokenStake[msg.sender]; } (reward, success) = _unstake(msg.sender, true); rewards += reward; if (success) { delete liquidityStake[msg.sender]; } if (tokens + rewards > 0) { _transfer(tokenAddress, msg.sender, tokens + rewards); if (rewards > 0) { emit Claimed(msg.sender, rewards); } } } /** * @dev Internal unstake function, withdraw staked LP tokens * @param _account address of account to transfer LP tokens * @param _lp true = LP stake * @return stake rewards amount * @return bool true if success */ function _unstake(address _account, bool _lp) internal returns (uint256, bool) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isWithdrawing) return (0, false); if (s.withdrawalPossibleAt > block.timestamp) return (0, false); data.totalRewardsClaimed += s.rewards; // only LP stake if (_lp && s.tokens > 0) { data.depositedLiquidity -= s.tokens; _transfer(liquidityAddress, _account, s.tokens); emit StakeLiquidityRemoved(_account, s.tokens); } return (s.rewards, true); } /** * @dev Unstake requested stake at any time accepting 10% penalty fee */ function unstakeWithFee() external nonReentrant hasStake cantUnstake { Stake memory ts = tokenStake[msg.sender]; Stake memory ls = liquidityStake[msg.sender]; uint256 tokens; uint256 rewards; if (ls.isWithdrawing) { uint256 lpTokens = _minusFee(ls.tokens); //remaining tokens remain on the contract rewards += ls.rewards; data.totalRewardsClaimed += ls.rewards; data.depositedLiquidity -= ls.tokens; emit StakeLiquidityRemoved(msg.sender, ls.tokens); if (lpTokens > 0) { _transfer(liquidityAddress, msg.sender, lpTokens); } delete liquidityStake[msg.sender]; } if (ts.isWithdrawing) { tokens = _minusFee(ts.tokens); // remaining tokens goes to Super Stakers rewards += ts.rewards; data.totalRewardsClaimed += ts.rewards; data.depositedTokens -= ts.tokens; emit StakeRemoved(msg.sender, ts.tokens); delete tokenStake[msg.sender]; } if (tokens + rewards > 0) { _transfer(tokenAddress, msg.sender, tokens + rewards); if (rewards > 0) { emit Claimed(msg.sender, rewards); } } } /** * @dev Set Super Staker status for token pool stake if possible. */ function setSuperToken() external { _setSuper(msg.sender, false); } /** * @dev Set Super Staker status for LP pool stake if possible. */ function setSuperLp() external { _setSuper(msg.sender, true); } /** * @dev Set Super Staker status if possible for selected pool. * Update super reward pools. * @param _account address of account to set super * @param _lp true=LP stake super staker, false=token stake super staker */ function _setSuper(address _account, bool _lp) internal hasPoolStake(_account, _lp) canBeSuper(_account, _lp) updateSuperRewards(address(0)) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.stakedSuperTokens += s.tokens; s.isSuperStaker = true; s.superRewardPerTokenPaid = sd.superRewardPerTokenStored; } /*************************************** GETTERS ****************************************/ /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Gets the last applicable timestamp for this super reward period */ function lastTimeSuperRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, superPeriodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @param _lp true=lpStaking, false=tokenStaking * @return 'Reward' per staked token */ function currentRewardPerTokenStored(bool _lp) public view returns (uint256) { StakingData memory sd = _lp ? lpStaking : tokenStaking; uint256 stakedTokens = sd.stakedTokens; uint256 rewardPerTokenStored = sd.rewardPerTokenStored; // If there is no staked tokens, avoid div(0) if (stakedTokens == 0) { return (rewardPerTokenStored); } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 timeDelta = lastTimeRewardApplicable() - sd.lastUpdateTime; uint256 rewardUnitsToDistribute = sd.rewardRate * timeDelta; // new reward units per token = (rewardUnitsToDistribute * 1e18) / stakedTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens); // return summed rate return (rewardPerTokenStored + unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed super rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @param _lp true=lpStaking, false=tokenStaking * @return 'Reward' per staked token */ function currentSuperRewardPerTokenStored(bool _lp) public view returns (uint256) { StakingData memory sd = _lp ? lpStaking : tokenStaking; uint256 stakedSuperTokens = sd.stakedSuperTokens; uint256 superRewardPerTokenStored = sd.superRewardPerTokenStored; // If there is no staked tokens, avoid div(0) if (stakedSuperTokens == 0) { return (superRewardPerTokenStored); } // new reward units to distribute = superRewardRate * timeSinceLastSuperUpdate uint256 timeDelta = lastTimeSuperRewardApplicable() - sd.lastSuperUpdateTime; uint256 rewardUnitsToDistribute = sd.superRewardRate * timeDelta; // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalSuperTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedSuperTokens); // return summed rate return (superRewardPerTokenStored + unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed rewards a user has earned * @param _account user address * @param _lp true=liquidityStake, false=tokenStake * @return Total reward amount earned */ function _earned(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 rewardPerTokenStored = currentRewardPerTokenStored(_lp); uint256 userRewardDelta = rewardPerTokenStored - s.rewardPerTokenPaid; uint256 userNewReward = s.tokens.mulTruncate(userRewardDelta); // add to previous rewards return (s.rewards + userNewReward); } /** * @dev Calculates the amount of unclaimed super rewards a user has earned * @param _account user address * @param _lp true=liquidityStake, false=tokenStake * @return Total reward amount earned */ function _earnedSuper(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isSuperStaker || s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 superRewardPerTokenStored = currentSuperRewardPerTokenStored(_lp); uint256 superRewardDelta = superRewardPerTokenStored - s.superRewardPerTokenPaid; uint256 userNewSuperReward = s.tokens.mulTruncate(superRewardDelta); // add to previous rewards return (s.rewards + userNewSuperReward); } /** * @dev Calculates the claimable amounts for token and lp stake from normal and super rewards * @param _account user address * @return token - claimable reward amount for token stake * @return lp - claimable reward amount for lp stake */ function claimable(address _account) external view returns (uint256 token, uint256 lp) { token = _earned(_account, false) + _earnedSuper(_account, false) - tokenStake[_account].rewards; lp = _earned(_account, true) + _earnedSuper(_account, true) - liquidityStake[_account].rewards; } /** * @dev Check if staker can set super staker status on token or LP stake * @param _account address to check * @return token true if can set super staker on token stake * @return lp true if can set super staker on LP stake */ function canSetSuper(address _account) external view returns (bool token, bool lp) { Stake memory ts = tokenStake[_account]; Stake memory ls = liquidityStake[_account]; if (ts.tokens > 0 && block.timestamp >= ts.superStakerPossibleAt && !ts.isSuperStaker && !ts.isWithdrawing) token = true; if (ls.tokens > 0 && block.timestamp >= ls.superStakerPossibleAt && !ls.isSuperStaker && !ls.isWithdrawing) lp = true; } /** * @dev internal view to check if msg.sender can unstake * @return true if user requested unstake and time for unstake has passed */ function _canUnstake() private view returns (bool) { return (liquidityStake[msg.sender].isWithdrawing && block.timestamp >= liquidityStake[msg.sender].withdrawalPossibleAt) || (tokenStake[msg.sender].isWithdrawing && block.timestamp >= tokenStake[msg.sender].withdrawalPossibleAt); } /** * @dev external view to check if address can stake tokens * @return true if user can stake tokens */ function canStakeTokens(address _account) external view returns (bool) { return !tokenStake[_account].isWithdrawing; } /** * @dev external view to check if address can stake lp * @return true if user can stake lp */ function canStakeLp(address _account) external view returns (bool) { return !liquidityStake[_account].isWithdrawing; } /*************************************** REWARDER ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of SNP token that have been added to the token pool * @param _lpReward Units of SNP token that have been added to the lp pool */ function notifyRewardAmount(uint256 _reward, uint256 _lpReward) external onlyRewardsDistributor updateRewards(address(0)) { uint256 currentTime = block.timestamp; // pull tokens require(_transferFrom(tokenAddress, msg.sender, _reward + _lpReward) == _reward + _lpReward, "Exclude Rewarder from fee"); // If previous period over, reset rewardRate if (currentTime >= periodFinish) { tokenStaking.rewardRate = _reward / WEEK; lpStaking.rewardRate = _lpReward / WEEK; } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish - currentTime; uint256 leftoverReward = remaining * tokenStaking.rewardRate; tokenStaking.rewardRate = (_reward + leftoverReward) / WEEK; uint256 leftoverLpReward = remaining * lpStaking.rewardRate; lpStaking.rewardRate = (_lpReward + leftoverLpReward) / WEEK; } tokenStaking.lastUpdateTime = currentTime; lpStaking.lastUpdateTime = currentTime; periodFinish = currentTime + WEEK; data.totalRewardsAdded += _reward + _lpReward; emit Recalculation(_reward, _lpReward); } /*************************************** SUPER STAKER ****************************************/ /** * @dev Notifies the contract that new super rewards have been added based on the collected fee. * Calculates an updated superRewardRate based on the rewards in period. * Function can be triggered by any super staker once a day. */ function _calculateSuperRewardAmount() internal { uint256 currentTime = block.timestamp; // Do nothing if less then a day from last calculation, save gas uint256 lastTime = superPeriodFinish > 0 ? superPeriodFinish - (MONTH - 1 days) : 0; if (currentTime >= lastTime) { uint256 contractBalance = _balance(tokenAddress, address(this)); uint256 feesCollected = contractBalance - data.depositedTokens - (data.totalRewardsAdded + data.totalRewardsFromFees - data.totalRewardsClaimed); data.totalRewardsFromFees += feesCollected; uint256 superRewards; unchecked { superRewards = feesCollected / 2; } // If previous period over, reset rewardRate if (currentTime >= superPeriodFinish) { tokenStaking.superRewardRate = superRewards / MONTH; lpStaking.superRewardRate = superRewards / MONTH; } // If additional reward to existing period, calc sum else { uint256 remaining = superPeriodFinish - currentTime; uint256 leftoverSuperReward = remaining * tokenStaking.superRewardRate; tokenStaking.superRewardRate = (superRewards + leftoverSuperReward) / MONTH; uint256 leftoverSuperLpReward = remaining * lpStaking.superRewardRate; lpStaking.superRewardRate = (superRewards + leftoverSuperLpReward) / MONTH; } tokenStaking.lastSuperUpdateTime = currentTime; lpStaking.lastSuperUpdateTime = currentTime; superPeriodFinish = currentTime + MONTH; emit SuperRecalculation(superRewards, superRewards); } } /*************************************** TOKEN ****************************************/ /** * @dev internal ERC20 tools */ function _balance(address token, address user) internal view returns (uint256) { return IERC20(token).balanceOf(user); } function _transferFrom( address token, address from, uint256 amount ) internal returns (uint256) { return IERC20(token).safeTransferFromDeluxe(from, amount); } function _transfer( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; abstract contract OwnableData { address public owner; address public pendingOwner; } abstract contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev `owner` defaults to msg.sender on construction. */ constructor() { _setOwner(msg.sender); } /** * @dev Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. * Can only be invoked by the current `owner`. * @param _newOwner Address of the new owner. * @param _direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. */ function transferOwnership(address _newOwner, bool _direct) external onlyOwner { if (_direct) { require(_newOwner != address(0), "zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; pendingOwner = address(0); } else { pendingOwner = _newOwner; } } /** * @dev Needs to be called by `pendingOwner` to claim ownership. */ function claimOwnership() external { address _pendingOwner = pendingOwner; require(msg.sender == _pendingOwner, "caller != pending owner"); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the Owner. */ modifier onlyOwner() { require(msg.sender == owner, "caller is not the owner"); _; } function _setOwner(address newOwner) internal { address oldOwner = owner; owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { Ownable } from "./Ownable.sol"; abstract contract RewardsDistributionData { address public rewardsDistributor; } abstract contract RewardsDistribution is Ownable, RewardsDistributionData { event RewardsDistributorChanged(address indexed previousDistributor, address indexed newDistributor); /** * @dev `rewardsDistributor` defaults to msg.sender on construction. */ constructor() { rewardsDistributor = msg.sender; emit RewardsDistributorChanged(address(0), msg.sender); } /** * @dev Throws if called by any account other than the Reward Distributor. */ modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "caller is not reward distributor"); _; } /** * @dev Change the rewardsDistributor - only called by owner * @param _rewardsDistributor Address of the new distributor */ function setRewardsDistribution(address _rewardsDistributor) external onlyOwner { require(_rewardsDistributor != address(0), "zero address"); emit RewardsDistributorChanged(rewardsDistributor, _rewardsDistributor); rewardsDistributor = _rewardsDistributor; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); // EIP 2612 // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address owner) external view returns (uint256); function permit(address owner, 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); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IERC20 } from "../interfaces/IERC20.sol"; library SafeERC20 { function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer(IERC20 token, address to, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed"); } function safeTransferFrom(IERC20 token, address from, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed"); } function safeTransferFromDeluxe(IERC20 token, address from, uint256 amount) internal returns (uint256) { uint256 preBalance = token.balanceOf(address(this)); safeTransferFrom(token, from, amount); uint256 postBalance = token.balanceOf(address(this)); return postBalance - preBalance; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; // Based on StableMath from mStable // https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e36 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
@notice LP token stakes storage
mapping(address => Stake) public liquidityStake;
10,143,483
[ 1, 14461, 1147, 384, 3223, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 934, 911, 13, 1071, 4501, 372, 24237, 510, 911, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x53466a575fE1beba1F49F557d9817a6996f25694/sources/Pool.sol
Info of each period.
Period[] public periods;
9,344,277
[ 1, 966, 434, 1517, 3879, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 5027, 8526, 1071, 12777, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-20 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // File: contracts/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. * * Source: openzeppelin */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external 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); } } // File: Strings.sol /** * Source: Openzeppelin */ /** * @dev String operations. */ 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); } } // File: ECDSA.sol // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { 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-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 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)); } } // File: Address.sol0 /** * Source: Openzeppelin */ /** * @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; } } // File: IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: IERC165.sol // https://eips.ethereum.org/EIPS/eip-165 interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: IERC2981.sol /** * Source: Openzeppelin */ /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev 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); } // File: ERC165.sol /** * Source: Openzeppelin */ /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: IERC721.sol // https://eips.ethereum.org/EIPS/eip-721, http://erc721.org/ /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://eips.ethereum.org/EIPS/eip-721 /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface IERC721 is IERC165 { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File: IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension * Made for efficiancy! */ contract ERC721 is ERC165, IERC721, IERC721Metadata, Ownable { using Address for address; using Strings for uint256; uint16 public totalSupply; address public proxyRegistryAddress; string public baseURI; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(address _openseaProxyRegistry, string memory _baseURI) { proxyRegistryAddress = _openseaProxyRegistry; baseURI = _baseURI; } /** * @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) external view 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 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() external pure override returns (string memory) { return "Kings"; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external pure override returns (string memory) { return "KINGS"; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString(), ".json")); } function setBaseURI(string memory uri) external onlyOwner { baseURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external override { address owner = _owners[tokenId]; require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view 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) external override { _setApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return _operatorApprovals[owner][operator]; } function setOpenseaProxyRegistry(address addr) external onlyOwner { proxyRegistryAddress = addr; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) external override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 ) external override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(_isApprovedOrOwner(msg.sender, 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 */ 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 = _owners[tokenId]; return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @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(uint256 amount, address to) internal { uint tokenId = totalSupply; _balances[to] += amount; for (uint i; i < amount; i++) { tokenId++; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } totalSupply += uint16(amount); require( _checkOnERC721Received(address(0), to, tokenId, ""), "ERC721: transfer to non ERC721Receiver implementer" ); // checking it once will make sure that the address can recieve NFTs } /** * @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(_owners[tokenId] == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from]--; _balances[to]++; _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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // File: Kings.sol contract Kings is Ownable, IERC2981, ERC721 { bool private _mintingEnabled; uint private EIP2981RoyaltyPercent; mapping (address => uint8) private amountMinted; constructor( uint _royalty, address _openseaProxyRegistry, string memory _tempBaseURI ) ERC721(_openseaProxyRegistry, _tempBaseURI) { EIP2981RoyaltyPercent = _royalty; } function mintFromReserve(uint amount, address to) external onlyOwner { require(amount + totalSupply < 2201, "Request will exceed max supply!"); _mint(amount, to); } function mint(uint256 amount) external payable { require(totalSupply > 599, "Minting is not enabled!"); require(amount < 21 && amount != 0, "Invalid request amount!"); require(amount + totalSupply < 2201, "Request exceeds max supply!"); require(msg.value == amount * 15e15, "ETH Amount is not correct!"); _mint(amount, msg.sender); } function freeMint(uint256 amount) external { require(_mintingEnabled, "Minting is not enabled!"); require(amount + totalSupply < 601, "Request exceeds max supply!"); require(amount + amountMinted[msg.sender] < 4 && amount != 0, "Request exceeds max per wallet!"); amountMinted[msg.sender] += uint8(amount); _mint(amount, msg.sender); } /** * @notice returns public sale status */ function mintingEnabled() external view returns(bool) { return _mintingEnabled; } /** * @notice returns royalty info for EIP2981 supporting marketplaces * @dev 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(uint tokenId, uint salePrice) external view override returns(address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Royality querry for non-existant token!"); return(owner(), salePrice * EIP2981RoyaltyPercent / 10000); } /** * @notice sets the royalty percentage for EIP2981 supporting marketplaces * @dev percentage is in bassis points (parts per 10,000). Example: 5% = 500, 0.5% = 50 * @param amount - percent amount */ function setRoyaltyPercent(uint256 amount) external onlyOwner { EIP2981RoyaltyPercent = amount; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function withdraw() onlyOwner external { uint bal = address(this).balance; bool success; (success, ) = payable(msg.sender).call{value: (bal * 93) / 100, gas: 3000}(""); require(success, "Transfer to contract owner failed!"); (success, ) = payable(0xC52a2331679404cB7DE9405e15303eEf122280A6).call{value: (bal * 7) / 100, gas: 3000}(""); require(success, "Transfer to core devs failed!"); } /** * @notice toggles the public sale */ function togglePublicSale() external onlyOwner { _mintingEnabled = !_mintingEnabled; } function tokensOfOwner(address owner) external view returns(uint[] memory) { uint[] memory tokens = new uint[](_balances[owner]); uint y = totalSupply + 1; uint x; for (uint i = 1; i < y; i++) { if (ownerOf(i) == owner) { tokens[x] = i; x++; } } return tokens; } }
* @dev Collection of functions related to the address type/
library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } }
2,344,407
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xF01A67842dAc71d2E515352E38783e45D7e4F639/sources/Alchemy.sol
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "Alchemy"; symbol = "AM"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
5,199,822
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 1067, 17192, 14432, 203, 3639, 3273, 273, 315, 2192, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: node_modules\@openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\contracts\cryptography\ECDSA.sol pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: contracts\VestingVault.sol pragma solidity ^0.5.0; /** * @title VestingVault * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract VestingVault is Initializable, Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); event TokenVestingBeneficiaryVerified(address beneficiary); // beneficiary of tokens after they are released address private _beneficiary; uint256 private _vestingAmount; uint256 private _intervalVested; uint256 private _cliff; uint256 private _start; uint256 private _interval; string private _stamp; uint256 private _duration; bool private _revocable; bool private _beneficiaryVerified; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint32 private constant SECONDS_PER_MINUTE = 60; uint32 private constant MINUTES_PER_HOUR = 60; uint32 private constant SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; uint32 private constant HOURS_PER_DAY = 24; uint32 private constant SECONDS_PER_DAY = HOURS_PER_DAY * SECONDS_PER_HOUR; // 86400 seconds per day uint32 private constant DAYS_PER_MONTH = 30; uint32 private constant SECONDS_PER_MONTH = DAYS_PER_MONTH * SECONDS_PER_DAY; // Month here is of 30 days period or 2592000 seconds per month. uint32 private constant DAYS_PER_YEAR = 365; uint32 private constant SECONDS_PER_YEAR = DAYS_PER_YEAR * SECONDS_PER_DAY; // Year here is of 365 days period. mapping(address => uint256) private _released; mapping(address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param vestingAmount vesting amount of the benefeciary to be recieved * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param interval The time period at which the tokens has to be vested * @param stamp the interval is in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y) * @param revocable whether the vesting is revocable or not */ function initialize( address beneficiary, uint256 vestingAmount, uint256 start, uint256 cliffDuration, uint256 duration, uint256 interval, string memory stamp, bool revocable ) public initializer { require( beneficiary != address(0), "VestingVault: beneficiary is the zero address" ); require(duration > 0, "VestingVault: duration is 0"); // solhint-disable-next-line max-line-length require( cliffDuration <= duration, "VestingVault: cliff is longer than duration" ); // solhint-disable-next-line max-line-length require( start.add(duration) > block.timestamp, "VestingVault: final time is before current time" ); require( keccak256(abi.encodePacked(stamp)) == keccak256("MIN") || keccak256(abi.encodePacked(stamp)) == keccak256("H") || keccak256(abi.encodePacked(stamp)) == keccak256("D") || keccak256(abi.encodePacked(stamp)) == keccak256("M") || keccak256(abi.encodePacked(stamp)) == keccak256("Y"), "VestingVault: Interval Stamp can be Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y)" ); uint256 interval_in_sec = getCalculatedIntervalInSeconds(interval, stamp); require( ((cliffDuration % interval_in_sec == 0) && (duration % interval_in_sec == 0)) , "VestingVault: duration & cliffDuration should multiplication of interval" ); Ownable.initialize(msg.sender); _beneficiary = beneficiary; _revocable = revocable; _vestingAmount = vestingAmount; _duration = duration; _cliff = start.add(cliffDuration); _interval = interval; _stamp = stamp; _start = start; _beneficiaryVerified = false; setCalculatedVestedAmountPerInterval(vestingAmount, duration, interval, stamp); } /** * @return the beneficiary of the tokens vesting. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the beneficiaryVerified of the tokens vesting. */ function beneficiaryVerified() public view returns (bool) { return _beneficiaryVerified; } /** * @return the vesting amount of the benefeciary. */ function vestingAmount() public view returns (uint256) { return _vestingAmount; } /** * @return the amount of token to be vested for the benefeciary per interval. */ function intervalVested() public view returns (uint256) { return _intervalVested; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the interval time of the token vesting in seconds. */ function interval() public view returns (uint256) { return _interval; } /** * @return the interval time is respect to Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function stamp() public view returns (string memory) { return _stamp; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasable(IERC20 token) public view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { require(_beneficiaryVerified == true, "VestingVault: Beneficiary signature not yet verified"); require(block.timestamp > _cliff, "VestingVault: you have not passed the lock period yet"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "VestingVault: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "VestingVault: cannot revoke"); require( !_revoked[address(token)], "VestingVault: token already revoked" ); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if ( block.timestamp >= _start.add(_duration) || _revoked[address(token)] ) { return totalBalance; } else { return getBatchTimestamp().mul(totalBalance).div(_duration); } } /** * @return Retrieves the duration passed from start till now according to interval in seconds. */ function getBatchTimestamp() private view returns (uint256) { require( block.timestamp > _start, "VestingVault: Current timestamp is smaller than start time" ); uint256 INTERVAL_TIMESTAMP = getCalculatedIntervalInSeconds(_interval,_stamp); uint256 ADJUSTED_INTERVAL = (block.timestamp.sub(_start)).div(INTERVAL_TIMESTAMP); uint256 START_TILL_NOW = ADJUSTED_INTERVAL.mul(INTERVAL_TIMESTAMP); return START_TILL_NOW; } /** * @return Timestamp in Interval. */ function getCalculatedIntervalInSeconds(uint256 interval__, string memory stamp__) public pure returns (uint256) { if (keccak256(abi.encodePacked(stamp__)) == keccak256("MIN")) { return (SECONDS_PER_MINUTE * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("H")) { return (SECONDS_PER_HOUR * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("D")) { return (SECONDS_PER_DAY * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("M")) { return (SECONDS_PER_MONTH * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("Y")) { return (SECONDS_PER_YEAR * interval__); } } /** * @dev Sets the calculated vesting amount per interval. * @param vestedAmount The total amount that is to be vested. * @param duration_ The total duration in which the veted tokens will be released. * @param interval_ The intervals at which the token will be released. * @param stamp_ The intervals mentioned are in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function setCalculatedVestedAmountPerInterval( uint256 vestedAmount, uint256 duration_, uint256 interval_, string memory stamp_ ) private { uint256 diff = vestedAmount; if (keccak256(abi.encodePacked(stamp_)) == keccak256("MIN")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MINUTE).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("H")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_HOUR).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("D")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_DAY).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("M")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MONTH).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("Y")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_YEAR).div(interval_)) ); } } function getVestedAmountNow() public view returns (uint256) { return getBatchTimestamp().mul(_vestingAmount).div(_duration); } function verifyAddress(bytes32 hash, bytes memory signature) public returns (bool) { // bytes32 tmpHash = toEthSignedMessageHash(hash); address tempAddress = recover(hash, signature); require(tempAddress == _beneficiary, "VestingVault: ECDSA Recover Failed, Beneficiary Address Signature is invalid"); _beneficiaryVerified = true; emit TokenVestingBeneficiaryVerified(_beneficiary); return true; } function recover(bytes32 hash, bytes memory signature) public pure returns (address) { return hash.recover(signature); } function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { return hash.toEthSignedMessageHash(); } uint256[50] private ______gap; }
* @dev Sets the calculated vesting amount per interval. @param vestedAmount The total amount that is to be vested. @param duration_ The total duration in which the veted tokens will be released. @param interval_ The intervals at which the token will be released. @param stamp_ The intervals mentioned are in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y)./
function setCalculatedVestedAmountPerInterval( uint256 vestedAmount, uint256 duration_, uint256 interval_, string memory stamp_ ) private { uint256 diff = vestedAmount; if (keccak256(abi.encodePacked(stamp_)) == keccak256("MIN")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MINUTE).div(interval_)) ); _intervalVested = ( diff.div(duration_.div(SECONDS_PER_HOUR).div(interval_)) ); _intervalVested = ( diff.div(duration_.div(SECONDS_PER_DAY).div(interval_)) ); _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MONTH).div(interval_)) ); _intervalVested = ( diff.div(duration_.div(SECONDS_PER_YEAR).div(interval_)) ); } }
485,365
[ 1, 2785, 326, 8894, 331, 10100, 3844, 1534, 3673, 18, 225, 331, 3149, 6275, 1021, 2078, 3844, 716, 353, 358, 506, 331, 3149, 18, 225, 3734, 67, 1021, 2078, 3734, 316, 1492, 326, 331, 278, 329, 2430, 903, 506, 15976, 18, 225, 3673, 67, 1021, 10389, 622, 1492, 326, 1147, 903, 506, 15976, 18, 225, 14429, 67, 1021, 10389, 27635, 854, 316, 5444, 993, 12, 6236, 13176, 14910, 12, 44, 13176, 9384, 12, 40, 13176, 19749, 12, 49, 13176, 21945, 12, 61, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4844, 690, 58, 3149, 6275, 2173, 4006, 12, 203, 3639, 2254, 5034, 331, 3149, 6275, 16, 203, 3639, 2254, 5034, 3734, 67, 16, 203, 3639, 2254, 5034, 3673, 67, 16, 203, 3639, 533, 3778, 14429, 67, 203, 565, 262, 3238, 288, 203, 3639, 2254, 5034, 3122, 273, 331, 3149, 6275, 31, 203, 203, 3639, 309, 261, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 14317, 67, 3719, 422, 417, 24410, 581, 5034, 2932, 6236, 6, 3719, 288, 203, 5411, 389, 6624, 58, 3149, 273, 261, 203, 7734, 3122, 18, 2892, 12, 8760, 27799, 2892, 12, 11609, 67, 3194, 67, 30090, 2934, 2892, 12, 6624, 67, 3719, 203, 5411, 11272, 203, 5411, 389, 6624, 58, 3149, 273, 261, 203, 7734, 3122, 18, 2892, 12, 8760, 27799, 2892, 12, 11609, 67, 3194, 67, 21372, 2934, 2892, 12, 6624, 67, 3719, 203, 5411, 11272, 203, 5411, 389, 6624, 58, 3149, 273, 261, 203, 7734, 3122, 18, 2892, 12, 8760, 27799, 2892, 12, 11609, 67, 3194, 67, 10339, 2934, 2892, 12, 6624, 67, 3719, 203, 5411, 11272, 203, 5411, 389, 6624, 58, 3149, 273, 261, 203, 7734, 3122, 18, 2892, 12, 8760, 27799, 2892, 12, 11609, 67, 3194, 67, 13942, 2934, 2892, 12, 6624, 67, 3719, 203, 5411, 11272, 203, 5411, 389, 6624, 58, 3149, 273, 261, 203, 7734, 3122, 18, 2892, 12, 8760, 27799, 2892, 12, 11609, 67, 3194, 67, 15137, 2934, 2892, 12, 6624, 67, 3719, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100 ]
./full_match/4/0xc746b7136B97AdAB08EeDe526345cCeaf554D4F3/sources/node_modules/_thirdweb-dev/contracts/feature/Royalty.sol
@dev Lets a contract admin update the default royalty recipient and bps.
function _setupDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) internal { if (_royaltyBps > 10_000) { revert Royalty__ExceedsMaxBps(_royaltyBps); } royaltyRecipient = _royaltyRecipient; royaltyBps = uint16(_royaltyBps); emit DefaultRoyalty(_royaltyRecipient, _royaltyBps); }
726,469
[ 1, 48, 2413, 279, 6835, 3981, 1089, 326, 805, 721, 93, 15006, 8027, 471, 324, 1121, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8401, 1868, 54, 13372, 15006, 966, 12, 2867, 389, 3800, 15006, 18241, 16, 2254, 5034, 389, 3800, 15006, 38, 1121, 13, 2713, 288, 203, 3639, 309, 261, 67, 3800, 15006, 38, 1121, 405, 1728, 67, 3784, 13, 288, 203, 5411, 15226, 534, 13372, 15006, 972, 424, 5288, 87, 2747, 38, 1121, 24899, 3800, 15006, 38, 1121, 1769, 203, 3639, 289, 203, 203, 3639, 721, 93, 15006, 18241, 273, 389, 3800, 15006, 18241, 31, 203, 3639, 721, 93, 15006, 38, 1121, 273, 2254, 2313, 24899, 3800, 15006, 38, 1121, 1769, 203, 203, 3639, 3626, 2989, 54, 13372, 15006, 24899, 3800, 15006, 18241, 16, 389, 3800, 15006, 38, 1121, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xaA3ac1c6c6c2938a607df7A7761C54D44DBC40c8/sources/UniswapV2Locker.sol
* @notice migrates liquidity to uniswap v3/ clean user storage
function migrate (address _lpToken, uint256 _index, uint256 _lockID, uint256 _amount) public { require(address(migrator) != address(0), "NOT SET"); require(_amount > 0, 'ZERO MIGRATION'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; userLock.amount = userLock.amount.sub(_amount); if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); } } TransferHelper.safeApprove(_lpToken, address(migrator), _amount); migrator.migrate(_lpToken, _amount, userLock.unlockDate, msg.sender); if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); } } TransferHelper.safeApprove(_lpToken, address(migrator), _amount); migrator.migrate(_lpToken, _amount, userLock.unlockDate, msg.sender); }
5,120,274
[ 1, 81, 2757, 815, 4501, 372, 24237, 358, 640, 291, 91, 438, 331, 23, 19, 2721, 729, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 13187, 261, 2867, 389, 9953, 1345, 16, 2254, 5034, 389, 1615, 16, 2254, 5034, 389, 739, 734, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 565, 2583, 12, 2867, 12, 81, 2757, 639, 13, 480, 1758, 12, 20, 3631, 315, 4400, 7855, 8863, 203, 565, 2583, 24899, 8949, 405, 374, 16, 296, 24968, 490, 3047, 24284, 8284, 203, 377, 203, 565, 2254, 5034, 2176, 734, 273, 3677, 63, 3576, 18, 15330, 8009, 23581, 1290, 1345, 63, 67, 9953, 1345, 6362, 67, 1615, 15533, 203, 565, 3155, 2531, 2502, 729, 2531, 273, 1147, 19159, 63, 67, 9953, 1345, 6362, 739, 734, 15533, 203, 565, 729, 2531, 18, 8949, 273, 729, 2531, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 377, 203, 565, 309, 261, 1355, 2531, 18, 8949, 422, 374, 13, 288, 203, 1377, 2254, 5034, 8526, 2502, 729, 19159, 273, 3677, 63, 3576, 18, 15330, 8009, 23581, 1290, 1345, 63, 67, 9953, 1345, 15533, 203, 1377, 729, 19159, 63, 67, 1615, 65, 273, 729, 19159, 63, 1355, 19159, 18, 2469, 17, 21, 15533, 203, 1377, 729, 19159, 18, 5120, 5621, 203, 1377, 309, 261, 1355, 19159, 18, 2469, 422, 374, 13, 288, 203, 3639, 3677, 63, 3576, 18, 15330, 8009, 15091, 5157, 18, 4479, 24899, 9953, 1345, 1769, 203, 1377, 289, 203, 565, 289, 203, 377, 203, 565, 12279, 2276, 18, 4626, 12053, 537, 24899, 9953, 1345, 16, 1758, 12, 81, 2757, 639, 3631, 389, 8949, 1769, 203, 565, 30188, 18, 22083, 24899, 9953, 1345, 16, 389, 8949, 16, 729, 2531, 2 ]
pragma solidity ^0.4.13; interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } contract NoRiskMgmt is RiskMgmtInterface { // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool) { return true; // For testing purposes } /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool) { return true; // For testing purposes } }
PUBLIC VIEW METHODS
contract NoRiskMgmt is RiskMgmtInterface { function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool) } { } function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool) { } }
14,888,630
[ 1, 14939, 21794, 10152, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2631, 54, 10175, 49, 7714, 353, 534, 10175, 49, 7714, 1358, 288, 203, 203, 203, 565, 445, 353, 6464, 31465, 12, 203, 3639, 2254, 1353, 5147, 16, 203, 3639, 2254, 2114, 5147, 16, 203, 3639, 1758, 357, 80, 6672, 16, 203, 3639, 1758, 30143, 6672, 16, 203, 3639, 2254, 357, 80, 12035, 16, 203, 3639, 2254, 30143, 12035, 203, 565, 262, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 97, 203, 565, 288, 203, 565, 289, 203, 203, 565, 445, 353, 13391, 31465, 12, 203, 3639, 2254, 1353, 5147, 16, 203, 3639, 2254, 2114, 5147, 16, 203, 3639, 1758, 357, 80, 6672, 16, 203, 3639, 1758, 30143, 6672, 16, 203, 3639, 2254, 357, 80, 12035, 16, 203, 3639, 2254, 30143, 12035, 203, 565, 262, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-26 */ // SPDX-License-Identifier: MIT // File: contracts/DateTime.sol pragma solidity ^0.8.0; // ---------------------------------------------------------------------------- // DateTime Library v2.0 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library DateTime { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.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 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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/TheDragonClub.sol pragma solidity ^0.8.4; contract TheDragonClub is ERC721A,Ownable,IERC2981 { using Address for address; using Strings for uint256; string public collectionName = "THE DRAGON CLUB NFT"; string public collectionSymbol = "TDCNFT"; string public baseExtension = ".json"; string private _baseUrl; string private _notRevealedUrl; uint256 public cost = 0.13 ether; uint256 public maxSupply = 8888; uint256 royaltyFee=500; uint256 private mintDate = DateTime.timestampFromDateTime(2022, 3, 27, 14, 0, 0); uint256 private revealDate = DateTime.timestampFromDateTime(2022, 4,6, 14, 0, 0); address royaltyAddress; bool public paused = true; address[] private _airdrops; address[] private _whitelist; constructor(string memory _base, string memory _notRevealed) ERC721A(collectionName, collectionSymbol) { setBaseUrl(_base); setNotRevealedUrl(_notRevealed); royaltyAddress=owner(); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { return (royaltyAddress, calculateRoyalty(_salePrice)); } function calculateRoyalty(uint256 _salePrice) public view returns (uint256) { return (_salePrice / 10000) * royaltyFee; } function supportsInterface(bytes4 interfaceId) public view override(ERC721A,IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function setMintDate(uint256 _year,uint256 _month,uint256 _day,uint256 _hour,uint256 _minute,uint256 _second) public onlyOwner { mintDate = DateTime.timestampFromDateTime(_year,_month,_day,_hour,_minute,_second); } function setRevealDate(uint256 _year,uint256 _month,uint256 _day,uint256 _hour,uint256 _minute,uint256 _second) public onlyOwner { revealDate = DateTime.timestampFromDateTime(_year,_month,_day,_hour,_minute,_second); } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool os,) = payable(owner()).call{value : address(this).balance}(""); require(os); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if(block.timestamp < revealDate) return _notRevealedUrl; return bytes(_baseUrl).length != 0 ? string(abi.encodePacked(_baseUrl, tokenId.toString(), baseExtension)) : ''; } function setBaseUrl(string memory _url) public onlyOwner { _baseUrl = _url; } function setNotRevealedUrl(string memory _url) public onlyOwner { _notRevealedUrl = _url; } function setAirDropAddresses(address[] memory addresses) public onlyOwner { _airdrops = addresses; } function listAirDropAddresses() public view onlyOwner returns (address[] memory) { return _airdrops; } function setWhitelist(address[] memory addresses) public onlyOwner { _whitelist = addresses; } function listWhitelist() public view onlyOwner returns (address[] memory) { return _whitelist; } function supply() public view returns (uint256) { return maxSupply - _totalMinted(); } function airdrop(uint256 quantity) external payable onlyOwner { require(_airdrops.length > 0,"Empty Airdrop List."); for (uint i = 0; i < _airdrops.length; i++) _safeMint(address(_airdrops[i]), quantity); } function mint(uint256 quantity) public payable { require(block.timestamp >= mintDate,"Not Yet The Public Sales Date.Stay Tuned."); require(paused == false,"Minting is Halted For a Moment, Please Try Again Later."); require(_totalMinted() + quantity <= maxSupply,"The Collection is Sold Out, Thank You For All Your Support."); require(quantity <= 10,"You Can Only Mint 10 Items A Time"); if (msg.sender != owner()) require(msg.value >= cost * quantity,"Insufficient Fund."); _safeMint(msg.sender, quantity); } }
------------------------------------------------------------------------ Calculate the number of days from 1970/01/01 to year/month/day using the date conversion algorithm from http:aa.usno.navy.mil/faq/docs/JD_Formula.php and subtracting the offset 2440588 so that 1970/01/01 is day 0 days = day - 32075 + 1461 * (year + 4800 + (month - 14) / 12) / 4 + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 - offset ------------------------------------------------------------------------
library DateTime { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; daysInMonth = 30; daysInMonth = _isLeapYear(year) ? 29 : 28; } } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; daysInMonth = 30; daysInMonth = _isLeapYear(year) ? 29 : 28; } } } else if (month != 2) { } else { function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
2,208,267
[ 1, 29461, 9029, 326, 1300, 434, 4681, 628, 5342, 7301, 19, 1611, 19, 1611, 358, 3286, 19, 7496, 19, 2881, 1450, 326, 1509, 4105, 4886, 628, 282, 1062, 30, 7598, 18, 407, 2135, 18, 11589, 93, 18, 81, 330, 19, 507, 85, 19, 8532, 19, 46, 40, 67, 14972, 18, 2684, 471, 10418, 310, 326, 1384, 4248, 24, 6260, 5482, 1427, 716, 5342, 7301, 19, 1611, 19, 1611, 353, 2548, 374, 4681, 273, 2548, 1377, 300, 890, 3462, 5877, 1377, 397, 5045, 9498, 225, 261, 6874, 397, 9934, 713, 397, 261, 7496, 300, 5045, 13, 342, 2593, 13, 342, 1059, 1377, 397, 6580, 27, 225, 261, 7496, 300, 576, 300, 261, 7496, 300, 5045, 13, 342, 2593, 225, 2593, 13, 342, 2593, 1377, 300, 890, 225, 14015, 6874, 397, 17160, 713, 397, 261, 7496, 300, 5045, 13, 342, 2593, 13, 342, 2130, 13, 342, 1059, 1377, 300, 1384, 8879, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 3716, 288, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 10339, 273, 4248, 380, 4752, 380, 4752, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 21372, 273, 4752, 380, 4752, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 30090, 273, 4752, 31, 203, 565, 509, 5034, 5381, 26019, 31728, 11664, 1611, 273, 4248, 24, 6260, 5482, 31, 203, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 17667, 273, 404, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 56, 1821, 273, 576, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 59, 2056, 273, 890, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 2455, 57, 273, 1059, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 42, 2259, 273, 1381, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 55, 789, 273, 1666, 31, 203, 565, 2254, 5034, 5381, 5467, 59, 67, 55, 2124, 273, 2371, 31, 203, 203, 565, 445, 389, 9810, 1265, 1626, 12, 203, 3639, 2254, 5034, 3286, 16, 203, 3639, 2254, 5034, 3138, 16, 203, 3639, 2254, 5034, 2548, 203, 203, 203, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 389, 9810, 13, 288, 203, 3639, 2583, 12, 6874, 1545, 5342, 7301, 1769, 203, 3639, 509, 5034, 389, 6874, 273, 509, 5034, 12, 6874, 1769, 203, 3639, 509, 5034, 389, 7496, 273, 509, 5034, 12, 7496, 1769, 203, 3639, 509, 5034, 389, 2881, 273, 509, 5034, 12, 2881, 1769, 203, 203, 3639, 509, 5034, 1001, 9810, 273, 203, 3639, 389, 2881, 300, 2 ]
./full_match/80001/0x8D2C372317524a8Af5313883434411fd3DAE55d9/sources/contracts/lib/OrderFulfiller.sol
* @dev Internal pure function to convert an order to an advanced order with numerator and denominator of 1 and empty extraData. @param order The order to convert. @return advancedOrder The new advanced order./ Convert to partial order (1/1 or full fill) and return new value.
function _convertOrderToAdvanced(Order calldata order) internal pure returns (AdvancedOrder memory advancedOrder) { advancedOrder = AdvancedOrder( order.parameters, 1, 1, order.signature, "" ); }
878,373
[ 1, 3061, 16618, 445, 358, 1765, 392, 1353, 358, 392, 16111, 1353, 598, 1377, 16730, 471, 15030, 434, 404, 471, 1008, 2870, 751, 18, 225, 1353, 1021, 1353, 358, 1765, 18, 327, 16111, 2448, 1021, 394, 16111, 1353, 18, 19, 4037, 358, 4702, 1353, 261, 21, 19, 21, 578, 1983, 3636, 13, 471, 327, 394, 460, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6283, 2448, 774, 23618, 12, 2448, 745, 892, 1353, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 23618, 2448, 3778, 16111, 2448, 13, 203, 565, 288, 203, 3639, 16111, 2448, 273, 27451, 2448, 12, 203, 5411, 1353, 18, 3977, 16, 203, 5411, 404, 16, 203, 5411, 404, 16, 203, 5411, 1353, 18, 8195, 16, 203, 5411, 1408, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x70588Eb4626600e6b9cD49b140E39e5a814D9535/sources/erc721bo/contracts/ERC721BO.sol
* @dev Same as `_safeReMint`, with an additional `data` parameter which is forwarded in IERC721Receiver.onERC721Received to contract recipients./
function _safeReMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _remint(to, tokenId); if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); }
3,053,407
[ 1, 8650, 487, 1375, 67, 4626, 426, 49, 474, 9191, 598, 392, 3312, 1375, 892, 68, 1569, 1492, 353, 19683, 316, 467, 654, 39, 27, 5340, 12952, 18, 265, 654, 39, 27, 5340, 8872, 358, 6835, 12045, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4626, 426, 49, 474, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 2713, 5024, 288, 203, 3639, 389, 2764, 474, 12, 869, 16, 1147, 548, 1769, 203, 3639, 309, 16051, 67, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 16, 389, 892, 3719, 203, 5411, 15226, 12279, 774, 3989, 654, 39, 27, 5340, 12952, 5726, 264, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x921331433c9167F0EcD95F5E6841C032843Ce130/sources/project_/contracts/STokenV1.sol
@notice Locks `_amountToLock` of tokens on `_account` address for the `_daysToLock` quantity of days @dev Allowed only for FinancialManager. Function blocked when contract is paused. The proper pair of data: ([0]timestamp when tokens can be unlocked & [1]`_amountToLock`) is written to the parametr of account: {personalLockUps} Function checks the opportunity to lock `_amountToLock`=> see comments to function {_checkAmountToLock} to know how is it checked. And lock `_amountToLock` of tokens or the whole available balance of `_account`. @param _account address on which tokens will be locked @param _amountToLock amount of tokens to lock @param _daysToLock the quantity of days you want to lock tokens for @return true if function passed successfully
function lockUpTokensOnAddress( address _account, uint256 _amountToLock, uint256 _daysToLock ) external whenNotPaused onlyFinancialManager returns (bool) { _lockTokens( _account, _checkAmountToLock(_account, _amountToLock), _daysToLock ); return true; }
5,596,194
[ 1, 19159, 1375, 67, 8949, 774, 2531, 68, 434, 2430, 603, 1375, 67, 4631, 68, 1758, 540, 364, 326, 1375, 67, 9810, 774, 2531, 68, 10457, 434, 4681, 225, 16740, 1338, 364, 9458, 19292, 649, 1318, 18, 1377, 4284, 14547, 1347, 6835, 353, 17781, 18, 1377, 1021, 5338, 3082, 434, 501, 30, 23265, 20, 65, 5508, 1347, 2430, 848, 506, 25966, 473, 306, 21, 65, 68, 67, 8949, 774, 2531, 24065, 1377, 353, 5941, 358, 326, 579, 16354, 434, 2236, 30, 288, 29991, 2531, 57, 1121, 97, 1377, 4284, 4271, 326, 1061, 655, 13352, 358, 2176, 1375, 67, 8949, 774, 2531, 68, 9207, 2621, 1377, 5678, 358, 445, 288, 67, 1893, 6275, 774, 2531, 97, 358, 5055, 3661, 353, 518, 5950, 18, 1377, 7835, 2176, 1375, 67, 8949, 774, 2531, 68, 434, 2430, 578, 326, 7339, 2319, 11013, 434, 1375, 67, 4631, 8338, 225, 389, 4631, 1758, 603, 1492, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 2176, 1211, 5157, 1398, 1887, 12, 203, 3639, 1758, 389, 4631, 16, 203, 3639, 2254, 5034, 389, 8949, 774, 2531, 16, 203, 3639, 2254, 5034, 389, 9810, 774, 2531, 203, 565, 262, 3903, 1347, 1248, 28590, 1338, 6187, 19292, 649, 1318, 1135, 261, 6430, 13, 288, 203, 3639, 389, 739, 5157, 12, 203, 5411, 389, 4631, 16, 203, 5411, 389, 1893, 6275, 774, 2531, 24899, 4631, 16, 389, 8949, 774, 2531, 3631, 203, 5411, 389, 9810, 774, 2531, 203, 3639, 11272, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xd454B7aa75654b8718A9279879aD165703d7fE68/sources/TestCoin0.sol
/Connect /fix => Crypto Block Mine Token to => Mainnet => "CBM" Coin
tokenSymbol = "TC0";
5,095,791
[ 1, 19, 5215, 342, 904, 516, 15629, 3914, 490, 558, 3155, 358, 516, 12740, 2758, 225, 516, 315, 8876, 49, 6, 28932, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 5335, 282, 273, 315, 15988, 20, 14432, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // ---------------------------------------------------------------------------- // @Name SafeMath // @Desc Math operations with safety checks that throw on error // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/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't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // @Name YouRyuCoinBase // @Desc ERC20-based token // ---------------------------------------------------------------------------- contract SaromsaryCoinBase is ERC20Interface { using SafeMath for uint; uint _totalSupply; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowed; function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return _balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return _allowed[tokenOwner][spender]; } function transfer(address to, uint tokens) public returns (bool success) { require( _balances[msg.sender] >= tokens); _balances[msg.sender] = _balances[msg.sender].sub(tokens); _balances[to] = _balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { _allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(tokens <= _balances[from]); require(tokens <= _allowed[from][msg.sender]); _balances[from] = _balances[from].sub(tokens); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(tokens); _balances[to] = _balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } } // ---------------------------------------------------------------------------- // @Name YouRyuCoin (YRC) // @Desc Cutie Ryu // ---------------------------------------------------------------------------- contract SaromsaryCoin is SaromsaryCoinBase { string public name; uint8 public decimals; string public symbol; // Admin Ryu Address address public owner; modifier isOwner { require(owner == msg.sender); _; } event EventBurnCoin(address a_burnAddress, uint a_amount); event EventAddCoin(uint a_amount, uint a_totalSupply); function SaromsaryCoin(uint a_totalSupply, string a_tokenName, string a_tokenSymbol, uint8 a_decimals) public { owner = msg.sender; _totalSupply = a_totalSupply; _balances[msg.sender] = a_totalSupply; name = a_tokenName; symbol = a_tokenSymbol; decimals = a_decimals; } function burnCoin(uint a_coinAmount) external isOwner { require(_balances[msg.sender] >= a_coinAmount); _balances[msg.sender] = _balances[msg.sender].sub(a_coinAmount); _totalSupply = _totalSupply.sub(a_coinAmount); emit EventBurnCoin(msg.sender, a_coinAmount); } function addCoin(uint a_coinAmount) external isOwner { _balances[msg.sender] = _balances[msg.sender].add(a_coinAmount); _totalSupply = _totalSupply.add(a_coinAmount); emit EventAddCoin(a_coinAmount, _totalSupply); } }
---------------------------------------------------------------------------- @Name YouRyuCoin (YRC) @Desc Cutie Ryu ---------------------------------------------------------------------------- Admin Ryu Address
contract SaromsaryCoin is SaromsaryCoinBase { string public name; uint8 public decimals; string public symbol; address public owner; modifier isOwner { require(owner == msg.sender); _; } event EventBurnCoin(address a_burnAddress, uint a_amount); event EventAddCoin(uint a_amount, uint a_totalSupply); function SaromsaryCoin(uint a_totalSupply, string a_tokenName, string a_tokenSymbol, uint8 a_decimals) public { owner = msg.sender; _totalSupply = a_totalSupply; _balances[msg.sender] = a_totalSupply; name = a_tokenName; symbol = a_tokenSymbol; decimals = a_decimals; } function burnCoin(uint a_coinAmount) external isOwner { require(_balances[msg.sender] >= a_coinAmount); _balances[msg.sender] = _balances[msg.sender].sub(a_coinAmount); _totalSupply = _totalSupply.sub(a_coinAmount); emit EventBurnCoin(msg.sender, a_coinAmount); } function addCoin(uint a_coinAmount) external isOwner { _balances[msg.sender] = _balances[msg.sender].add(a_coinAmount); _totalSupply = _totalSupply.add(a_coinAmount); emit EventAddCoin(a_coinAmount, _totalSupply); } }
1,805,146
[ 1, 5802, 7620, 632, 461, 4554, 54, 93, 89, 27055, 261, 61, 11529, 13, 632, 4217, 385, 322, 1385, 534, 93, 89, 8879, 13849, 7807, 534, 93, 89, 5267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 297, 25390, 814, 27055, 353, 348, 297, 25390, 814, 27055, 2171, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 203, 565, 9606, 353, 5541, 288, 203, 3639, 2583, 12, 8443, 422, 1234, 18, 15330, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 871, 2587, 38, 321, 27055, 12, 2867, 279, 67, 70, 321, 1887, 16, 2254, 279, 67, 8949, 1769, 203, 565, 871, 2587, 986, 27055, 12, 11890, 279, 67, 8949, 16, 2254, 279, 67, 4963, 3088, 1283, 1769, 203, 203, 377, 445, 348, 297, 25390, 814, 27055, 12, 11890, 279, 67, 4963, 3088, 1283, 16, 533, 279, 67, 2316, 461, 16, 533, 279, 67, 2316, 5335, 16, 2254, 28, 279, 67, 31734, 13, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 389, 4963, 3088, 1283, 273, 279, 67, 4963, 3088, 1283, 31, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 279, 67, 4963, 3088, 1283, 31, 203, 203, 3639, 508, 273, 279, 67, 2316, 461, 31, 203, 3639, 3273, 273, 279, 67, 2316, 5335, 31, 203, 3639, 15105, 273, 279, 67, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 18305, 27055, 12, 11890, 279, 67, 12645, 6275, 13, 3903, 353, 5541, 203, 565, 288, 203, 3639, 2583, 24899, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 279, 67, 12645, 6275, 1769, 203, 203, 3639, 389, 70, 26488, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./libs/IUpgradedStandardToken.sol"; import "./BlackList.sol"; contract SperaV3 is Initializable, OwnableUpgradeable, PausableUpgradeable, BlackList, ERC20Upgradeable { // Called when new token are issued event Issue(uint256 amount); // Called when tokens are redeemed event Redeem(uint256 amount); // Called when contract is deprecated event Deprecate(address newAddress); address public upgradedAddress; bool public deprecated; function initialize() public initializer { __ERC20_init("Spera", "SPRA"); _mint(msg.sender, 10000000000000000000); __Ownable_init(); } function destroyBlackFunds(address _blackListedUser) public override onlyOwner { require(isBlackListed[_blackListedUser]); uint256 dirtyFunds = balanceOf(_blackListedUser); _burn(_blackListedUser, dirtyFunds); emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint256 _value) public override whenNotPaused returns (bool) { require(!isBlackListed[msg.sender], "Blacklisted Member"); if (deprecated) { IUpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { super.transfer(_to, _value); } return true; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom( address _from, address _to, uint256 _value ) public override whenNotPaused returns (bool) { require(!isBlackListed[_from], "Blacklisted Member"); if (deprecated) { IUpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { super.transferFrom(_from, _to, _value); } return true; } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public view override returns (uint256) { if (deprecated) { return IERC20Upgradeable(upgradedAddress).totalSupply(); } else { return super.totalSupply(); } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint256 amount) whenNotPaused external onlyOwner { require(totalSupply() + amount > totalSupply(), "Invalide value"); uint256 addValue; bool addBoolValue; (addBoolValue, addValue) = SafeMathUpgradeable.tryAdd(balanceOf(owner()), amount); require(addBoolValue &&(addValue > balanceOf(owner())), "Invalide value"); _mint(owner(), amount); emit Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint256 amount) public onlyOwner { require(balanceOf(owner()) >= amount); _burn(owner(), amount); emit Redeem(amount); } // Pause functions from Pausable.sol contract function pause() public onlyOwner{ _pause(); } // Unpause functions from Pausable.sol contract function unpause() public onlyOwner{ _unpause(); } // minting function to mint the coin function mint(uint256 amount, address recipient) public onlyOwner whenNotPaused{ _mint(recipient, amount); } // burning function to burn the coin function burn(address account, uint256 amount) public onlyOwner whenNotPaused{ _burn(account, amount); } } // 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @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[45] private __gap; } // 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 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library 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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the UpgradedStandardToken standard as defined in the EIP. */ interface IUpgradedStandardToken { // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy( address from, address to, uint256 value ) external; function transferFromByLegacy( address sender, address from, address spender, uint256 value ) external; function approveByLegacy( address from, address spender, uint256 value ) external; function balanceOf(address _owner) external view returns (uint256 balance); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract BlackList is OwnableUpgradeable { event DestroyedBlackFunds(address _blackListedUser, uint256 _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); mapping(address => bool) public isBlackListed; /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) /////// function getBlackListStatus(address _maker) external view returns (bool) { return isBlackListed[_maker]; } function getOwner() external view returns (address) { return owner(); } function addBlackList(address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); } function removeBlackList(address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); } function destroyBlackFunds(address _blackListedUser) public virtual onlyOwner {} } // 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) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
* @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./ SPDX-License-Identifier: MIT OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.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] ``` constructor() initializer {} ``` ====/
abstract contract Initializable { bool private _initialized; bool private _initializing; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount uint256[45] private __gap; } pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; modifier initializer() { require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount uint256[45] private __gap; } pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; modifier initializer() { require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount uint256[45] private __gap; } pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; modifier initializer() { require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } }
6,231,968
[ 1, 2503, 1008, 8735, 3476, 353, 1378, 316, 3166, 358, 1699, 3563, 5244, 358, 527, 394, 3152, 2887, 699, 430, 1787, 2588, 2502, 316, 326, 16334, 2687, 18, 19, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 3502, 62, 881, 84, 292, 267, 30131, 261, 2722, 3526, 331, 24, 18, 25, 18, 20, 13, 261, 5656, 19, 5471, 19, 4435, 6934, 18, 18281, 13, 225, 1220, 353, 279, 1026, 6835, 358, 20702, 316, 7410, 8400, 429, 20092, 16, 578, 1281, 3846, 434, 6835, 716, 903, 506, 19357, 21478, 279, 2889, 18, 7897, 21875, 20092, 741, 486, 1221, 999, 434, 279, 3885, 16, 518, 1807, 2975, 358, 3635, 3885, 4058, 358, 392, 3903, 12562, 445, 16, 11234, 2566, 1375, 11160, 8338, 2597, 1508, 12724, 4573, 358, 17151, 333, 12562, 445, 1427, 518, 848, 1338, 506, 2566, 3647, 18, 1021, 288, 22181, 97, 9606, 2112, 635, 333, 6835, 903, 1240, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 10188, 6934, 288, 203, 565, 1426, 3238, 389, 13227, 31, 203, 203, 565, 1426, 3238, 389, 6769, 6894, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 2254, 5034, 63, 7950, 65, 3238, 1001, 14048, 31, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 16644, 5471, 19, 1887, 10784, 429, 18, 18281, 14432, 203, 203, 565, 9606, 12562, 1435, 288, 203, 3639, 2583, 24899, 6769, 6894, 692, 389, 291, 6293, 1435, 294, 401, 67, 13227, 16, 315, 4435, 6934, 30, 6835, 353, 1818, 6454, 8863, 203, 203, 3639, 1426, 353, 27046, 1477, 273, 401, 67, 6769, 6894, 31, 203, 3639, 309, 261, 291, 27046, 1477, 13, 288, 203, 5411, 389, 6769, 6894, 273, 638, 31, 203, 5411, 389, 13227, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 389, 31, 203, 203, 3639, 309, 261, 291, 27046, 1477, 13, 288, 203, 5411, 389, 6769, 6894, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 2 ]
pragma solidity 0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } /* Copyright 2016, Jordi Baylina 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/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.2'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // 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((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints /// PURE function function min(uint a, uint b) internal constant returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract StakeTreeWithTokenization { using SafeMath for uint256; uint public version = 2; struct Funder { bool exists; uint balance; uint withdrawalEntry; uint contribution; uint contributionClaimed; } mapping(address => Funder) public funders; bool public live = true; // For sunsetting contract uint public totalCurrentFunders = 0; // Keeps track of total funders uint public withdrawalCounter = 0; // Keeps track of how many withdrawals have taken place uint public sunsetWithdrawDate; MiniMeToken public tokenContract; MiniMeTokenFactory public tokenFactory; bool public tokenized = false; bool public canClaimTokens = false; address public beneficiary; // Address for beneficiary uint public sunsetWithdrawalPeriod; // How long it takes for beneficiary to swipe contract when put into sunset mode uint public withdrawalPeriod; // How long the beneficiary has to wait withdraw uint public minimumFundingAmount; // Setting used for setting minimum amounts to fund contract with uint public lastWithdrawal; // Last withdrawal time uint public nextWithdrawal; // Next withdrawal time uint public contractStartTime; // For accounting purposes event Payment(address indexed funder, uint amount); event Refund(address indexed funder, uint amount); event Withdrawal(uint amount); event TokensClaimed(address indexed funder, uint amount); event Sunset(bool hasSunset); function StakeTreeWithTokenization( address beneficiaryAddress, uint withdrawalPeriodInit, uint withdrawalStart, uint sunsetWithdrawPeriodInit, uint minimumFundingAmountInit) { beneficiary = beneficiaryAddress; withdrawalPeriod = withdrawalPeriodInit; sunsetWithdrawalPeriod = sunsetWithdrawPeriodInit; lastWithdrawal = withdrawalStart; nextWithdrawal = lastWithdrawal + withdrawalPeriod; minimumFundingAmount = minimumFundingAmountInit; contractStartTime = now; } // Modifiers modifier onlyByBeneficiary() { require(msg.sender == beneficiary); _; } modifier onlyWhenTokenized() { require(isTokenized()); _; } modifier onlyByFunder() { require(isFunder(msg.sender)); _; } modifier onlyAfterNextWithdrawalDate() { require(now >= nextWithdrawal); _; } modifier onlyWhenLive() { require(live); _; } modifier onlyWhenSunset() { require(!live); _; } /* * External accounts can pay directly to contract to fund it. */ function () payable { fund(); } /* * Additional api for contracts to use as well * Can only happen when live and over a minimum amount set by the beneficiary */ function fund() public payable onlyWhenLive { require(msg.value >= minimumFundingAmount); // Only increase total funders when we have a new funder if(!isFunder(msg.sender)) { totalCurrentFunders = totalCurrentFunders.add(1); // Increase total funder count funders[msg.sender] = Funder({ exists: true, balance: msg.value, withdrawalEntry: withdrawalCounter, // Set the withdrawal counter. Ie at which withdrawal the funder "entered" the patronage contract contribution: 0, contributionClaimed: 0 }); } else { consolidateFunder(msg.sender, msg.value); } Payment(msg.sender, msg.value); } // Pure functions /* * This function calculates how much the beneficiary can withdraw. * Due to no floating points in Solidity, we will lose some fidelity * if there's wei on the last digit. The beneficiary loses a neglibible amount * to withdraw but this benefits the beneficiary again on later withdrawals. * We multiply by 10 (which corresponds to the 10%) * then divide by 100 to get the actual part. */ function calculateWithdrawalAmount(uint startAmount) public returns (uint){ return startAmount.mul(10).div(100); // 10% } /* * This function calculates the refund amount for the funder. * Due to no floating points in Solidity, we will lose some fidelity. * The funder loses a neglibible amount to refund. * The left over wei gets pooled to the fund. */ function calculateRefundAmount(uint amount, uint withdrawalTimes) public returns (uint) { for(uint i=0; i<withdrawalTimes; i++){ amount = amount.mul(9).div(10); } return amount; } // Getter functions /* * To calculate the refund amount we look at how many times the beneficiary * has withdrawn since the funder added their funds. * We use that deduct 10% for each withdrawal. */ function getRefundAmountForFunder(address addr) public constant returns (uint) { // Only calculate on-the-fly if funder has not been updated if(shouldUpdateFunder(addr)) { uint amount = funders[addr].balance; uint withdrawalTimes = getHowManyWithdrawalsForFunder(addr); return calculateRefundAmount(amount, withdrawalTimes); } else { return funders[addr].balance; } } function getFunderContribution(address funder) public constant returns (uint) { // Only calculate on-the-fly if funder has not been updated if(shouldUpdateFunder(funder)) { uint oldBalance = funders[funder].balance; uint newBalance = getRefundAmountForFunder(funder); uint contribution = oldBalance.sub(newBalance); return funders[funder].contribution.add(contribution); } else { return funders[funder].contribution; } } function getBeneficiary() public constant returns (address) { return beneficiary; } function getCurrentTotalFunders() public constant returns (uint) { return totalCurrentFunders; } function getWithdrawalCounter() public constant returns (uint) { return withdrawalCounter; } function getWithdrawalEntryForFunder(address addr) public constant returns (uint) { return funders[addr].withdrawalEntry; } function getContractBalance() public constant returns (uint256 balance) { balance = this.balance; } function getFunderBalance(address funder) public constant returns (uint256) { return getRefundAmountForFunder(funder); } function getFunderContributionClaimed(address addr) public constant returns (uint) { return funders[addr].contributionClaimed; } function isFunder(address addr) public constant returns (bool) { return funders[addr].exists; } function isTokenized() public constant returns (bool) { return tokenized; } function shouldUpdateFunder(address funder) public constant returns (bool) { return getWithdrawalEntryForFunder(funder) < withdrawalCounter; } function getHowManyWithdrawalsForFunder(address addr) private constant returns (uint) { return withdrawalCounter.sub(getWithdrawalEntryForFunder(addr)); } // State changing functions function setMinimumFundingAmount(uint amount) external onlyByBeneficiary { require(amount > 0); minimumFundingAmount = amount; } function withdraw() external onlyByBeneficiary onlyAfterNextWithdrawalDate onlyWhenLive { // Check uint amount = calculateWithdrawalAmount(this.balance); // Effects withdrawalCounter = withdrawalCounter.add(1); lastWithdrawal = now; // For tracking purposes nextWithdrawal = nextWithdrawal + withdrawalPeriod; // Fixed period increase // Interaction beneficiary.transfer(amount); Withdrawal(amount); } // Refunding by funder // Only funders can refund their own funding // Can only be sent back to the same address it was funded with // We also remove the funder if they succesfully exit with their funds function refund() external onlyByFunder { // Check uint walletBalance = this.balance; uint amount = getRefundAmountForFunder(msg.sender); require(amount > 0); // Effects removeFunder(); // Interaction msg.sender.transfer(amount); Refund(msg.sender, amount); // Make sure this worked as intended assert(this.balance == walletBalance-amount); } // Used when the funder wants to remove themselves as a funder // without refunding. Their eth stays in the pool function removeFunder() public onlyByFunder { delete funders[msg.sender]; totalCurrentFunders = totalCurrentFunders.sub(1); } /* * This is a bookkeeping function which updates the state for the funder * when top up their funds. */ function consolidateFunder(address funder, uint newPayment) private { // Update contribution funders[funder].contribution = getFunderContribution(funder); // Update balance funders[funder].balance = getRefundAmountForFunder(funder).add(newPayment); // Update withdrawal entry funders[funder].withdrawalEntry = withdrawalCounter; } function addTokenization(string tokenName, string tokenSymbol, uint8 tokenDecimals ) external onlyByBeneficiary { require(!isTokenized()); tokenFactory = new MiniMeTokenFactory(); tokenContract = tokenFactory.createCloneToken(0x0, 0, tokenName, tokenDecimals, tokenSymbol, true); tokenized = true; canClaimTokens = true; } function claimTokens() external onlyByFunder onlyWhenTokenized { require(canClaimTokens); uint contributionAmount = getFunderContribution(msg.sender); uint contributionClaimedAmount = getFunderContributionClaimed(msg.sender); // Only claim tokens if they have some left to claim uint claimAmount = contributionAmount.sub(contributionClaimedAmount); require(claimAmount > 0); // Claim tokens funders[msg.sender].contributionClaimed = contributionAmount; tokenContract.generateTokens(msg.sender, claimAmount); TokensClaimed(msg.sender, claimAmount); } /* * The beneficiary can stop/enable funders from claiming more tokens. * This opens up opportunities for tokenizing only happening for a set periods. */ function enableTokenClaiming(bool _enabled) external onlyWhenTokenized onlyByBeneficiary { canClaimTokens = _enabled; } /* --- Sunsetting --- */ /* * The beneficiary can decide to stop using this contract. * They use this sunset function to put it into sunset mode. * The beneficiary can then swipe rest of the funds after a set time * if funders have not withdrawn their funds. */ function sunset() external onlyByBeneficiary onlyWhenLive { sunsetWithdrawDate = now.add(sunsetWithdrawalPeriod); live = false; Sunset(true); } function swipe(address recipient) external onlyWhenSunset onlyByBeneficiary { require(now >= sunsetWithdrawDate); recipient.transfer(this.balance); } /* --- Token Contract Forwarding Controller Functions --- */ /* * Allows beneficiary to call two additional functions on the token contract: * claimTokens * enabledTransfers * */ function tokenContractClaimTokens(address _token) onlyByBeneficiary onlyWhenTokenized { tokenContract.claimTokens(_token); } function tokenContractEnableTransfers(bool _transfersEnabled) onlyByBeneficiary onlyWhenTokenized { tokenContract.enableTransfers(_transfersEnabled); } }
Only increase total funders when we have a new funder
function fund() public payable onlyWhenLive { require(msg.value >= minimumFundingAmount); if(!isFunder(msg.sender)) { funders[msg.sender] = Funder({ exists: true, balance: msg.value, contribution: 0, contributionClaimed: 0 }); } else { consolidateFunder(msg.sender, msg.value); } Payment(msg.sender, msg.value); }
7,211,559
[ 1, 3386, 10929, 2078, 284, 26843, 1347, 732, 1240, 279, 394, 284, 9341, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 284, 1074, 1435, 1071, 8843, 429, 1338, 9434, 12328, 288, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 5224, 42, 14351, 6275, 1769, 203, 203, 565, 309, 12, 5, 291, 42, 9341, 12, 3576, 18, 15330, 3719, 288, 203, 203, 1377, 284, 26843, 63, 3576, 18, 15330, 65, 273, 478, 9341, 12590, 203, 3639, 1704, 30, 638, 16, 203, 3639, 11013, 30, 1234, 18, 1132, 16, 203, 3639, 24880, 30, 374, 16, 203, 3639, 24880, 9762, 329, 30, 374, 203, 1377, 15549, 203, 565, 289, 203, 565, 469, 288, 7010, 1377, 21785, 340, 42, 9341, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 12022, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC383372e5B69fc487374b91298D124820132c567/sources/src/token/erc721/LazyMintAdventureERC721.sol
@notice Similar to {IERC721-setApprovalForAll}, but for special in-game adventures only
function setAdventuresApprovedForAll(address operator, bool approved) external { address tokenOwner = _msgSender(); if(tokenOwner == operator) { revert LazyMintAdventureBase__AdventureApprovalToCaller(); } operatorAdventureApprovals[tokenOwner][operator] = approved; emit AdventureApprovalForAll(tokenOwner, operator, approved); }
8,311,107
[ 1, 16891, 358, 288, 45, 654, 39, 27, 5340, 17, 542, 23461, 1290, 1595, 5779, 1496, 364, 4582, 316, 17, 13957, 1261, 616, 1823, 1338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1871, 616, 1823, 31639, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 3903, 288, 203, 3639, 1758, 1147, 5541, 273, 389, 3576, 12021, 5621, 203, 203, 3639, 309, 12, 2316, 5541, 422, 3726, 13, 288, 203, 5411, 15226, 12805, 49, 474, 1871, 616, 594, 2171, 972, 1871, 616, 594, 23461, 774, 11095, 5621, 203, 3639, 289, 203, 3639, 3726, 1871, 616, 594, 12053, 4524, 63, 2316, 5541, 6362, 9497, 65, 273, 20412, 31, 203, 3639, 3626, 4052, 616, 594, 23461, 1290, 1595, 12, 2316, 5541, 16, 3726, 16, 20412, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Creator: Chiru 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'; /** * UUUUUUUU UUUUUUUU AAA WWWWWWWW WWWWWWWW AAA RRRRRRRRRRRRRRRRR 222222222222222 222222222222222 U::::::U U::::::U A:::A W::::::W W::::::W A:::A R::::::::::::::::R 2:::::::::::::::22 2:::::::::::::::22 U::::::U U::::::U A:::::A W::::::W W::::::W A:::::A R::::::RRRRRR:::::R 2::::::222222:::::2 2::::::222222:::::2 UU:::::U U:::::UU A:::::::A W::::::W W::::::WA:::::::A RR:::::R R:::::R 2222222 2:::::2 2222222 2:::::2 U:::::U U:::::U A:::::::::A W:::::W WWWWW W:::::WA:::::::::A R::::R R:::::R 2:::::2 2:::::2 U:::::D D:::::U A:::::A:::::A W:::::W W:::::W W:::::WA:::::A:::::A R::::R R:::::R 2:::::2 2:::::2 U:::::D D:::::U A:::::A A:::::A W:::::W W:::::::W W:::::WA:::::A A:::::A R::::RRRRRR:::::R 2222::::2 2222::::2 U:::::D D:::::U A:::::A A:::::A W:::::W W:::::::::W W:::::WA:::::A A:::::A R:::::::::::::RR 22222::::::22 22222::::::22 U:::::D D:::::U A:::::A A:::::A W:::::W W:::::W:::::W W:::::WA:::::A A:::::A R::::RRRRRR:::::R 22::::::::222 22::::::::222 U:::::D D:::::U A:::::AAAAAAAAA:::::A W:::::W W:::::W W:::::W W:::::WA:::::AAAAAAAAA:::::A R::::R R:::::R 2:::::22222 2:::::22222 U:::::D D:::::U A:::::::::::::::::::::A W:::::W:::::W W:::::W:::::WA:::::::::::::::::::::A R::::R R:::::R 2:::::2 2:::::2 U::::::U U::::::U A:::::AAAAAAAAAAAAA:::::A W:::::::::W W:::::::::WA:::::AAAAAAAAAAAAA:::::A R::::R R:::::R 2:::::2 2:::::2 U:::::::UUU:::::::UA:::::A A:::::A W:::::::W W:::::::WA:::::A A:::::A RR:::::R R:::::R 2:::::2 2222222:::::2 222222 UU:::::::::::::UUA:::::A A:::::A W:::::W W:::::WA:::::A A:::::A R::::::R R:::::R 2::::::2222222:::::22::::::2222222:::::2 UU:::::::::UU A:::::A A:::::A W:::W W:::WA:::::A A:::::A R::::::R R:::::R 2::::::::::::::::::22::::::::::::::::::2 UUUUUUUUU AAAAAAA AAAAAAA WWW WWWAAAAAAA AAAAAAARRRRRRRR RRRRRRR 2222222222222222222222222222222222222222 * **/ contract UAWAR22 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // mint price uint256 public _price = 20000000000000000; // Token name string private _name; address private _owner = msg.sender; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'UAWAR22: 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), 'UAWAR22: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('UAWAR22: 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), 'UAWAR22: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'UAWAR22: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'UAWAR22: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('UAWAR22: 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(), '.json')) : ''; } /** * @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 'ipfs://QmVLP5owcXic5BjD61bHTrLUu3ojbSXgBUgxt9ZyXJvJ6M/'; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = UAWAR22.ownerOf(tokenId); require(to != owner, 'UAWAR22: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'UAWAR22: 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), 'UAWAR22: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'UAWAR22: 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), 'UAWAR22: transfer to non ERC721Receiver implementer' ); } function setPrice(uint256 newPrice) external { require(msg.sender == _owner); _price = newPrice; } /** * @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 reserveBulk(address[] memory to) external { require(msg.sender == _owner); for (uint i = 0; i < to.length;i++) { _safeMint(to[i], 1); } } function reserve(address to, uint256 quantity) external { require(msg.sender == _owner); require(currentIndex + quantity <= 10000); _safeMint(to, quantity); } function mint(address to, uint256 quantity) external payable { require(quantity <= 30 && quantity > 0); require(_price * quantity == msg.value); require(currentIndex + quantity <= 10000); payable(_owner).transfer(msg.value); _safeMint(to, quantity); } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'UAWAR22: 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), 'UAWAR22: token already minted'); require(quantity > 0, 'UAWAR22: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'UAWAR22: 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, 'UAWAR22: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'UAWAR22: transfer from incorrect owner'); require(to != address(0), 'UAWAR22: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous ownefr 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('UAWAR22: 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 v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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); } // 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; }
* @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 ownefr 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; if (reason.length == 0) { revert('UAWAR22: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
11,721,184
[ 1, 3061, 445, 358, 4356, 288, 45, 654, 39, 27, 5340, 12952, 17, 265, 654, 39, 27, 5340, 8872, 97, 603, 279, 1018, 1758, 18, 1021, 745, 353, 486, 7120, 309, 326, 1018, 1758, 353, 486, 279, 6835, 18, 225, 628, 1758, 5123, 326, 2416, 2523, 4644, 4840, 434, 326, 864, 1147, 1599, 225, 358, 1018, 1758, 716, 903, 6798, 326, 2430, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 906, 4193, 225, 389, 892, 1731, 3129, 501, 358, 1366, 7563, 598, 326, 745, 327, 1426, 2856, 326, 745, 8783, 2106, 326, 2665, 8146, 460, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 869, 18, 291, 8924, 10756, 288, 203, 5411, 775, 467, 654, 39, 27, 5340, 12952, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 24899, 3576, 12021, 9334, 628, 16, 1147, 548, 16, 389, 892, 13, 1135, 261, 3890, 24, 5221, 13, 288, 203, 7734, 327, 5221, 422, 467, 654, 39, 27, 5340, 12952, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 31, 203, 7734, 309, 261, 10579, 18, 2469, 422, 374, 13, 288, 203, 10792, 15226, 2668, 57, 12999, 985, 3787, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8284, 203, 10792, 19931, 288, 203, 13491, 15226, 12, 1289, 12, 1578, 16, 3971, 3631, 312, 945, 12, 10579, 3719, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity =0.6.6; import "@openzeppelin/contracts/proxy/BeaconProxy.sol"; import "@openzeppelin/contracts/proxy/UpgradeableBeacon.sol"; contract OwnedBeaconProxy is BeaconProxy { bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; event AdminChanged(address previousAdmin, address newAdmin); event BeaconUpgraded(address indexed beacon); modifier ifAdmin() { if (msg.sender == admin()) { _; } else { _fallback(); } } constructor(address beacon, bytes memory data) public payable BeaconProxy(beacon, data) { emit BeaconUpgraded(beacon); assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); emit AdminChanged(address(0), msg.sender); _setAdmin(msg.sender); } function admin() public view returns (address adm) { bytes32 slot = _ADMIN_SLOT; assembly { adm := sload(slot) } } function beacon() public view returns (address beacon_) { beacon_ = _beacon(); } function implementation() public view returns (address implementation_) { implementation_ = _implementation(); } function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "OwnedBeaconProxy: new admin is the zero address"); emit AdminChanged(admin(), newAdmin); _setAdmin(newAdmin); } function upgradeBeaconTo(address newBeacon) external virtual ifAdmin { require(newBeacon != address(0), "OwnedBeaconProxy: new beacon is the zero address"); emit BeaconUpgraded(newBeacon); _setBeacon(newBeacon, ""); } function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IBeacon.sol"; import "../access/Ownable.sol"; import "../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) public { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 { // solhint-disable-next-line no-inline-assembly 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.6.0 <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.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; import "./IBeacon.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy { /** * @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 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) public payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _setBeacon(beacon, data); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { beacon := sload(slot) } } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't conflict with the storage layout of the implementation behind the proxy. _Available since v3.4._/
contract BeaconProxy is Proxy { bytes32 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; } constructor(address beacon, bytes memory data) public payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _setBeacon(beacon, data); } function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; assembly { beacon := sload(slot) } } function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; assembly { beacon := sload(slot) } } function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).implementation(); } function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } }
14,737,149
[ 1, 2503, 6835, 4792, 279, 2889, 716, 5571, 326, 4471, 1758, 364, 1517, 745, 628, 279, 288, 10784, 429, 1919, 16329, 5496, 1021, 29203, 1758, 353, 4041, 316, 2502, 4694, 1375, 11890, 5034, 12, 79, 24410, 581, 5034, 2668, 73, 625, 3657, 9599, 18, 5656, 18, 2196, 16329, 26112, 300, 404, 9191, 1427, 716, 518, 3302, 1404, 7546, 598, 326, 2502, 3511, 434, 326, 4471, 21478, 326, 2889, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4823, 16329, 3886, 353, 7659, 288, 203, 565, 1731, 1578, 3238, 5381, 389, 5948, 2226, 673, 67, 55, 1502, 56, 273, 374, 6995, 23, 74, 20, 361, 5608, 73, 6564, 4366, 8906, 70, 8313, 3672, 72, 23, 10241, 24, 5026, 9222, 8285, 3707, 25, 69, 29, 69, 9060, 8906, 69, 1340, 6162, 1403, 26, 7358, 4763, 11149, 70, 4763, 28615, 72, 3361, 31, 203, 203, 97, 203, 203, 565, 3885, 12, 2867, 29203, 16, 1731, 3778, 501, 13, 1071, 8843, 429, 288, 203, 3639, 1815, 24899, 5948, 2226, 673, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2932, 73, 625, 3657, 9599, 18, 5656, 18, 2196, 16329, 6, 3719, 300, 404, 10019, 203, 3639, 389, 542, 1919, 16329, 12, 2196, 16329, 16, 501, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2196, 16329, 1435, 2713, 1476, 5024, 1135, 261, 2867, 29203, 13, 288, 203, 3639, 1731, 1578, 4694, 273, 389, 5948, 2226, 673, 67, 55, 1502, 56, 31, 203, 3639, 19931, 288, 203, 5411, 29203, 519, 272, 945, 12, 14194, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 2196, 16329, 1435, 2713, 1476, 5024, 1135, 261, 2867, 29203, 13, 288, 203, 3639, 1731, 1578, 4694, 273, 389, 5948, 2226, 673, 67, 55, 1502, 56, 31, 203, 3639, 19931, 288, 203, 5411, 29203, 519, 272, 945, 12, 14194, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 30810, 1435, 2713, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 2 ]
pragma solidity ^0.4.24; contract PriceOracleInterface { /** * @notice Gets the price of a given asset * @dev fetches the price of a given asset * @param asset Asset to get the price of * @return the price scaled by 10**18, or zero if the price is not available */ function assetPrices(address asset) public view returns (uint); } contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(Error.OPAQUE_ERROR), uint(info), opaqueError); return uint(Error.OPAQUE_ERROR); } } contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate(address asset, uint cash, uint borrows) public view returns (uint, uint); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate(address asset, uint cash, uint borrows) public view returns (uint, uint); } contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public 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 amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @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 amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint a, uint b) internal pure returns (Error, uint) { if (a == 0) { return (Error.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (Error, uint) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (Error, uint) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint a, uint b) internal pure returns (Error, uint) { uint c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub(uint a, uint b, uint c) internal pure returns (Error, uint) { (Error err0, uint sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } contract Exponential is ErrorReporter, CarefulMath { // TODO: We may wish to put the result of 10**18 here instead of the expression. // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint constant expScale = 10**18; // See TODO on expScale uint constant halfExpScale = expScale/2; struct Exp { uint mantissa; } uint constant mantissaOne = 10**18; uint constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) { (Error err0, uint scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / 10**18; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract MoneyMarket is Exponential, SafeToken { uint constant initialInterestIndex = 10 ** 18; uint constant defaultOriginationFee = 0; // default is zero bps uint constant minimumCollateralRatioMantissa = 11 * (10 ** 17); // 1.1 uint constant maximumLiquidationDiscountMantissa = (10 ** 17); // 0.1 /** * @notice `MoneyMarket` is the core Compound MoneyMarket contract */ constructor() public { admin = msg.sender; collateralRatio = Exp({mantissa: 2 * mantissaOne}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: 0}); // oracle must be configured via _setOracle } /** * @notice Do not pay directly into MoneyMarket, please use `supply`. */ function() payable public { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address public oracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = the total interestIndex as calculated after applying the customer's most recent balance-changing action * } */ struct Balance { uint principal; uint interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint blockNumber; InterestRateModel interestRateModel; uint totalSupply; uint supplyRateMantissa; uint supplyIndex; uint totalBorrows; uint borrowRateMantissa; uint borrowIndex; } /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken(address account, address asset, uint amount, uint startingBalance, uint borrowAmountWithFee, uint newBalance); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) */ event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); /** * @dev emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @dev newOracle - address of new oracle */ event NewOracle(address oldOracle, address newOracle); /** * @dev emitted when new market is supported by admin */ event SupportedMarket(address asset, address interestRateModel); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters(uint oldCollateralRatioMantissa, uint newCollateralRatioMantissa, uint oldLiquidationDiscountMantissa, uint newLiquidationDiscountMantissa); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee(uint oldOriginationFeeMantissa, uint newOriginationFeeMantissa); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel(address asset, address interestRateModel); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner); /** * @dev emitted when a supported market is suspended by admin */ event SuspendedMarket(address asset); /** * @dev emitted when admin either pauses or resumes the contract; newState is the resulting state */ event SetPaused(bool newState); /** * @dev Simple function to calculate min between two numbers. */ function min(uint a, uint b) pure internal returns (uint) { if (a < b) { return a; } else { return b; } } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint) { return collateralMarkets.length; } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` */ function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure internal returns (Error, uint) { // Get the block delta (Error err0, uint blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar(Exp({mantissa: interestRateMantissa}), blockDelta); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp(blocksTimesRate, Exp({mantissa: mantissaOne})); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar(onePlusBlocksTimesRate, startingInterestIndex); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * * TODO: Is there a way to handle this that is less likely to overflow? */ function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. */ function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` */ function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * * TODO: Track at what magnitude this fee rounds down to zero? */ function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne})); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (oracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } PriceOracleInterface oracleInterface = PriceOracleInterface(oracle); uint priceMantissa = oracleInterface.assetPrices(asset); return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller = pendingAdmin // msg.sender can't be zero if (msg.sender != pendingAdmin) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint(Error.NO_ERROR); } /** * @notice Set new oracle, who can set asset prices * @dev Admin function to change oracle * @param newOracle New oracle address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOracle(address newOracle) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle); oracleInterface.assetPrices(address(0)); address oldOracle = oracle; // Store oracle = newOracle oracle = newOracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice set `paused` to the specified state * @dev Admin function to pause or resume the market * @param requestedState value to assign to `paused` * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPaused(bool requestedState) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSED_OWNER_CHECK); } paused = requestedState; emit SetPaused(requestedState); return uint(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); require(err == Error.NO_ERROR); if (isZeroExp(accountLiquidity)) { return -1 * int(truncate(accountShortfall)); } else { return int(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) view public returns (uint) { Error err; uint newSupplyIndex; uint userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex); require(err == Error.NO_ERROR); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) view public returns (uint) { Error err; uint newBorrowIndex; uint userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex); require(err == Error.NO_ERROR); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use with Compound * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use with Compound. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK); } // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; emit SuspendedMarket(asset); return uint(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters(uint collateralRatioMantissa, uint liquidationDiscountMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RISK_PARAMETERS_OWNER_CHECK); } Exp memory newCollateralRatio = Exp({mantissa: collateralRatioMantissa}); Exp memory newLiquidationDiscount = Exp({mantissa: liquidationDiscountMantissa}); Exp memory minimumCollateralRatio = Exp({mantissa: minimumCollateralRatioMantissa}); Exp memory maximumLiquidationDiscount = Exp({mantissa: maximumLiquidationDiscountMantissa}); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail(Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail(Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp(newLiquidationDiscount, Exp({mantissa: mantissaOne})); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if (lessThanOrEqualExp(newCollateralRatio, newLiquidationDiscountPlusOne)) { return fail(Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters(oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the origination fee (which is a multiplier on new borrows) * @dev Owner function to set the origination fee * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOriginationFee(uint originationFeeMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK); } // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows) * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows) * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint amount) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK); } // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint cash = getCash(asset); (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED); } //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint(Error.NO_ERROR); // success } /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED); } // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(balance.principal, balance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED); } (err, localResults.userSupplyUpdated) = add(localResults.userSupplyCurrent, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, balance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; emit SupplyReceived(msg.sender, asset, amount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct WithdrawLocalVars { uint withdrawAmount; uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; uint withdrawCapacity; } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint requestedAmount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(asset, localResults.withdrawAmount); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; emit SupplyWithdrawn(msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct AccountValueLocalVars { address assetAddress; uint collateralMarketsLength; uint newSupplyIndex; uint userSupplyCurrent; Exp supplyTotalValue; Exp sumSupplies; uint newBorrowIndex; uint userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). */ function calculateAccountLiquidity(address userAddress) internal view returns (Error, Exp memory, Exp memory) { Error err; uint sumSupplyValuesMantissa; uint sumBorrowValuesMantissa; (err, sumSupplyValuesMantissa, sumBorrowValuesMantissa) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return(err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({mantissa: sumSupplyValuesMantissa}); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp(collateralRatio, Exp({mantissa: sumBorrowValuesMantissa})); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) * TODO: Possibly should add a Min(500, collateralMarkets.length) for extra safety * TODO: To help save gas we could think about using the current Market.interestIndex * accumulate interest rather than calculating it */ function calculateAccountValuesInternal(address userAddress) internal view returns (Error, uint, uint) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][localResults.assetAddress]; Balance storage borrowBalance = borrowBalances[userAddress][localResults.assetAddress]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userSupplyCurrent); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp(localResults.supplyTotalValue, localResults.sumSupplies); if (err != Error.NO_ERROR) { return (err, 0, 0); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex(currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // In the case of borrow, we multiply the borrow value by the collateral ratio (err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp(localResults.borrowTotalValue, localResults.sumBorrows); if (err != Error.NO_ERROR) { return (err, 0, 0); } } } return (Error.NO_ERROR, localResults.sumSupplies.mantissa, localResults.sumBorrows.mantissa); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) { (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint(err), 0, 0); } return (0, supplyValue, borrowValue); } struct PayBorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint repayAmount; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED); } PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (amount == uint(-1)) { localResults.repayAmount = min(getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent); } else { localResults.repayAmount = amount; } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub(localResults.userBorrowCurrent, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowRepaid(msg.sender, asset, localResults.repayAmount, localResults.startingBalance, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } struct BorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint borrowAmountWithFee; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint newBorrowIndex_UnderwaterAsset; uint newSupplyIndex_UnderwaterAsset; uint newBorrowIndex_CollateralAsset; uint newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint updatedBorrowBalance_TargetUnderwaterAsset; uint newTotalBorrows_ProtocolUnderwaterAsset; uint startingBorrowBalance_TargetUnderwaterAsset; uint startingSupplyBalance_TargetCollateralAsset; uint startingSupplyBalance_LiquidatorCollateralAsset; uint currentSupplyBalance_TargetCollateralAsset; uint updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint updatedSupplyBalance_LiquidatorCollateralAsset; uint newTotalSupply_ProtocolCollateralAsset; uint currentCash_ProtocolUnderwaterAsset; uint updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint newSupplyRateMantissa_ProtocolUnderwaterAsset; uint newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint discountedBorrowDenominatedCollateral; uint maxCloseableBorrowAmount_TargetUnderwaterAsset; uint closeBorrowAmount_TargetUnderwaterAsset; uint seizeSupplyAmount_TargetCollateralAsset; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address targetAccount, address assetBorrow, address assetCollateral, uint requestedAmountClose) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED); } LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[targetAccount][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[targetAccount][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if(err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset (err, localResults.newBorrowIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (err, localResults.currentBorrowBalance_TargetUnderwaterAsset) = calculateBalance(borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset (err, localResults.newSupplyIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } (err, localResults.currentSupplyBalance_TargetCollateralAsset) = calculateBalance(supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset (err, localResults.currentSupplyBalance_LiquidatorCollateralAsset) = calculateBalance(supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (err, localResults.discountedBorrowDenominatedCollateral) = calculateDiscountedBorrowDenominatedCollateral(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. (err, localResults.discountedRepayToEvenAmount) = calculateDiscountedRepayToEvenAmount(targetAccount, localResults.underwaterAssetPrice); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (requestedAmountClose == uint(-1)) { localResults.closeBorrowAmount_TargetUnderwaterAsset = localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) (err, localResults.seizeSupplyAmount_TargetCollateralAsset) = calculateAmountSeize(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into Compound // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows_ProtocolUnderwaterAsset) = addThenSub(borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. (err, localResults.newSupplyIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getSupplyRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getBorrowRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. (err, localResults.newBorrowIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert (err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset) = add(localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert (err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } // Save borrow market updates borrowMarket.blockNumber = getBlockNumber(); borrowMarket.totalBorrows = localResults.newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = getBlockNumber(); collateralMarket.totalSupply = localResults.newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults.newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults.newBorrowIndex_CollateralAsset; // Save user updates localResults.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset.principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults.updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults.newBorrowIndex_UnderwaterAsset; localResults.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset.principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults.updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; localResults.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset.principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults.updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; emitLiquidationEvent(localResults); return uint(Error.NO_ERROR); // success } /** * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow` */ function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal { // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); emit BorrowLiquidated(localResults.targetAccount, localResults.assetBorrow, localResults.startingBorrowBalance_TargetUnderwaterAsset, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.updatedBorrowBalance_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.startingSupplyBalance_TargetCollateralAsset, localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset, localResults.updatedSupplyBalance_TargetCollateralAsset); } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. **/ function calculateDiscountedRepayToEvenAmount(address targetAccount, Exp memory underwaterAssetPrice) internal view returns (Error, uint) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio (err, _accountLiquidity, accountShortfall_TargetUser) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp(collateralRatio, liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp(collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne})); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp(underwaterAssetPrice, discountedCollateralRatioMinusOne); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); (err, rawResult) = divExp(accountShortfall_TargetUser, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) */ function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrent_TargetCollateralAsset) view internal returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar(collateralPrice, supplyCurrent_TargetCollateralAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(onePlusLiquidationDiscount, underwaterAssetPrice); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral **/ function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED); } // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add(localResults.userBorrowCurrent, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // Check customer liquidity (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` (err, localResults.ethValueOfBorrowAmountWithFee) = getPriceForAssetAmountMulCollatRatio(asset, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowTaken(msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } }
save for use in event
localResults.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset.principal;
2,476,539
[ 1, 5688, 364, 999, 316, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1191, 3447, 18, 18526, 3088, 1283, 13937, 67, 48, 18988, 350, 639, 13535, 2045, 287, 6672, 273, 14467, 13937, 67, 48, 18988, 350, 639, 13535, 2045, 287, 6672, 18, 26138, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xb02B34c48138464888A477a6F0CC96d8Ce2Fe3F0/sources/contracts/Cafe.sol
* Check each assert in each test to see if any failed. Note: The check is here instead of setting a `passed` bool in `TestResult` to reduce the amount of code in each unit test./
function checkIfAllPassed( TestResult[] memory _testResults ) public pure returns (bool) { for (uint i = 0; i < _testResults.length; i++) { for (uint k = 0; k < _testResults[i].assertResults.num; k++) { if (!_testResults[i].assertResults.elements[k].passed) { return false; } } } return true; }
11,511,082
[ 1, 1564, 1517, 1815, 316, 1517, 1842, 358, 2621, 309, 1281, 2535, 18, 3609, 30, 225, 1021, 866, 353, 2674, 3560, 434, 3637, 279, 1375, 23603, 68, 1426, 316, 1375, 4709, 1253, 68, 358, 5459, 326, 3844, 434, 981, 316, 1517, 2836, 1842, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19130, 1595, 22530, 12, 203, 3639, 7766, 1253, 8526, 3778, 389, 3813, 3447, 203, 565, 262, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 3813, 3447, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 417, 273, 374, 31, 417, 411, 389, 3813, 3447, 63, 77, 8009, 11231, 3447, 18, 2107, 31, 417, 27245, 288, 203, 7734, 309, 16051, 67, 3813, 3447, 63, 77, 8009, 11231, 3447, 18, 6274, 63, 79, 8009, 23603, 13, 288, 203, 10792, 327, 629, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x37af0fBBe45dbFC40b63956c1e7bBd2D22C63eEa/sources/contracts/Zauction.sol
Create a bid object hashed with the current contract address @param auctionId unique per address auction identifier chosen by seller @param bid token amount bid @param nftAddress address of the nft contract @param tokenId token id we are transferring @param minbid minimum bid allowed @param startBlock block number at which acceptBid starts working @param expireBlock block number at which acceptBid stops working
function createBid( uint256 auctionId, uint256 bid, address nftAddress, uint256 tokenId, uint256 minbid, uint256 startBlock, uint256 expireBlock ) public view returns (bytes32 data) { data = keccak256( abi.encode( auctionId, address(this), block.chainid, bid, nftAddress, tokenId, minbid, startBlock, expireBlock ) ); return data; }
17,125,725
[ 1, 1684, 279, 9949, 733, 14242, 598, 326, 783, 6835, 1758, 225, 279, 4062, 548, 3089, 1534, 1758, 279, 4062, 2756, 10447, 635, 29804, 225, 9949, 1147, 3844, 9949, 225, 290, 1222, 1887, 1758, 434, 326, 290, 1222, 6835, 225, 1147, 548, 1147, 612, 732, 854, 906, 74, 20245, 225, 1131, 19773, 5224, 9949, 2935, 225, 787, 1768, 1203, 1300, 622, 1492, 2791, 17763, 2542, 5960, 225, 6930, 1768, 1203, 1300, 622, 1492, 2791, 17763, 12349, 5960, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 752, 17763, 12, 203, 565, 2254, 5034, 279, 4062, 548, 16, 203, 565, 2254, 5034, 9949, 16, 203, 565, 1758, 290, 1222, 1887, 16, 203, 565, 2254, 5034, 1147, 548, 16, 203, 565, 2254, 5034, 1131, 19773, 16, 203, 565, 2254, 5034, 787, 1768, 16, 203, 565, 2254, 5034, 6930, 1768, 203, 225, 262, 1071, 1476, 1135, 261, 3890, 1578, 501, 13, 288, 203, 565, 501, 273, 417, 24410, 581, 5034, 12, 203, 1377, 24126, 18, 3015, 12, 203, 3639, 279, 4062, 548, 16, 203, 3639, 1758, 12, 2211, 3631, 203, 3639, 1203, 18, 5639, 350, 16, 203, 3639, 9949, 16, 203, 3639, 290, 1222, 1887, 16, 203, 3639, 1147, 548, 16, 203, 3639, 1131, 19773, 16, 203, 3639, 787, 1768, 16, 203, 3639, 6930, 1768, 203, 1377, 262, 203, 565, 11272, 203, 565, 327, 501, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./RobiToken.sol"; /// @dev RobiToken interface containing only needed methods interface IRobiToken { function getBalanceAtBlockHeight(address _address, uint _blockHeight) external view returns (uint); } contract RobiGovernor is Ownable, ReentrancyGuard { /* * Events */ /// @notice LogProposalCreated is emitted when proposal is created event LogProposalCreated(uint proposalId); /// @notice LogProposalStatusUpdate is emitted when proposals status has been updated event LogProposalStatusUpdate(uint proposalId, ProposalStatus status); /// @notice LogProposalVotesUpdate is emitted when vote for specific proposal has been updated event LogProposalVotesUpdate(uint proposalId, Vote vote); /* * Structs */ /// @notice votes mapping maps user address to his vote /// @dev votes mapping is used as nested mapping for specific proposal votes struct Votes { mapping(address => Vote) votes; } /// @notice Vote struct represents users vote and is defined by status and weight (users balance on voteStart) /// @dev Vote -> weight should be users balance at voteStart struct Vote { VoteStatus status; // weight represents balance of user at the voteStart block height uint weight; } /// @notice VoteResult struct represents response for users vote on specific proposal /// @dev VoteResult struct is used as response object for get all user votes query struct VoteResult { Vote vote; uint proposalId; address voter; } /// @notice Proposal struct represents specific proposal struct Proposal { uint id; uint voteStart; // block number uint voteEnd; // block number address payable proposer; string title; string description; ProposalStatus status; uint forVotes; uint againstVotes; uint fee; bool feeRefunded; string forumLink; } /* * Enums */ /// @notice ProposalStatus enum represents the state of specific proposal enum ProposalStatus { ACTIVE, DEFEATED, PASSED, EXECUTED } /// @notice VoteStatus enum represents the state of users vote enum VoteStatus { APPROVED, REJECTED } /* * Modifiers */ /// @dev checks if string is empty /// @param data string to be checked modifier noEmptyString(string memory data) { require(bytes(data).length > 0, "RobiGovernor: String is empty"); _; } /* * State variables */ string private _name; // @notice _proposals mapping maps proposal id (uint256) to specific proposal mapping(uint256 => Proposal) private _proposals; // @notice votes mapping maps proposal id (uint256) to its Votes mapping(uint256 => Votes) private votes; uint proposalsCounter; // @notice governanceTokenAddress holds address of the governance token IRobiToken immutable private robiToken; uint private _votingPeriod; /// @notice Construct contract by specifying governance token address and governance name /// @param _token Governance token address /// @param contractName Contract name constructor(address _token, string memory contractName, uint votingPeriod) noEmptyString(contractName) { _name = contractName; robiToken = IRobiToken(_token); _votingPeriod = votingPeriod; // 1 hour } /// @notice This function is used to cast vote on specific proposal /// @param proposalId Specific proposal id /// @param voteStatus VoteStatus enum that specifies users decision /// @return bool True if cast was successful and false if not function castVote(uint proposalId, VoteStatus voteStatus) public returns (bool) { Proposal storage proposal = _proposals[proposalId]; // vote can only be cast between vote start and end block heights require(block.number >= proposal.voteStart && block.number < proposal.voteEnd, "Voting period is not active."); // establish contract interface uint balance = robiToken.getBalanceAtBlockHeight(msg.sender, proposal.voteStart); // Check if users balance on voteStart was greater than 0 require(balance > 0, "You have no voting power."); Vote storage currentVote = votes[proposalId].votes[msg.sender]; // check if user has already voted and subtract vote weight from total for or against if (currentVote.weight != 0) { if (currentVote.status == VoteStatus.APPROVED) { proposal.forVotes -= currentVote.weight; } else { proposal.againstVotes -= currentVote.weight; } } if (VoteStatus.APPROVED == voteStatus) { proposal.forVotes += balance; } else { proposal.againstVotes += balance; } currentVote.status = voteStatus; currentVote.weight = balance; emit LogProposalVotesUpdate(proposalId, currentVote); return true; } /// @notice This function is used to update the proposal states and should be called now and then. /// @dev This function is protected against reentrancy because of external transfer call inside loop function updateProposalStates() payable public nonReentrant { // iterate all proposals // FIXME optimise proposal state update logic before production for (uint i = 0; i < proposalsCounter; i++) { Proposal storage proposal = _proposals[proposalsCounter]; // if proposal is active and time to vote has passed if (proposal.status == ProposalStatus.ACTIVE && block.number >= proposal.voteEnd) { processProposal(proposal.id); } } } /// @notice This function confirms proposal execution by owner /// @dev This function should be triggered only when proposal is enacted /// @param proposalId Proposal id function confirmProposalExecution(uint proposalId) public onlyOwner { require(block.number >= _proposals[proposalId].voteEnd, "Proposal voting period is still open!"); _proposals[proposalId].status = ProposalStatus.EXECUTED; emit LogProposalStatusUpdate(proposalId, _proposals[proposalId].status); } /// @notice This function is used to process proposal states and return fees if proposal has passed /// @dev Calling function should be protected by reentrancy guard /// @param proposalId Proposal which is being processed function processProposal(uint proposalId) private { Proposal storage proposal = _proposals[proposalId]; if (proposal.forVotes > proposal.againstVotes) { proposal.status = ProposalStatus.PASSED; if (!proposal.feeRefunded) { proposal.feeRefunded = true; proposal.proposer.transfer(proposal.fee); } } else { proposal.status = ProposalStatus.DEFEATED; } emit LogProposalStatusUpdate(proposal.id, proposal.status); } /// @notice This function is used to create a new proposal /// @dev This function accepts fee (payable) required for creating a proposal. Fee is returned if proposal passes /// @param forumLink string representing link to the forum where discussion about proposal should be held /// @param title Proposals title /// @param description Proposals description /// @return uint Proposal id function createProposal(string memory forumLink, string memory title, string memory description ) payable noEmptyString(forumLink) noEmptyString(title) noEmptyString(description) public returns (uint) { // check if user paid enough fee require(msg.value >= fee(), "Fee is lower than required"); // string input length checks require(utfStringLength(forumLink) <= maxForumLinkSize(), "Forum link length exceeds max size"); require(utfStringLength(title) <= maxTitleSize(), "Title length exceeds max size"); require(utfStringLength(description) <= maxDescriptionSize(), "Description length exceeds max size"); uint proposalId = proposalsCounter; _proposals[proposalId] = Proposal(proposalId, block.number, block.number + _votingPeriod, payable(msg.sender), title, description, ProposalStatus.ACTIVE, 0, 0, fee(), false, forumLink); proposalsCounter++; emit LogProposalCreated(proposalId); return proposalsCounter - 1; } /// @notice This function is used to update the voting period function updateVotingPeriod(uint256 newPeriod) public onlyOwner { _votingPeriod = newPeriod; } /// @notice This function returns name of this contract /// @return string Contracts name function name() public view returns (string memory) { return _name; } /// @notice This function returns Proposal struct /// @param id Proposal id /// @return Proposal Proposal struct function getProposal(uint id) public view returns (Proposal memory) { return _proposals[id]; } /// @notice This function returns users vote for specific proposal /// @param proposalId Proposal id /// @return Vote Users vote for specific proposal function getVote(uint proposalId, address _address) public view returns (Vote memory) { return votes[proposalId].votes[_address]; } /// @notice This function returns all user votes for all proposals /// @return VoteResult[] Array of user VoteResult structs function getUserVotes() public view returns (VoteResult[] memory) { VoteResult[] memory tmpVotes = new VoteResult[](proposalsCounter); for (uint i = 0; i < proposalsCounter; i++) { tmpVotes[i] = VoteResult(votes[i].votes[msg.sender], i, msg.sender); } return tmpVotes; } /// @notice This function returns all proposals /// @return proposals Array of proposals function getProposals() public view returns (Proposal[] memory proposals) { Proposal[] memory tmpProposals = new Proposal[](proposalsCounter); for (uint i = 0; i < proposalsCounter; i++) { tmpProposals[i] = _proposals[i]; } return tmpProposals; } /// @notice This function returns proposal count /// @return uint256 Number of proposals function proposalCount() public view returns (uint256) { return proposalsCounter; } /// @notice This function returns fee required for creation of proposal /// @return uint256 Number representing fee function fee() public pure returns (uint256) { return 1; } /// @notice This function returns max forum link size /// @return uint256 Number representing max forum link size function maxForumLinkSize() public pure returns (uint256) { return 200; } /// @notice This function returns max title size /// @return uint256 Number representing max title size function maxTitleSize() public pure returns (uint256) { return 100; } /// @notice This function returns max description size /// @return uint256 Number representing max description size function maxDescriptionSize() public pure returns (uint256) { return 200; } /// @notice This function returns voting period /// @dev Voting period is specified in number of blocks /// @return uint256 Number representing voting period function getVotingPeriod() public view returns (uint) { return _votingPeriod; } /// @notice This function returns length of string /// @dev This function should be used for determining the actual string length /// @return length Number representing provided string length function utfStringLength(string memory str) pure internal returns (uint length) { uint i=0; bytes memory string_rep = bytes(str); while (i<string_rep.length) { if (string_rep[i]>>7==0) i+=1; else if (string_rep[i]>>5==bytes1(uint8(0x6))) i+=2; else if (string_rep[i]>>4==bytes1(uint8(0xE))) i+=3; else if (string_rep[i]>>3==bytes1(uint8(0x1E))) i+=4; else //For safety i+=1; length++; } } }
@notice votes mapping maps proposal id (uint256) to its Votes
mapping(uint256 => Votes) private votes;
879,510
[ 1, 27800, 2874, 7565, 14708, 612, 261, 11890, 5034, 13, 358, 2097, 776, 6366, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 776, 6366, 13, 3238, 19588, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x4125F21293b86B0F951859D535312E9E62570B33/sources/project_/contracts/Horae.sol
Name of the tokenSymbol of the tokenOwner of the tokenbaseURI of tokens Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvalsMapping from token ID to token URIWatch attributes
contract MyToken { string public _name = "Horae"; string public _symbol = "HOR"; address public _owner; string public _baseURI; mapping(uint256 => address) public _owners; mapping(address => uint256) public _balances; mapping(uint256 => address) public _tokenApprovals; mapping(address => mapping(address => bool)) public _operatorApprovals; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => string) public _watchBrand; mapping(uint256 => string) public _watchYear; mapping(uint256 => string) public _watchModel; mapping(uint256 => string) public _watchID; mapping(uint256 => bool) public _watchIsStolen; constructor(string memory baseURI_) { _owner = msg.sender; _baseURI = baseURI_; } modifier onlyOwner() { require(msg.sender == _owner, "You are not the owner"); _; } function safeMint(address to, uint256 tokenId, string memory uri) public onlyOwner { _safeMint(to, tokenId,""); _setTokenURI(tokenId, uri); } function _safeMint(address to,uint256 tokenId,bytes memory /*data*/) private { _mint(to, tokenId); } function _mint(address to, uint256 tokenId) private { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId, 1); require(!_exists(tokenId), "ERC721: token already minted"); unchecked { _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } event Transfer(address indexed from, address indexed to, uint256 value); function _mint(address to, uint256 tokenId) private { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId, 1); require(!_exists(tokenId), "ERC721: token already minted"); unchecked { _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } event Transfer(address indexed from, address indexed to, uint256 value); function _beforeTokenTransfer(address from, address to, uint256 /*firstTokenId*/, uint256 batchSize) private{ if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } function _beforeTokenTransfer(address from, address to, uint256 /*firstTokenId*/, uint256 batchSize) private{ if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } function _beforeTokenTransfer(address from, address to, uint256 /*firstTokenId*/, uint256 batchSize) private{ if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } function _beforeTokenTransfer(address from, address to, uint256 /*firstTokenId*/, uint256 batchSize) private{ if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } function transferFrom(address from,address to,uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: caller is not token owner or approved"); _transfer(from, to, tokenId); } function _transfer(address from,address to,uint256 tokenId) private { require(_ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); require(to != from, "ERC721: you can not transfert your token to yourself"); _beforeTokenTransfer(from, to, tokenId, 1); require(_ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); delete _tokenApprovals[tokenId]; unchecked { _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); } event ApprovalForAll(address owner,address operator,bool approved); event Approval(address owner,address to, uint256 tokenId); function _transfer(address from,address to,uint256 tokenId) private { require(_ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); require(to != from, "ERC721: you can not transfert your token to yourself"); _beforeTokenTransfer(from, to, tokenId, 1); require(_ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); delete _tokenApprovals[tokenId]; unchecked { _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); } event ApprovalForAll(address owner,address operator,bool approved); event Approval(address owner,address to, uint256 tokenId); function approve(address to, uint256 tokenId) public { address owner = _ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender),"ERC721: approve caller is not token owner or approved for all"); _approve(to, tokenId); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(_ownerOf(tokenId), to, tokenId); } function getApproved(uint256 tokenId) public view returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public { _setApprovalForAll(msg.sender, operator, approved); } function _setApprovalForAll(address owner,address operator,bool approved) private { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } function _isApprovedOrOwner(address spender, uint256 tokenId) private view returns (bool) { address owner = _ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } function _exists(uint256 tokenId) private view returns (bool) { return _ownerOf(tokenId) != address(0); } function _ownerOf(uint256 tokenId) private view returns (address) { return _owners[tokenId]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: address zero is not a valid owner"); return _balances[owner]; } function _requireMinted(uint256 tokenId) private view { require(_exists(tokenId), "ERC721: invalid token ID"); } function tokenURI(uint256 tokenId) public view returns (string memory) { _requireMinted(tokenId); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI; if (bytes(base).length == 0) { return string(abi.encodePacked(base, "default")); } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return base; } function tokenURI(uint256 tokenId) public view returns (string memory) { _requireMinted(tokenId); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI; if (bytes(base).length == 0) { return string(abi.encodePacked(base, "default")); } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return base; } function tokenURI(uint256 tokenId) public view returns (string memory) { _requireMinted(tokenId); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI; if (bytes(base).length == 0) { return string(abi.encodePacked(base, "default")); } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return base; } function _setTokenURI(uint256 tokenId, string memory _tokenURI) private { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _getBaseURI() public view returns (string memory) { return _baseURI; } function _setBaseURI(string memory baseURI_) public onlyOwner { _baseURI=baseURI_; } function _burn(uint256 tokenId) public onlyOwner { address owner = _ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); owner = _ownerOf(tokenId); delete _tokenApprovals[tokenId]; unchecked { _balances[owner] -= 1; } delete _owners[tokenId]; if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } emit Transfer(owner, address(0), tokenId); } event Stolen(uint256 tokenId, string reason); event Recovered(uint256 tokenId, string reason); function _burn(uint256 tokenId) public onlyOwner { address owner = _ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); owner = _ownerOf(tokenId); delete _tokenApprovals[tokenId]; unchecked { _balances[owner] -= 1; } delete _owners[tokenId]; if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } emit Transfer(owner, address(0), tokenId); } event Stolen(uint256 tokenId, string reason); event Recovered(uint256 tokenId, string reason); function _burn(uint256 tokenId) public onlyOwner { address owner = _ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); owner = _ownerOf(tokenId); delete _tokenApprovals[tokenId]; unchecked { _balances[owner] -= 1; } delete _owners[tokenId]; if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } emit Transfer(owner, address(0), tokenId); } event Stolen(uint256 tokenId, string reason); event Recovered(uint256 tokenId, string reason); function setAsStolen(uint256 tokenId, string memory reason) public { require(_ownerOf(tokenId) == msg.sender, "ERC721: call from incorrect owner"); require(_watchIsStolen[tokenId] == true, "ERC721: watch already stolen"); _watchIsStolen[tokenId] = true; emit Stolen(tokenId, reason); } function setAsRecovered(uint256 tokenId, string memory reason) public { require(_ownerOf(tokenId) == msg.sender, "ERC721: call from incorrect owner"); require(_watchIsStolen[tokenId] == false, "ERC721: watch was not stoled"); _watchIsStolen[tokenId] = true; emit Recovered(tokenId, reason); } }
1,936,405
[ 1, 461, 434, 326, 1147, 5335, 434, 326, 1147, 5541, 434, 326, 1147, 1969, 3098, 434, 2430, 9408, 628, 1147, 1599, 358, 3410, 1758, 9408, 3410, 1758, 358, 1147, 1056, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 3233, 628, 1147, 1599, 358, 1147, 3699, 5234, 1677, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8005, 1345, 288, 203, 203, 565, 533, 1071, 389, 529, 273, 315, 44, 280, 8906, 14432, 203, 565, 533, 1071, 389, 7175, 273, 315, 44, 916, 14432, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 533, 1071, 389, 1969, 3098, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 389, 995, 414, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 389, 9497, 12053, 4524, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 389, 7585, 20484, 31, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 389, 7585, 5593, 31, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 389, 7585, 1488, 31, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 389, 7585, 734, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 13, 1071, 389, 7585, 2520, 510, 355, 275, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 1026, 3098, 67, 13, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 389, 1969, 3098, 273, 1026, 3098, 67, 31, 203, 565, 289, 203, 203, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 16, 2 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _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; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } 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); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } }
* @title VariableDebtToken @notice Implements a variable debt token to track the borrowing positions of users at variable rate mode @author Aave/
contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params } pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } }
135,601
[ 1, 3092, 758, 23602, 1345, 225, 29704, 279, 2190, 18202, 88, 1147, 358, 3298, 326, 29759, 310, 6865, 434, 3677, 622, 2190, 4993, 1965, 225, 432, 836, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7110, 758, 23602, 1345, 353, 1505, 23602, 1345, 2171, 16, 467, 3092, 758, 23602, 1345, 288, 203, 225, 1450, 678, 361, 54, 528, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 1071, 5381, 2030, 38, 56, 67, 8412, 67, 862, 25216, 273, 374, 92, 21, 31, 203, 203, 225, 467, 48, 2846, 2864, 2713, 389, 6011, 31, 203, 225, 1758, 2713, 389, 9341, 6291, 6672, 31, 203, 225, 467, 37, 836, 382, 2998, 3606, 2933, 2713, 389, 267, 2998, 3606, 2933, 31, 203, 203, 225, 445, 4046, 12, 203, 565, 467, 48, 2846, 2864, 2845, 16, 203, 565, 1758, 6808, 6672, 16, 203, 565, 467, 37, 836, 382, 2998, 3606, 2933, 316, 2998, 3606, 2933, 16, 203, 565, 2254, 28, 18202, 88, 1345, 31809, 16, 203, 565, 533, 3778, 18202, 88, 1345, 461, 16, 203, 565, 533, 3778, 18202, 88, 1345, 5335, 16, 203, 565, 1731, 745, 892, 859, 203, 97, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 5666, 288, 45, 3092, 758, 23602, 1345, 97, 628, 296, 16644, 15898, 19, 45, 3092, 758, 23602, 1345, 18, 18281, 13506, 203, 5666, 288, 59, 361, 54, 528, 10477, 97, 628, 25226, 31417, 19, 15949, 19, 59, 361, 54, 528, 10477, 18, 18281, 13506, 203, 5666, 288, 4229, 97, 628, 25226, 31417, 19, 11397, 19, 4229, 18, 18281, 13506, 203, 5666, 288, 758, 23602, 1345, 2171, 97, 628, 12871, 1969, 19, 758, 23602, 1345, 2171, 18, 18281, 13506, 203, 5666, 288, 2627, 2846, 2864, 97, 628, 296, 16644, 2 ]
// Наречия, которые могут предварять предложение без отбивки запятой wordentry_set AdvAsClausePrefix = { eng_adverb:Finally{}, // Finally I would like to express my debt to my personal heroes. eng_adverb:In all likelihood{}, // In all likelihood we are headed for war. eng_adverb:Hopefully{}, // Hopefully the weather will be fine on Sunday. eng_adverb:Tranquilly{}, // Tranquilly she went on with her work. eng_adverb:Stealthily{}, // Stealthily they advanced upstream. eng_adverb:Henceforth{}, // Henceforth she will be known as Mrs. Smith. eng_adverb:Hereafter{}, // Hereafter you will no longer receive an allowance. eng_adverb:Today{}, // Today almost every home has television. eng_adverb:Altogether{}, // Altogether he earns close to a million dollars. eng_adverb:Meantime{}, // Meantime he was attentive to his other interests. eng_adverb:Bravely{}, // Bravely he went into the burning house. eng_adverb:Thereafter{}, // Thereafter he never called again. eng_adverb:Sure{}, // Sure he'll come. eng_adverb:Economically{}, // Economically this proposal makes no sense. eng_adverb:Once{}, // Once I ran into her. eng_adverb:Usually{}, // Usually she was late. eng_adverb:Historically{}, // Historically they have never coexisted peacefully. eng_adverb:Lately{}, // Lately the rules have been enforced. eng_adverb:Then{}, // Then he left. eng_adverb:Suddenly{}, // Suddenly she turned around. eng_adverb:Ultimately{}, // Ultimately he had to give in. eng_adverb:Unfortunately{}, // Unfortunately it rained all day. eng_adverb:Sadly{}, // Sadly he died before he could see his grandchild. eng_adverb:Happily{}, // Happily he was not injured. eng_adverb:Straightway{}, // Straightway the clouds began to scatter. eng_adverb:now{}, // Now it's awake. eng_adverb:Meanwhile{}, // Meanwhile I will not think about the problem. eng_adverb:someday{}, // Someday you will understand my actions. eng_adverb:Thankfully{}, // Thankfully he didn't come to the party. eng_adverb:Intermittently{}, // Intermittently we questioned the barometer. eng_adverb:Currently{}, // Currently they live in Connecticut. eng_adverb:yesterday{}, // Yesterday the weather was beautiful. eng_adverb:Gingerly{}, // Gingerly I raised the edge of the blanket. eng_adverb:Daringly{}, // Daringly he took the first step. eng_adverb:Yet{}, // Yet George always did his work. eng_adverb:Probably{}, // Probably he closed the door eng_adverb:Pensively{}, // Pensively he stared at the painting. eng_adverb:Fortunately{}, // Fortunately he closed the door eng_adverb:Apparently{}, // Apparently he closed the door eng_adverb:Maybe{}, // Maybe he is coming eng_adverb:Perhaps{}, // Perhaps I could see you tomorrow. eng_adverb:away{}, // Away they went. eng_adverb:there{}, // There they go. eng_adverb:here{}, // Here I come. eng_adverb:sometimes{}, // Sometimes we go to Italy. eng_adverb:Lifelessly{}, // Lifelessly he performed the song. eng_adverb:Providentially{}, // Providentially the weather remained good. eng_adverb:Obediently{}, // Obediently she slipped off her right shoe and stocking. eng_adverb:Dextrously{}, // Dextrously he untied the knots. eng_adverb:Normally{} // Normally I stay at home in the evening } // множество наречий, которые могут выступать в роли одиночного opener'а, с отбивкой запятой. wordentry_set AdvAsOpener = { eng_adverb:well{}, // Well, he is a national hero. eng_adverb:Candidly{}, // Candidly, I think she doesn't have a conscience. eng_adverb:Obligingly{}, // Obligingly, he lowered his voice. eng_adverb:Hastily{}, // Hastily, he scanned the headlines. eng_adverb:Ideally{}, // Ideally, this will remove all problems. eng_adverb:Privately{}, // Privately, she thought differently. eng_adverb:Presumably{}, // Presumably, he missed the train. eng_adverb:Naturally{}, // Naturally, the lawyer sent us a huge bill. eng_adverb:Really{}, // Really, you shouldn't have done it. eng_adverb:Fourthly{}, // Fourthly, you must pay the rent on the first of the month. eng_adverb:Unforgivingly{}, // Unforgivingly, he insisted that she pay her debt to the last penny. eng_adverb:Personally{}, // Personally, I find him stupid. eng_adverb:Outside{}, // Outside, the box is black. eng_adverb:Inside{}, // Inside, the car is a mess. eng_adverb:Unfeelingly{}, // Unfeelingly, she required her maid to work on Christmas Day. eng_adverb:Delightedly{}, // Delightedly, she accepted the invitation. eng_adverb:Contemporaneously{}, // Contemporaneously, or possibly a little later, there developed a great Sumerian civilisation. eng_adverb:Contrastingly{}, // Contrastingly, both the rooms leading off it gave an immediate impression of being disgraced. eng_adverb:Unassertively{}, // Unassertively, she always follows her husband's suggestions. eng_adverb:Analogously{}, // Analogously, we have a variable. eng_adverb:Consequently{}, // Consequently, he didn't do it. eng_adverb:anyhow{}, // Anyhow, he is dead now. eng_adverb:Uncouthly{}, // Uncouthly, he told stories that made everybody at the table wince. eng_adverb:Unchivalrously{}, // Unchivalrously, the husbands who had to provide such innocent indulgences eventually began to count the costs. eng_adverb:Imprudently{}, // Imprudently, he downed tools and ran home to make his wife happy. eng_adverb:Providently{}, // Providently, he had saved up some money for emergencies. eng_adverb:Logically{}, // Logically, you should now do the same to him. eng_adverb:Ideologically{}, // Ideologically, we do not see eye to eye. eng_adverb:Undemocratically{}, // Undemocratically, he made all the important decisions without his colleagues. eng_adverb:Academically{}, // Academically, this is a good school. eng_adverb:Officially{}, // Officially, he is in charge. eng_adverb:Unofficially{}, // Unofficially, he serves as the treasurer. eng_adverb:Inwardly{}, // Inwardly, she was raging. eng_adverb:Outwardly{}, // Outwardly, the figure is smooth. eng_adverb:Amazingly{}, // Amazingly, he finished medical school in three years. eng_adverb:Fearlessly{}, // Fearlessly, he led the troops into combat. eng_adverb:Incidentally{}, // Incidentally, I won't go to the party. eng_adverb:Actually{}, // Actually, I haven't seen the film. eng_adverb:Technically{}, // Technically, a bank's reserves belong to the stockholders. eng_adverb:Structurally{}, // Structurally, the organization is healthy. eng_adverb:Computationally{}, // Computationally, this is a tricky problem. eng_adverb:Conceptually{}, // Conceptually, the idea is quite simple. eng_adverb:Organizationally{}, // Organizationally, the conference was a disaster! eng_adverb:Nutritionally{}, // Nutritionally, her new diet is suicide. eng_adverb:briefly{}, // Briefly, we have a problem. eng_adverb:Brashly{}, // Brashly, she asked for a rebate. eng_adverb:Crucially{}, // Crucially, he must meet us at the airport. eng_adverb:Fretfully{}, // Fretfully, the baby tossed in his crib. eng_adverb:hereupon{}, // Hereupon, the passengers stumbled aboard. eng_adverb:Daringly{}, // Daringly, he set out on a camping trip in East Africa. eng_adverb:Disingenuously{}, // Disingenuously, he asked leading questions about his opponent's work. eng_adverb:Invincibly{}, // Invincibly, the troops moved forward. eng_adverb:Statistically{}, // Statistically, the study was almost worthless. eng_adverb:Predictably{}, // Predictably, he did not like the news. eng_adverb:Portentously{}, // Portentously, the engines began to roll. eng_adverb:Piggishly{}, // Piggishly, he took two pieces of cake. eng_adverb:Suprisingly{}, // Suprisingly, the dog had only three legs. eng_adverb:Surely{}, // Surely, you must be joking. eng_adverb:Truthfully{}, // Truthfully, I didn't suspect a thing. eng_adverb:Ultimately{}, // Ultimately, I have been studying Greek at evening classes. eng_adverb:Biochemically{}, // Biochemically, the experiment was well-designed eng_adverb:Sometimes{}, // Sometimes, we have chicken eng_adverb:Apparently{}, // Apparently, they went to a movie eng_adverb:Clearly{}, // Clearly, he read the speech. eng_adverb:Honestly{}, // Honestly, I didn't do it. eng_adverb:Frankly{}, // Frankly, this whole paragraph needs work. eng_adverb:Interestingly{}, // Interestingly, the comment made for a great topic of its own. eng_adverb:Luckily{}, // Luckily, the amount of sugar the recipe called for was in stock in the pantry. eng_adverb:Fortunately{}, // Fortunately, there was a bridge across the river. eng_adverb:Metrically{}, // Metrically, these poems are matched. eng_adverb:Domestically{}, // Domestically, the president proposes a more moderate economic policy. eng_adverb:Conversely{}, // Conversely, not all women are mothers. eng_adverb:Anyway{}, // Anyway, there is another factor to consider. eng_adverb:Unabashedly{}, // Unabashedly, he asked for more. eng_adverb:Unfortunately{} // Unfortunately, by the time she reached the bus stop, the bus had already left. }
Thereafter he never called again.
eng_adverb:Thereafter{},
13,045,048
[ 1, 9828, 5205, 3904, 5903, 2566, 3382, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 24691, 67, 361, 16629, 30, 9828, 5205, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.11; import './ArrayInterface.sol'; /// @notice "normal" array implementation used as base case for comparison /// @dev light wrapper around uint8[] array /// @author Adapted by @devtooligan from https://solidity-by-example.org/array/ contract NormalArray is ArrayInterface { /* Storage *********************************************************************************************/ uint8[] public arr; /* Main functions *********************************************************************************************/ function getArr() public view returns(uint8[] memory) { return arr; } /// @return length of array function length() public view returns (uint8) { return uint8(arr.length); } /// @param index of element to return the value of /// @return value of the specified element function val(uint256 index) public view returns(uint8) { require(index < arr.length, "outtarange"); return arr[index]; } /// @param value of new element added to the end of the array function push(uint8 value) public { arr.push(value); } /// @return value of popped element function pop() public returns(uint8 value) { require(arr.length != 0, "no can"); value = arr[arr.length - 1]; arr.pop(); } /// @dev delete element and replace it with a popped element /// @param index of element to remove function remove(uint256 index) public { arr[index] = pop(); } /// @param index to update /// @param value is the new value being set function set(uint256 index, uint8 value) public { arr[index] = value; } }
@dev delete element and replace it with a popped element @param index of element to remove
function remove(uint256 index) public { arr[index] = pop(); }
15,806,298
[ 1, 3733, 930, 471, 1453, 518, 598, 279, 30766, 930, 225, 770, 434, 930, 358, 1206, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 12, 11890, 5034, 770, 13, 1071, 288, 203, 3639, 2454, 63, 1615, 65, 273, 1843, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x0A1826b2C8dB24Fe9F18ADe9fd717E8B3DE2DB68/sources/NANJCOIN.sol
* 彡(゚)(゚) @title NANJCOIN @author Tsuchinoko & NanJ people @dev NANJCOIN is an ERC223 Token with ERC20 functions and events Fully backward compatible with ERC20/
contract NANJCOIN is ERC223, Ownable { using SafeMath for uint256; string public name = "NANJCOIN"; string public symbol = "NANJ"; string public constant AAcontributors = "sybit & クリプたん"; uint8 public decimals = 8; uint256 public totalSupply = 30e9 * 1e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; address public founder = 0xb668B8E8D8fD02514a38937bA4FDe6265E17100F; address public preSeasonGame = 0xb668B8E8D8fD02514a38937bA4FDe6265E17100F; address public activityFunds = 0xb668B8E8D8fD02514a38937bA4FDe6265E17100F; address public lockedFundsForthefuture = 0xb668B8E8D8fD02514a38937bA4FDe6265E17100F; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); function NANJCOIN() public { owner = activityFunds; balanceOf[founder] = totalSupply.mul(25).div(100); balanceOf[preSeasonGame] = totalSupply.mul(55).div(100); balanceOf[activityFunds] = totalSupply.mul(10).div(100); balanceOf[lockedFundsForthefuture] = totalSupply.mul(10).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; return transferToAddress(_to, _value, _data); } } } else { function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); return transferToAddress(_to, _value, _data); } } } else { function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); return transferToAddress(_to, _value, empty); } } function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); return transferToAddress(_to, _value, empty); } } } else { function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[activityFunds] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) activityFunds.transfer(msg.value); balanceOf[activityFunds] = balanceOf[activityFunds].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(activityFunds, msg.sender, distributeAmount); } function() payable public { autoDistribute(); } }
3,308,037
[ 1, 166, 126, 99, 12, 176, 127, 258, 21433, 176, 127, 258, 13, 225, 21600, 46, 3865, 706, 225, 24709, 2648, 267, 601, 83, 473, 23294, 46, 16951, 225, 21600, 46, 3865, 706, 353, 392, 4232, 39, 3787, 23, 3155, 598, 4232, 39, 3462, 4186, 471, 2641, 1377, 11692, 93, 12555, 7318, 598, 4232, 39, 3462, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21600, 46, 3865, 706, 353, 4232, 39, 3787, 23, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 508, 273, 315, 50, 1258, 46, 3865, 706, 14432, 203, 565, 533, 1071, 3273, 273, 315, 50, 1258, 46, 14432, 203, 565, 533, 1071, 5381, 27343, 26930, 13595, 273, 315, 9009, 3682, 473, 225, 164, 229, 112, 164, 230, 108, 164, 230, 250, 164, 228, 258, 164, 229, 246, 14432, 203, 565, 2254, 28, 1071, 15105, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 273, 5196, 73, 29, 380, 404, 73, 28, 31, 203, 565, 2254, 5034, 1071, 25722, 6275, 273, 374, 31, 203, 565, 1426, 1071, 312, 474, 310, 10577, 273, 629, 31, 203, 377, 203, 565, 1758, 1071, 284, 465, 765, 273, 374, 6114, 6028, 28, 38, 28, 41, 28, 40, 28, 74, 40, 20, 2947, 3461, 69, 23, 6675, 6418, 70, 37, 24, 42, 758, 26, 30281, 41, 4033, 6625, 42, 31, 203, 565, 1758, 1071, 675, 1761, 2753, 12496, 273, 374, 6114, 6028, 28, 38, 28, 41, 28, 40, 28, 74, 40, 20, 2947, 3461, 69, 23, 6675, 6418, 70, 37, 24, 42, 758, 26, 30281, 41, 4033, 6625, 42, 31, 203, 565, 1758, 1071, 5728, 42, 19156, 273, 374, 6114, 6028, 28, 38, 28, 41, 28, 40, 28, 74, 40, 20, 2947, 3461, 69, 23, 6675, 6418, 70, 37, 24, 42, 758, 26, 30281, 41, 4033, 6625, 42, 31, 203, 565, 1758, 1071, 8586, 42, 19156, 1290, 5787, 2 ]
/** * Copyright 2017-2019, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/Math.sol"; import "../proxy/BZxProxiable.sol"; import "../shared/OrderClosingFunctions.sol"; import "../BZxVault.sol"; import "../oracle/OracleInterface.sol"; contract LoanHealth_MiscFunctions is BZxStorage, BZxProxiable, OrderClosingFunctions { using SafeMath for uint256; constructor() public {} function() external { revert("fallback not allowed"); } function initialize( address _target) public onlyOwner { targets[bytes4(keccak256("liquidatePosition(bytes32,address,uint256)"))] = _target; targets[bytes4(keccak256("closeLoan(bytes32)"))] = _target; targets[bytes4(keccak256("closeLoanForBorrower(bytes32,address)"))] = _target; targets[bytes4(keccak256("forceCloseLoan(bytes32,address)"))] = _target; targets[bytes4(keccak256("shouldLiquidate(bytes32,address)"))] = _target; } /// @dev Checks that a position meets the conditions for liquidation, then closes the position and loan. /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @param maxCloseAmount The maximum amount of loan principal to liquidate /// @dev A maxCloseAmount exceeding loanTokenAmountFilled or a maxCloseAmount of 0, will set the maximum to loanTokenAmountFilled. /// @return True on success function liquidatePosition( bytes32 loanOrderHash, address trader, uint256 maxCloseAmount) external nonReentrant tracksGas returns (bool) { require(trader != msg.sender, "BZxLoanHealth::liquidatePosition: trader can't liquidate"); require(msg.sender == tx.origin, "BZxLoanHealth::liquidatePosition: only EOAs can liquidate"); LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][trader]]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { revert("BZxLoanHealth::liquidatePosition: loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active"); } LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxLoanHealth::liquidatePosition: loanOrder.loanTokenAddress == address(0)"); } uint256 currentMargin = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).getCurrentMarginAmount( loanOrder.loanTokenAddress, loanPosition.positionTokenAddressFilled, loanPosition.collateralTokenAddressFilled, loanPosition.loanTokenAmountFilled, loanPosition.positionTokenAmountFilled, loanPosition.collateralTokenAmountFilled ); if (!DEBUG_MODE && block.timestamp < loanPosition.loanEndUnixTimestampSec && currentMargin > loanOrder.maintenanceMarginAmount) { revert("BZxLoanHealth::liquidatePosition: loan is healthy"); } uint256 closeAmount; if ((!DEBUG_MODE && block.timestamp < loanPosition.loanEndUnixTimestampSec) || (DEBUG_MODE && currentMargin <= loanOrder.maintenanceMarginAmount)) { // loan hasn't ended uint256 desiredMargin = loanOrder.maintenanceMarginAmount .add(10 ether); // 10 percentage points above maintenance uint256 normalizedCollateral = currentMargin .mul(loanPosition.loanTokenAmountFilled) .div(desiredMargin); if (loanPosition.loanTokenAmountFilled > normalizedCollateral) { closeAmount = loanPosition.loanTokenAmountFilled .sub(normalizedCollateral); } else { closeAmount = loanPosition.loanTokenAmountFilled; } } else { // loans passed their end dates will fully closed if possible closeAmount = loanPosition.loanTokenAmountFilled; } if (maxCloseAmount == 0 || maxCloseAmount > loanPosition.loanTokenAmountFilled) { closeAmount = Math.min256(closeAmount, loanPosition.loanTokenAmountFilled); } else { closeAmount = Math.min256(closeAmount, maxCloseAmount); } uint256 loanAmountBought; if (loanOrder.interestAmount != 0) { (loanAmountBought,) = _settleInterest( loanOrder, loanPosition, closeAmount, true, // sendToOracle true // refundToCollateral ); } uint256 closeAmountUsable; if (loanPosition.positionTokenAddressFilled != loanOrder.loanTokenAddress) { if (loanPosition.positionTokenAmountFilled == 0) { loanPosition.positionTokenAddressFilled = loanOrder.loanTokenAddress; if (loanAmountBought != 0) { closeAmountUsable = loanAmountBought; } } else { // If the position token is not the loan token, then we need to buy back the loan token prior to closing the loan. // transfer the current position token to the Oracle contract if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, oracleAddresses[loanOrder.oracleAddress], loanPosition.positionTokenAmountFilled)) { revert("MiscFunctions::liquidatePosition: BZxVault.withdrawToken failed"); } uint256 positionTokenAmountUsed; (closeAmountUsable, positionTokenAmountUsed) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).liquidatePosition( loanOrder, loanPosition, closeAmount < loanPosition.loanTokenAmountFilled ? closeAmount .sub(loanAmountBought) : MAX_UINT // maxDestTokenAmount ); if (positionTokenAmountUsed == 0) { revert("BZxLoanHealth::liquidatePosition: liquidation not allowed"); } if (loanAmountBought != 0) { closeAmountUsable = closeAmountUsable .add(loanAmountBought); } if (closeAmount == loanPosition.loanTokenAmountFilled) { if (loanPosition.positionTokenAmountFilled > positionTokenAmountUsed) { // left over sourceToken needs to be dispursed if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, closeAmountUsable >= loanPosition.loanTokenAmountFilled ? loanPosition.trader : orderLender[loanOrderHash], loanPosition.positionTokenAmountFilled.sub(positionTokenAmountUsed) )) { revert("BZxLoanHealth::liquidatePosition: BZxVault.withdrawToken excess failed"); } } // the loan token becomes the new position token loanPosition.positionTokenAddressFilled = loanOrder.loanTokenAddress; loanPosition.positionTokenAmountFilled = closeAmountUsable; } else { loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(positionTokenAmountUsed); } } } else { if (loanPosition.positionTokenAmountFilled > closeAmount) { closeAmountUsable = closeAmount; loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(closeAmount); } else { closeAmountUsable = loanPosition.positionTokenAmountFilled; loanPosition.positionTokenAmountFilled = 0; } if (loanAmountBought != 0) { closeAmountUsable = closeAmountUsable .add(loanAmountBought); } } require(_finalizeLoan( loanOrder, loanPosition, // needs to be storage closeAmount, closeAmountUsable, true, // isLiquidation gasUsed // initial used gas, collected in modifier ),"BZxLoanHealth::liquidatePosition: _finalizeLoan failed"); return true; } /// @dev Called to close a loan in full /// @param loanOrderHash A unique hash representing the loan order /// @return True on success function closeLoan( bytes32 loanOrderHash) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, msg.sender, // borrower gasUsed // initial used gas, collected in modifier ); } /// @dev Called to close a loan in full for someone else /// @param loanOrderHash A unique hash representing the loan order /// @param borrower The borrower whose loan to close in full (for margin trades, this has to equal the sender) /// @return True on success function closeLoanForBorrower( bytes32 loanOrderHash, address borrower) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, borrower, gasUsed // initial used gas, collected in modifier ); } /// @dev Called by an admin to force close a loan early and return assets to the lender and trader as is. /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @return True on success function forceCloseLoan( bytes32 loanOrderHash, address trader) external onlyOwner tracksGas returns (bool) { uint256 positionId = loanPositionsIds[loanOrderHash][trader]; LoanPosition storage loanPosition = loanPositions[positionId]; require(loanPosition.loanTokenAmountFilled != 0 && loanPosition.active); LoanOrder memory loanOrder = orders[loanOrderHash]; require(loanOrder.loanTokenAddress != address(0)); if (loanOrder.interestAmount > 0) { _settleInterest( loanOrder, loanPosition, loanPosition.loanTokenAmountFilled, // closeAmount false, // sendToOracle false // interestToCollateralSwap ); } if (loanPosition.collateralTokenAmountFilled > 0) { require(BZxVault(vaultContract).withdrawToken( loanPosition.collateralTokenAddressFilled, loanPosition.trader, loanPosition.collateralTokenAmountFilled )); } if (loanPosition.positionTokenAmountFilled > 0) { require(BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, orderLender[loanOrderHash], loanPosition.positionTokenAmountFilled )); } uint256 closeAmount = loanPosition.loanTokenAmountFilled; loanPosition.positionTokenAmountFilled = closeAmount; // for historical reference loanPosition.loanTokenAmountFilled = 0; //loanPosition.loanTokenAmountUsed = 0; <- not used yet loanPosition.active = false; _removePosition( loanOrderHash, loanPosition.trader); emit LogLoanClosed( orderLender[loanOrderHash], loanPosition.trader, msg.sender, // loanCloser false, // isLiquidation loanOrder.loanOrderHash, loanPosition.positionId ); reentrancyLock = REENTRANCY_GUARD_FREE; // reentrancy safe at this point require(OracleInterface(oracleAddresses[loanOrder.oracleAddress]).didCloseLoan( loanOrder, loanPosition, msg.sender, // loanCloser closeAmount, false, // isLiquidation gasUsed )); return true; } /* * Constant public functions */ /// @dev Checks the conditions for liquidation with the oracle /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @return True if liquidation should occur, false otherwise function shouldLiquidate( bytes32 loanOrderHash, address trader) public view returns (bool) { LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { return false; } LoanPosition memory loanPosition = loanPositions[loanPositionsIds[loanOrderHash][trader]]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { return false; } if (block.timestamp >= loanPosition.loanEndUnixTimestampSec) { return true; // expired loan } return OracleInterface(oracleAddresses[loanOrder.oracleAddress]).shouldLiquidate( loanOrder, loanPosition); } }
@dev Called to close a loan in full for someone else @param loanOrderHash A unique hash representing the loan order @param borrower The borrower whose loan to close in full (for margin trades, this has to equal the sender) @return True on success
function closeLoanForBorrower( bytes32 loanOrderHash, address borrower) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, borrower, ); }
7,227,986
[ 1, 8185, 358, 1746, 279, 28183, 316, 1983, 364, 18626, 469, 225, 28183, 2448, 2310, 432, 3089, 1651, 5123, 326, 28183, 1353, 225, 29759, 264, 1021, 29759, 264, 8272, 28183, 358, 1746, 316, 1983, 261, 1884, 7333, 1284, 5489, 16, 333, 711, 358, 3959, 326, 5793, 13, 327, 1053, 603, 2216, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1746, 1504, 304, 1290, 38, 15318, 264, 12, 203, 3639, 1731, 1578, 28183, 2448, 2310, 16, 203, 3639, 1758, 29759, 264, 13, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 13933, 27998, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 4412, 1504, 304, 12, 203, 5411, 28183, 2448, 2310, 16, 203, 5411, 29759, 264, 16, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-06 */ /* The internet is full of trolls, and in the realm of crypto, the population is especially concentrated. Come visit us at t.me/TrollsOfTelegram and see what type of troll you are and get rewarded with Ethereum. The Trolls token has a special wallet to reward those most active in telegram and/or the ones who exhibit the best troll repellent. 10% Tax with autoLP & a wallet to feed the trolls of telegram (the holders) The more active one is in Telegram & Twitter, the more ETH you will earn. */ /* Trolls Token t.me/TelegramOfTrolls The internet is full of trolls, and in the realm of crypto, the population is especially concentrated. Come visit us at t.me/TrollsOfTelegram and see what type of troll you are and get rewarded with Ethereum from the special wallet for those most active in telegram and/or the ones who exhibit the best troll repellent. 🏵$TROLLS🏵 Launch Dec 6, 2021 Total Supply: 3,750,000,000 Max Txn: 3% (122,500,000) Max Wallet: 5% 💎10% Tax featuring an Auto LP and the TROLL TAX to feed the trolls of Telegram. */ // SPDX-License-Identifier: MIT 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); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; 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 transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } 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 swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } abstract contract IERC20Extented is IERC20 { function decimals() external view virtual returns (uint8); function name() external view virtual returns (string memory); function symbol() external view virtual returns (string memory); } contract TrollsToken is Context, IERC20, IERC20Extented, Ownable { using SafeMath for uint256; string private constant _name = "Trolls Token"; string private constant _symbol = "TROLLS"; uint8 private constant _decimals = 9; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant _tTotal = 3750 * 1e6 * 1e9; // 3,750,000,000 uint256 public _priceImpact = 2; uint256 private _firstBlock; uint256 private _botBlocks; uint256 public _maxWalletAmount; uint256 private _maxSellAmountETH = 5 * 1e9; // 5 ETH uint256 private _minBuyETH = 0; //1 * 1e7; // 0.01 ETH uint256 private _minSellETH = 0; //1 * 1e7; // 0.01 ETH // fees uint256 public _liquidityFee = 40; // divided by 1000 uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 40; // divided by 1000 uint256 private _previousMarketingFee = _marketingFee; uint256 public _trollFee = 10; // divided by 1000 uint256 private _previousTrollFee = _trollFee; uint256 private _cardsFee = 10; // divided by 1000 uint256 private _previousCardsFee = _cardsFee; uint256 public _burnFee = 0; // divided by 1000 uint256 private _previousBurnFee = _burnFee; uint256 private _marketingPercent = 750; uint256 private _trollPercent = 125; uint256 private _cardsPercent = 125; struct FeeBreakdown { uint256 tLiquidity; uint256 tMarketing; uint256 tTroll; uint256 tCards; uint256 tBurn; uint256 tAmount; } mapping(address => bool) private bots; address payable private _marketingAddress = payable(0xE85EC5e9b863eEcD8EfE12b77EcA2e2Cc8Fd1155); address payable private _trollAddress = payable(0x2008FbC22476fE372A8a449a832CEa4e3b517B1c); address payable private _cards; address payable constant private _burnAddress = payable(0x000000000000000000000000000000000000dEaD); address private presaleRouter; address private presaleAddress; IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; uint256 private _maxTxAmount; bool private tradingOpen = false; bool private inSwap = false; bool private presale = true; bool private pairSwapped = false; bool public _priceImpactSellLimitEnabled = false; bool public _ETHsellLimitEnabled = false; event EndedPresale(bool presale); event MaxTxAmountUpdated(uint256 _maxTxAmount); event PercentsUpdated(uint256 _marketingPercent, uint256 _trollPercent, uint256 _cardsPercent); event FeesUpdated(uint256 _marketingFee, uint256 _liquidityFee, uint256 _trollFee, uint256 _cardsFee, uint256 _burnFee); event PriceImpactUpdated(uint256 _priceImpact); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address cards) { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); IERC20(uniswapV2Pair).approve(address(uniswapV2Router),type(uint256).max); _maxTxAmount = _tTotal; // start off transaction limit at 100% of total supply _maxWalletAmount = _tTotal.div(1); // 100% _priceImpact = 100; cards = _cards; _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function airdrop(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner { require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i]; _transfer(msg.sender, wallet, amount); } } function name() override external pure returns (string memory) { return _name; } function symbol() override external pure returns (string memory) { return _symbol; } function decimals() override external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function isBot(address account) public view returns (bool) { return bots[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function removeAllFee() private { if (_marketingFee == 0 && _liquidityFee == 0 && _trollFee == 0 && _cardsFee == 0 && _burnFee == 0) return; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTrollFee = _trollFee; _previousCardsFee = _cardsFee; _previousBurnFee = _burnFee; _marketingFee = 0; _liquidityFee = 0; _trollFee = 0; _cardsFee = 0; _burnFee = 0; } function setBotFee() private { _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTrollFee = _trollFee; _previousCardsFee = _cardsFee; _previousBurnFee = _burnFee; _marketingFee = 300; _liquidityFee = 300; _trollFee = 18; _cardsFee = 0; _burnFee = 0; } function restoreAllFee() private { _marketingFee = _previousMarketingFee; _liquidityFee = _previousLiquidityFee; _trollFee = _previousTrollFee; _cardsFee = _previousCardsFee; _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); } // calculate price based on pair reserves function getTokenPriceETH(uint256 amount) external view returns(uint256) { IERC20Extented token0 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token0());//Meliodas IERC20Extented token1 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token1());//eth require(token0.decimals() != 0, "ERR: decimals cannot be zero"); (uint112 Res0, uint112 Res1,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); if(pairSwapped) { token0 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token1());//Meliodas token1 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token0());//eth (Res1, Res0,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); } uint res1 = Res1*(10**token0.decimals()); return((amount*res1)/(Res0*(10**token0.decimals()))); // return amount of token1 needed to buy token0 } 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"); bool takeFee = true; if (from != owner() && to != owner() && !presale && from != address(this) && to != address(this)) { require(tradingOpen); if (from != presaleRouter && from != presaleAddress) { require(amount <= _maxTxAmount); } if (from == uniswapV2Pair && to != address(uniswapV2Router)) {//buys if (block.timestamp <= _firstBlock.add(_botBlocks) && from != presaleRouter && from != presaleAddress) { bots[to] = true; } uint256 ethAmount = this.getTokenPriceETH(amount); require(ethAmount >= _minBuyETH, "you must buy at least min ETH worth of token"); require(balanceOf(to).add(amount) <= _maxWalletAmount, "wallet balance after transfer must be less than max wallet amount"); } if (!inSwap && from != uniswapV2Pair) { //sells, transfers require(!bots[from] && !bots[to]); uint256 ethAmount = this.getTokenPriceETH(amount); require(ethAmount >= _minSellETH, "you must sell at least the min ETH worth of token"); if (_ETHsellLimitEnabled) { require(ethAmount <= _maxSellAmountETH, 'you cannot sell more than the max ETH amount per transaction'); } else if (_priceImpactSellLimitEnabled) { require(amount <= balanceOf(uniswapV2Pair).mul(_priceImpact).div(100)); // price impact limit } if(to != uniswapV2Pair) { require(balanceOf(to).add(amount) <= _maxWalletAmount, "wallet balance after transfer must be less than max wallet amount"); } uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance > 0) { swapAndLiquify(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if (_isExcludedFromFee[from] || _isExcludedFromFee[to] || presale ) { takeFee = false; } else if (bots[from] || bots[to]) { setBotFee(); takeFee = true; } if (presale) { require(from == owner() || from == presaleRouter || from == presaleAddress); } _tokenTransfer(from, to, amount, takeFee); restoreAllFee(); } 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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 autoLPamount = _liquidityFee.mul(contractTokenBalance).div(_marketingFee.add(_trollFee).add(_cardsFee).add(_liquidityFee)); // split the contract balance into halves uint256 half = autoLPamount.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(otherHalf); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = ((address(this).balance.sub(initialBalance)).mul(half)).div(otherHalf); addLiquidity(half, newBalance); } function sendETHToFee(uint256 amount) private { _trollAddress.transfer(amount.mul(_trollPercent).div(1000)); _cards.transfer(amount.mul(_cardsPercent).div(1000)); _marketingAddress.transfer(amount.mul(_marketingPercent).div(1000)); } function openTrading(uint256 botBlocks) private { _firstBlock = block.timestamp; _botBlocks = botBlocks; tradingOpen = true; } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > 0) { swapTokensForEth(contractBalance); } } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(contractETHBalance); } } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) { removeAllFee(); } _transferStandard(sender, recipient, amount); restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 amount) private { FeeBreakdown memory fees; fees.tMarketing = amount.mul(_marketingFee).div(1000); fees.tLiquidity = amount.mul(_liquidityFee).div(1000); fees.tTroll = amount.mul(_trollFee).div(1000); fees.tCards = amount.mul(_cardsFee).div(1000); fees.tBurn = amount.mul(_burnFee).div(1000); fees.tAmount = amount.sub(fees.tMarketing).sub(fees.tLiquidity).sub(fees.tTroll).sub(fees.tCards).sub(fees.tBurn); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(fees.tAmount); _balances[address(this)] = _balances[address(this)].add(fees.tMarketing.add(fees.tLiquidity).add(fees.tTroll).add(fees.tCards)); _balances[_burnAddress] = _balances[_burnAddress].add(fees.tBurn); emit Transfer(sender, recipient, fees.tAmount); } receive() external payable {} function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner() { _isExcludedFromFee[account] = false; } function removeBot(address account) external onlyOwner() { bots[account] = false; } function addBot(address account) external onlyOwner() { bots[account] = true; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount > _tTotal.div(10000), "Amount must be greater than 0.01% of supply"); require(maxTxAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxTxAmount = maxTxAmount; emit MaxTxAmountUpdated(_maxTxAmount); } function setMaxWalletAmount(uint256 maxWalletAmount) external onlyOwner() { require(maxWalletAmount > _tTotal.div(200), "Amount must be greater than 0.5% of supply"); require(maxWalletAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxWalletAmount = maxWalletAmount; } function setTaxes(uint256 marketingFee, uint256 liquidityFee, uint256 trollFee, uint256 cardsFee, uint256 burnFee) external onlyOwner() { uint256 totalFee = marketingFee.add(liquidityFee).add(trollFee).add(cardsFee).add(burnFee); require(totalFee.div(10) < 50, "Sum of fees must be less than 50"); _marketingFee = marketingFee; _liquidityFee = liquidityFee; _trollFee = trollFee; _cardsFee = cardsFee; _burnFee = burnFee; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTrollFee = _trollFee; _previousCardsFee = _cardsFee; _previousBurnFee = _burnFee; uint256 totalETHfees = _marketingFee.add(_trollFee).add(_cardsFee); _marketingPercent = (_marketingFee.mul(1000)).div(totalETHfees); _trollPercent = (_trollFee.mul(1000)).div(totalETHfees); _cardsPercent = (_cardsFee.mul(1000)).div(totalETHfees); emit FeesUpdated(_marketingFee, _liquidityFee, _trollFee, _cardsFee, _burnFee); } function setPercents(uint256 marketingPercent, uint256 trollPercent, uint256 cardsPercent) external onlyOwner() { _marketingPercent = marketingPercent; _trollPercent = trollPercent; _cardsPercent = cardsPercent; emit PercentsUpdated(_marketingPercent, _trollPercent, _cardsPercent); } function setPriceImpact(uint256 priceImpact) external onlyOwner() { require(priceImpact <= 100, "max price impact must be less than or equal to 100"); require(priceImpact > 0, "cant prevent sells, choose value greater than 0"); _priceImpact = priceImpact; emit PriceImpactUpdated(_priceImpact); } function endPresale(uint256 botBlocks) external onlyOwner() { require(presale == true, "presale already ended"); presale = false; openTrading(botBlocks); emit EndedPresale(presale); } function updatePairSwapped(bool swapped) external onlyOwner() { pairSwapped = swapped; } function updateMinBuySellETH(uint256 minBuyETH, uint256 minSellETH) external onlyOwner() { require(minBuyETH <= 1e7, "cant make the limit higher than 0.1 ETH"); require(minSellETH <= 1e7, "cant make the limit higher than 0.1 ETH"); _minBuyETH = minBuyETH; _minSellETH = minSellETH; } function updateMaxSellAmountETH(uint256 maxSellETH) external onlyOwner() { require(maxSellETH >= 1e9, "cant make the limit lower than 1 ETH"); _maxSellAmountETH = maxSellETH; } function updateCards(address payable cards) external onlyOwner() { _cards = cards; } function updateMarketingAddress(address payable marketingAddress) external onlyOwner() { _marketingAddress = marketingAddress; } function updateTrollAddress(address payable trollAddress) external onlyOwner() { _trollAddress = trollAddress; } function enableETHsellLimit() external onlyOwner() { require(_ETHsellLimitEnabled == false, "already enabled"); _ETHsellLimitEnabled = true; _priceImpactSellLimitEnabled = false; } function disableETHsellLimit() external onlyOwner() { require(_ETHsellLimitEnabled == true, "already disabled"); _ETHsellLimitEnabled = false; } function enablePriceImpactSellLimit() external onlyOwner() { require(_priceImpactSellLimitEnabled == false, "already enabled"); _priceImpactSellLimitEnabled = true; _ETHsellLimitEnabled = false; } function disablePriceImpactSellLimit() external onlyOwner() { require(_priceImpactSellLimitEnabled == true, "already disabled"); _priceImpactSellLimitEnabled = false; } }
price impact limit
require(amount <= balanceOf(uniswapV2Pair).mul(_priceImpact).div(100));
2,441,257
[ 1, 8694, 15800, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 10792, 2583, 12, 8949, 1648, 11013, 951, 12, 318, 291, 91, 438, 58, 22, 4154, 2934, 16411, 24899, 8694, 22683, 621, 2934, 2892, 12, 6625, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xa943F863fA69ff4F6D9022843Fb861BBEe45B2ce/sources/TangleBundle0.sol
@notice Returns the amount of a Tangle holder's Tangle a spender is allowed to spend @param _owner The Tangle token holder's address @param _spender The spender's address @return The amount that can be spent
function allowance(address _owner, address _spender) external view returns (uint) { return SLib.getS().allowances[_owner][_spender]; }
17,007,029
[ 1, 1356, 326, 3844, 434, 279, 399, 4341, 10438, 1807, 399, 4341, 279, 17571, 264, 353, 2935, 358, 17571, 225, 389, 8443, 1021, 399, 4341, 1147, 10438, 1807, 1758, 225, 389, 87, 1302, 264, 1021, 17571, 264, 1807, 1758, 327, 1021, 3844, 716, 848, 506, 26515, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 203, 3639, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 348, 5664, 18, 588, 55, 7675, 5965, 6872, 63, 67, 8443, 6362, 67, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xF66C6fDBDD7d57dD14D23d0C8A4E58Cc4869bBfa/sources/SaferERC20.sol
* @title SaferERC20 @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 SaferERC20 for IERC20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./
library SaferERC20 { using Address for address; function safeTransferToSelf(IERC20 token, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { require(msg.value >= value, "insuff.eth"); uint256 dust = msg.value - value; if(dust > 0) { payable(msg.sender).transfer(dust); } return value; } else { require(token.allowance(msg.sender, address(this)) >= value, "insuff.approval"); return safeTransferFromWithAmount(token, msg.sender, address(this), value); } } function safeTransferToSelf(IERC20 token, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { require(msg.value >= value, "insuff.eth"); uint256 dust = msg.value - value; if(dust > 0) { payable(msg.sender).transfer(dust); } return value; } else { require(token.allowance(msg.sender, address(this)) >= value, "insuff.approval"); return safeTransferFromWithAmount(token, msg.sender, address(this), value); } } function safeTransferToSelf(IERC20 token, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { require(msg.value >= value, "insuff.eth"); uint256 dust = msg.value - value; if(dust > 0) { payable(msg.sender).transfer(dust); } return value; } else { require(token.allowance(msg.sender, address(this)) >= value, "insuff.approval"); return safeTransferFromWithAmount(token, msg.sender, address(this), value); } } function safeTransferToSelf(IERC20 token, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { require(msg.value >= value, "insuff.eth"); uint256 dust = msg.value - value; if(dust > 0) { payable(msg.sender).transfer(dust); } return value; } else { require(token.allowance(msg.sender, address(this)) >= value, "insuff.approval"); return safeTransferFromWithAmount(token, msg.sender, address(this), value); } } function safeBalanceOf(IERC20 token, address account) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return account.balance; } else { return token.balanceOf(account); } } function safeBalanceOf(IERC20 token, address account) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return account.balance; } else { return token.balanceOf(account); } } function safeBalanceOf(IERC20 token, address account) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return account.balance; } else { return token.balanceOf(account); } } function safeTransfer(IERC20 token, address to, uint256 value) internal { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); } else { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } } function safeTransfer(IERC20 token, address to, uint256 value) internal { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); } else { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } } function safeTransfer(IERC20 token, address to, uint256 value) internal { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); } else { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } } function safeTransferWithAmount(IERC20 token, address to, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); return value; } else { uint256 balanceBefore = token.balanceOf(to); safeTransfer(token, to, value); uint256 balanceAfter = token.balanceOf(to); return balanceAfter - balanceBefore; } } function safeTransferWithAmount(IERC20 token, address to, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); return value; } else { uint256 balanceBefore = token.balanceOf(to); safeTransfer(token, to, value); uint256 balanceAfter = token.balanceOf(to); return balanceAfter - balanceBefore; } } function safeTransferWithAmount(IERC20 token, address to, uint256 value) internal returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { payable(to).transfer(value); return value; } else { uint256 balanceBefore = token.balanceOf(to); safeTransfer(token, to, value); uint256 balanceAfter = token.balanceOf(to); return balanceAfter - balanceBefore; } } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(address(token) != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), "safeTransferFrom.eth.unsupported"); _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } function safeTransferFromWithAmount(IERC20 token, address from, address to, uint256 value) internal returns (uint256) { uint256 balanceBefore = token.balanceOf(to); safeTransferFrom(token, from, to, value); uint256 balanceAfter = token.balanceOf(to); return balanceAfter - balanceBefore; } function safeDecimals(IERC20 token) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return 18; } else { return IERC20Metadata(address(token)).decimals(); } } function safeDecimals(IERC20 token) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return 18; } else { return IERC20Metadata(address(token)).decimals(); } } function safeDecimals(IERC20 token) internal view returns (uint256) { if(address(token) == address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)) { return 18; } else { return IERC20Metadata(address(token)).decimals(); } } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SaferERC20: decreased allowance below zero"); forceApprove(token, spender, oldAllowance - value); } } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SaferERC20: decreased allowance below zero"); forceApprove(token, spender, oldAllowance - value); } } function forceApprove(IERC20 token, address spender, uint256 value) internal { require( address(token) != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), "forceApprove.eth.unsupported" ); bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } function forceApprove(IERC20 token, address spender, uint256 value) internal { require( address(token) != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), "forceApprove.eth.unsupported" ); bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require( address(token) != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), "safePermit.eth.unsupported" ); uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SaferERC20: permit did not succeed"); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SaferERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SaferERC20: ERC20 operation did not succeed"); } function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; } }
3,949,113
[ 1, 55, 69, 586, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 348, 69, 586, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 348, 69, 586, 654, 39, 3462, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 203, 565, 445, 4183, 5912, 774, 10084, 12, 45, 654, 39, 3462, 1147, 16, 2254, 5034, 460, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 12, 2867, 12, 2316, 13, 422, 1758, 12, 20, 6356, 74, 42, 74, 42, 1403, 2246, 25449, 2246, 74, 2246, 74, 8998, 42, 1403, 2246, 42, 9460, 42, 74, 2246, 42, 74, 42, 3719, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 1545, 460, 16, 315, 2679, 3809, 18, 546, 8863, 203, 5411, 2254, 5034, 302, 641, 273, 1234, 18, 1132, 300, 460, 31, 203, 5411, 309, 12, 72, 641, 405, 374, 13, 288, 203, 7734, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 72, 641, 1769, 203, 5411, 289, 203, 5411, 327, 460, 31, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 2583, 12, 2316, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 460, 16, 315, 2679, 3809, 18, 12908, 1125, 8863, 203, 5411, 327, 4183, 5912, 1265, 1190, 6275, 12, 2316, 16, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 460, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 774, 10084, 12, 45, 654, 39, 3462, 1147, 16, 2254, 5034, 460, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 12, 2867, 12, 2316, 13, 422, 1758, 12, 20, 6356, 74, 42, 74, 42, 1403, 2246, 25449, 2246, 74, 2246, 74, 8998, 42, 2 ]
./full_match/1/0x9eE4530EE122E82c700Ef355CC9b8F11079AE636/sources/contracts/protocol/libraries/helpers/Errors.sol
* @title Errors library @author Sturdy, inspiration from Aave @notice Defines the error messages emitted by the different contracts of the Sturdy protocol @dev Error messages prefix glossary: - VL = ValidationLogic - MATH = Math libraries - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) - AT = AToken - SDT = StableDebtToken - VDT = VariableDebtToken - LP = LendingPool - LPAPR = LendingPoolAddressesProviderRegistry - LPC = LendingPoolConfiguration - RL = ReserveLogic - LPCM = LendingPoolCollateralManager - P = Pausable/common errorscontract specific errors
library Errors { string internal constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string internal constant MATH_MULTIPLICATION_OVERFLOW = '48'; string internal constant MATH_ADDITION_OVERFLOW = '49'; string internal constant MATH_DIVISION_BY_ZERO = '50'; string internal constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string internal constant LP_FAILED_COLLATERAL_SWAP = '60'; string internal constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string internal constant LP_REENTRANCY_NOT_ALLOWED = '62'; string internal constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string internal constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string internal constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string internal constant RC_INVALID_LTV = '67'; string internal constant RC_INVALID_LIQ_THRESHOLD = '68'; string internal constant RC_INVALID_LIQ_BONUS = '69'; string internal constant RC_INVALID_DECIMALS = '70'; string internal constant RC_INVALID_RESERVE_FACTOR = '71'; string internal constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string internal constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string internal constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string internal constant UL_INVALID_INDEX = '77'; string internal constant LP_NOT_CONTRACT = '78'; string internal constant SDT_STABLE_DEBT_OVERFLOW = '79'; string internal constant SDT_BURN_EXCEEDS_BALANCE = '80'; string internal constant VT_COLLATERAL_DEPOSIT_VAULT_UNAVAILABLE = '91'; string internal constant LP_LIQUIDATION_CONVERT_FAILED = '92'; string internal constant YD_VR_ASSET_NOT_REGISTERED = '110'; pragma solidity ^0.8.0; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } }
3,217,715
[ 1, 4229, 5313, 225, 934, 295, 15680, 16, 316, 1752, 5447, 628, 432, 836, 225, 18003, 281, 326, 555, 2743, 17826, 635, 326, 3775, 20092, 434, 326, 934, 295, 15680, 1771, 225, 1068, 2743, 1633, 30256, 30, 225, 300, 776, 48, 273, 5684, 20556, 225, 300, 28394, 273, 2361, 14732, 225, 300, 21088, 273, 5658, 1334, 3086, 2430, 261, 789, 969, 16, 7110, 758, 23602, 1345, 471, 934, 429, 758, 23602, 1345, 13, 225, 300, 14464, 273, 432, 1345, 225, 300, 348, 9081, 273, 934, 429, 758, 23602, 1345, 225, 300, 776, 9081, 273, 7110, 758, 23602, 1345, 225, 300, 511, 52, 273, 511, 2846, 2864, 225, 300, 511, 52, 2203, 54, 273, 511, 2846, 2864, 7148, 2249, 4243, 225, 300, 511, 3513, 273, 511, 2846, 2864, 1750, 225, 300, 534, 48, 273, 1124, 6527, 20556, 225, 300, 511, 3513, 49, 273, 511, 2846, 2864, 13535, 2045, 287, 1318, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 9372, 288, 203, 203, 225, 533, 2713, 5381, 511, 52, 67, 706, 2248, 28175, 67, 42, 16504, 1502, 1258, 67, 16785, 273, 296, 6030, 13506, 203, 225, 533, 2713, 5381, 28394, 67, 24683, 11154, 67, 12959, 17430, 273, 296, 8875, 13506, 203, 225, 533, 2713, 5381, 28394, 67, 8355, 7022, 67, 12959, 17430, 273, 296, 7616, 13506, 203, 225, 533, 2713, 5381, 28394, 67, 2565, 25216, 67, 6486, 67, 24968, 273, 296, 3361, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 11965, 67, 862, 11389, 67, 9147, 67, 4935, 12190, 654, 1013, 273, 296, 10321, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 11965, 67, 4935, 12190, 654, 1013, 67, 18746, 2203, 273, 296, 4848, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 9347, 67, 12853, 67, 3033, 28092, 67, 4296, 67, 18746, 2203, 273, 296, 9498, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 862, 2222, 54, 1258, 16068, 67, 4400, 67, 16852, 273, 296, 8898, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 13730, 654, 67, 49, 5996, 67, 5948, 67, 1258, 67, 789, 6239, 273, 296, 4449, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 3417, 67, 31078, 67, 862, 2123, 3412, 55, 67, 16852, 273, 296, 9222, 13506, 203, 225, 533, 2713, 5381, 511, 52, 67, 9347, 67, 42, 16504, 67, 1502, 1258, 67, 15271, 1693, 916, 67, 14033, 273, 296, 6028, 13506, 203, 225, 533, 2713, 5381, 24206, 67, 9347, 67, 12050, 58, 273, 296, 9599, 13506, 203, 225, 533, 2713, 5381, 2 ]
/* ==================================================================== */ /* Copyright (c) 2018 The ether.online Project. All rights reserved. /* /* https://ether.online The first RPG game of blockchain /* /* authors <span class="__cf_email__" data-cfemail="1c6e757f7774697268796e326f7479725c7b717d7570327f7371">[email&#160;protected]</span> /* <span class="__cf_email__" data-cfemail="6211110711170c060b0c0522050f030b0e4c010d0f">[email&#160;protected]</span> /* ==================================================================== */ pragma solidity ^0.4.20; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { 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) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function approve(address _approved, uint256 _tokenId) external; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } function withdraw(address _target, uint256 _amount) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_amount > 0); address receiver = _target == address(0) ? addrFinance : _target; uint256 balance = this.balance; if (_amount < balance) { receiver.transfer(_amount); } else { receiver.transfer(this.balance); } } } interface IDataMining { function getRecommender(address _target) external view returns(address); function subFreeMineral(address _target) external returns(bool); } interface IDataEquip { function isEquiped(address _target, uint256 _tokenId) external view returns(bool); function isEquipedAny2(address _target, uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isEquipedAny3(address _target, uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } interface IDataAuction { function isOnSaleAny2(uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isOnSaleAny3(uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } interface IBitGuildToken { function transfer(address _to, uint256 _value) external; function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external; function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool); function balanceOf(address _from) external view returns(uint256); } contract Random { uint256 _seed; function _rand() internal returns (uint256) { _seed = uint256(keccak256(_seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty)); return _seed; } function _randBySeed(uint256 _outSeed) internal view returns (uint256) { return uint256(keccak256(_outSeed, block.blockhash(block.number - 1), block.coinbase, block.difficulty)); } } /** * @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; } } contract WarToken is ERC721, AccessAdmin { /// @dev The equipment info struct Fashion { uint16 protoId; // 0 Equipment ID uint16 quality; // 1 Rarity: 1 Coarse/2 Good/3 Rare/4 Epic/5 Legendary uint16 pos; // 2 Slots: 1 Weapon/2 Hat/3 Cloth/4 Pant/5 Shoes/9 Pets uint16 health; // 3 Health uint16 atkMin; // 4 Min attack uint16 atkMax; // 5 Max attack uint16 defence; // 6 Defennse uint16 crit; // 7 Critical rate uint16 isPercent; // 8 Attr value type uint16 attrExt1; // 9 future stat 1 uint16 attrExt2; // 10 future stat 2 uint16 attrExt3; // 11 future stat 3 } /// @dev All equipments tokenArray (not exceeding 2^32-1) Fashion[] public fashionArray; /// @dev Amount of tokens destroyed uint256 destroyFashionCount; /// @dev Equipment token ID vs owner address mapping (uint256 => address) fashionIdToOwner; /// @dev Equipments owner by the owner (array) mapping (address => uint256[]) ownerToFashionArray; /// @dev Equipment token ID search in owner array mapping (uint256 => uint256) fashionIdToOwnerIndex; /// @dev The authorized address for each WAR mapping (uint256 => address) fashionIdToApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) operatorToApprovals; /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } /// @dev This emits when the approved address for an WAR is changed or reaffirmed. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev This emits when the equipment ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when the equipment created event CreateFashion(address indexed owner, uint256 tokenId, uint16 protoId, uint16 quality, uint16 pos, uint16 createType); /// @dev This emits when the equipment&#39;s attributes changed event ChangeFashion(address indexed owner, uint256 tokenId, uint16 changeType); /// @dev This emits when the equipment destroyed event DeleteFashion(address indexed owner, uint256 tokenId, uint16 deleteType); function WarToken() public { addrAdmin = msg.sender; fashionArray.length += 1; } // modifier /// @dev Check if token ID is valid modifier isValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= fashionArray.length); require(fashionIdToOwner[_tokenId] != address(0)); _; } modifier canTransfer(uint256 _tokenId) { address owner = fashionIdToOwner[_tokenId]; require(msg.sender == owner || msg.sender == fashionIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]); _; } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } function name() public pure returns(string) { return "WAR Token"; } function symbol() public pure returns(string) { return "WAR"; } /// @dev Search for token quantity address /// @param _owner Address that needs to be searched /// @return Returns token quantity function balanceOf(address _owner) external view returns(uint256) { require(_owner != address(0)); return ownerToFashionArray[_owner].length; } /// @dev Find the owner of an WAR /// @param _tokenId The tokenId of WAR /// @return Give The address of the owner of this WAR function ownerOf(uint256 _tokenId) external view /*isValidToken(_tokenId)*/ returns (address owner) { return fashionIdToOwner[_tokenId]; } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, data); } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @dev Transfer ownership of an WAR, &#39;_to&#39; must be a vaild address, or the WAR will lost /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); } /// @dev Set or reaffirm the approved address for an WAR /// @param _approved The new approved WAR controller /// @param _tokenId The WAR to approve function approve(address _approved, uint256 _tokenId) external whenNotPaused { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(msg.sender == owner || operatorToApprovals[owner][msg.sender]); fashionIdToApprovals[_tokenId] = _approved; Approval(owner, _approved, _tokenId); } /// @dev Enable or disable approval for a third party ("operator") to manage all your asset. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external whenNotPaused { operatorToApprovals[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Get the approved address for a single WAR /// @param _tokenId The WAR to find the approved address for /// @return The approved address for this WAR, or the zero address if there is none function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) { return fashionIdToApprovals[_tokenId]; } /// @dev Query if an address is an authorized operator for another address /// @param _owner The address that owns the WARs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorToApprovals[_owner][_operator]; } /// @dev Count WARs tracked by this contract /// @return A count of valid WARs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return fashionArray.length - destroyFashionCount - 1; } /// @dev Do the real transfer with out any condition checking /// @param _from The old owner of this WAR(If created: 0x0) /// @param _to The new owner of this WAR /// @param _tokenId The tokenId of the WAR function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); // If the WAR is not the element of array, change it to with the last if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; if (fashionIdToApprovals[_tokenId] != address(0)) { delete fashionIdToApprovals[_tokenId]; } } // Give the WAR to &#39;_to&#39; fashionIdToOwner[_tokenId] = _to; ownerToFashionArray[_to].push(_tokenId); fashionIdToOwnerIndex[_tokenId] = ownerToFashionArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); // bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; require(retval == 0xf0b9e5ba); } //---------------------------------------------------------------------------------------------------------- /// @dev Equipment creation /// @param _owner Owner of the equipment created /// @param _attrs Attributes of the equipment created /// @return Token ID of the equipment created function createFashion(address _owner, uint16[9] _attrs, uint16 _createType) external whenNotPaused returns(uint256) { require(actionContracts[msg.sender]); require(_owner != address(0)); uint256 newFashionId = fashionArray.length; require(newFashionId < 4294967296); fashionArray.length += 1; Fashion storage fs = fashionArray[newFashionId]; fs.protoId = _attrs[0]; fs.quality = _attrs[1]; fs.pos = _attrs[2]; if (_attrs[3] != 0) { fs.health = _attrs[3]; } if (_attrs[4] != 0) { fs.atkMin = _attrs[4]; fs.atkMax = _attrs[5]; } if (_attrs[6] != 0) { fs.defence = _attrs[6]; } if (_attrs[7] != 0) { fs.crit = _attrs[7]; } if (_attrs[8] != 0) { fs.isPercent = _attrs[8]; } _transfer(0, _owner, newFashionId); CreateFashion(_owner, newFashionId, _attrs[0], _attrs[1], _attrs[2], _createType); return newFashionId; } /// @dev One specific attribute of the equipment modified function _changeAttrByIndex(Fashion storage _fs, uint16 _index, uint16 _val) internal { if (_index == 3) { _fs.health = _val; } else if(_index == 4) { _fs.atkMin = _val; } else if(_index == 5) { _fs.atkMax = _val; } else if(_index == 6) { _fs.defence = _val; } else if(_index == 7) { _fs.crit = _val; } else if(_index == 9) { _fs.attrExt1 = _val; } else if(_index == 10) { _fs.attrExt2 = _val; } else if(_index == 11) { _fs.attrExt3 = _val; } } /// @dev Equiment attributes modified (max 4 stats modified) /// @param _tokenId Equipment Token ID /// @param _idxArray Stats order that must be modified /// @param _params Stat value that must be modified /// @param _changeType Modification type such as enhance, socket, etc. function changeFashionAttr(uint256 _tokenId, uint16[4] _idxArray, uint16[4] _params, uint16 _changeType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); Fashion storage fs = fashionArray[_tokenId]; if (_idxArray[0] > 0) { _changeAttrByIndex(fs, _idxArray[0], _params[0]); } if (_idxArray[1] > 0) { _changeAttrByIndex(fs, _idxArray[1], _params[1]); } if (_idxArray[2] > 0) { _changeAttrByIndex(fs, _idxArray[2], _params[2]); } if (_idxArray[3] > 0) { _changeAttrByIndex(fs, _idxArray[3], _params[3]); } ChangeFashion(fashionIdToOwner[_tokenId], _tokenId, _changeType); } /// @dev Equipment destruction /// @param _tokenId Equipment Token ID /// @param _deleteType Destruction type, such as craft function destroyFashion(uint256 _tokenId, uint16 _deleteType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); address _from = fashionIdToOwner[_tokenId]; uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; fashionIdToOwner[_tokenId] = address(0); delete fashionIdToOwnerIndex[_tokenId]; destroyFashionCount += 1; Transfer(_from, 0, _tokenId); DeleteFashion(_from, _tokenId, _deleteType); } /// @dev Safe transfer by trust contracts function safeTransferByContract(uint256 _tokenId, address _to) external whenNotPaused { require(actionContracts[msg.sender]); require(_tokenId >= 1 && _tokenId <= fashionArray.length); address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner != _to); _transfer(owner, _to, _tokenId); } //---------------------------------------------------------------------------------------------------------- /// @dev Get fashion attrs by tokenId function getFashion(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[12] datas) { Fashion storage fs = fashionArray[_tokenId]; datas[0] = fs.protoId; datas[1] = fs.quality; datas[2] = fs.pos; datas[3] = fs.health; datas[4] = fs.atkMin; datas[5] = fs.atkMax; datas[6] = fs.defence; datas[7] = fs.crit; datas[8] = fs.isPercent; datas[9] = fs.attrExt1; datas[10] = fs.attrExt2; datas[11] = fs.attrExt3; } /// @dev Get tokenIds and flags by owner function getOwnFashions(address _owner) external view returns(uint256[] tokens, uint32[] flags) { require(_owner != address(0)); uint256[] storage fsArray = ownerToFashionArray[_owner]; uint256 length = fsArray.length; tokens = new uint256[](length); flags = new uint32[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = fsArray[i]; Fashion storage fs = fashionArray[fsArray[i]]; flags[i] = uint32(uint32(fs.protoId) * 100 + uint32(fs.quality) * 10 + fs.pos); } } /// @dev WAR token info returned based on Token ID transfered (64 at most) function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) { uint256 length = _tokens.length; require(length <= 64); attrs = new uint16[](length * 11); uint256 tokenId; uint256 index; for (uint256 i = 0; i < length; ++i) { tokenId = _tokens[i]; if (fashionIdToOwner[tokenId] != address(0)) { index = i * 11; Fashion storage fs = fashionArray[tokenId]; attrs[index] = fs.health; attrs[index + 1] = fs.atkMin; attrs[index + 2] = fs.atkMax; attrs[index + 3] = fs.defence; attrs[index + 4] = fs.crit; attrs[index + 5] = fs.isPercent; attrs[index + 6] = fs.attrExt1; attrs[index + 7] = fs.attrExt2; attrs[index + 8] = fs.attrExt3; } } } } contract ActionMiningPlat is Random, AccessService { using SafeMath for uint256; event MiningOrderPlatCreated(uint256 indexed index, address indexed miner, uint64 chestCnt); event MiningPlatResolved(uint256 indexed index, address indexed miner, uint64 chestCnt); struct MiningOrder { address miner; uint64 chestCnt; uint64 tmCreate; uint64 tmResolve; } /// @dev Max fashion suit id uint16 maxProtoId; /// @dev If the recommender can get reward bool isRecommendOpen; /// @dev WarToken(NFT) contract address WarToken public tokenContract; /// @dev DataMining contract address IDataMining public dataContract; /// @dev mining order array MiningOrder[] public ordersArray; /// @dev suit count mapping (uint16 => uint256) public protoIdToCount; /// @dev BitGuildToken address IBitGuildToken public bitGuildContract; /// @dev mining Price of PLAT uint256 public miningOnePlat = 600000000000000000000; uint256 public miningThreePlat = 1800000000000000000000; uint256 public miningFivePlat = 2850000000000000000000; uint256 public miningTenPlat = 5400000000000000000000; function ActionMiningPlat(address _nftAddr, uint16 _maxProtoId, address _platAddr) public { addrAdmin = msg.sender; addrService = msg.sender; addrFinance = msg.sender; tokenContract = WarToken(_nftAddr); maxProtoId = _maxProtoId; MiningOrder memory order = MiningOrder(0, 0, 1, 1); ordersArray.push(order); bitGuildContract = IBitGuildToken(_platAddr); } function() external payable { } function getPlatBalance() external view returns(uint256) { return bitGuildContract.balanceOf(this); } function withdrawPlat() external { require(msg.sender == addrFinance || msg.sender == addrAdmin); uint256 balance = bitGuildContract.balanceOf(this); require(balance > 0); bitGuildContract.transfer(addrFinance, balance); } function getOrderCount() external view returns(uint256) { return ordersArray.length - 1; } function setDataMining(address _addr) external onlyAdmin { require(_addr != address(0)); dataContract = IDataMining(_addr); } function setMaxProtoId(uint16 _maxProtoId) external onlyAdmin { require(_maxProtoId > 0 && _maxProtoId < 10000); require(_maxProtoId != maxProtoId); maxProtoId = _maxProtoId; } function setRecommendStatus(bool _isOpen) external onlyAdmin { require(_isOpen != isRecommendOpen); isRecommendOpen = _isOpen; } function setFashionSuitCount(uint16 _protoId, uint256 _cnt) external onlyAdmin { require(_protoId > 0 && _protoId <= maxProtoId); require(_cnt > 0 && _cnt <= 5); require(protoIdToCount[_protoId] != _cnt); protoIdToCount[_protoId] = _cnt; } function changePlatPrice(uint32 miningType, uint256 price) external onlyAdmin { require(price > 0 && price < 100000); uint256 newPrice = price * 1000000000000000000; if (miningType == 1) { miningOnePlat = newPrice; } else if (miningType == 3) { miningThreePlat = newPrice; } else if (miningType == 5) { miningFivePlat = newPrice; } else if (miningType == 10) { miningTenPlat = newPrice; } else { require(false); } } function _getFashionParam(uint256 _seed) internal view returns(uint16[9] attrs) { uint256 curSeed = _seed; // quality uint256 rdm = curSeed % 10000; uint16 qtyParam; if (rdm < 6900) { attrs[1] = 1; qtyParam = 0; } else if (rdm < 8700) { attrs[1] = 2; qtyParam = 1; } else if (rdm < 9600) { attrs[1] = 3; qtyParam = 2; } else if (rdm < 9900) { attrs[1] = 4; qtyParam = 4; } else { attrs[1] = 5; qtyParam = 6; } // protoId curSeed /= 10000; rdm = ((curSeed % 10000) / (9999 / maxProtoId)) + 1; attrs[0] = uint16(rdm <= maxProtoId ? rdm : maxProtoId); // pos curSeed /= 10000; uint256 tmpVal = protoIdToCount[attrs[0]]; if (tmpVal == 0) { tmpVal = 5; } rdm = ((curSeed % 10000) / (9999 / tmpVal)) + 1; uint16 pos = uint16(rdm <= tmpVal ? rdm : tmpVal); attrs[2] = pos; rdm = attrs[0] % 3; curSeed /= 10000; tmpVal = (curSeed % 10000) % 21 + 90; if (rdm == 0) { if (pos == 1) { uint256 attr = (200 + qtyParam * 200) * tmpVal / 100; // +atk attrs[4] = uint16(attr * 40 / 100); attrs[5] = uint16(attr * 160 / 100); } else if (pos == 2) { attrs[6] = uint16((40 + qtyParam * 40) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((600 + qtyParam * 600) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((60 + qtyParam * 60) * tmpVal / 100); // +def } else { attrs[3] = uint16((400 + qtyParam * 400) * tmpVal / 100); // +hp } } else if (rdm == 1) { if (pos == 1) { uint256 attr2 = (190 + qtyParam * 190) * tmpVal / 100; // +atk attrs[4] = uint16(attr2 * 50 / 100); attrs[5] = uint16(attr2 * 150 / 100); } else if (pos == 2) { attrs[6] = uint16((42 + qtyParam * 42) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((630 + qtyParam * 630) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((63 + qtyParam * 63) * tmpVal / 100); // +def } else { attrs[3] = uint16((420 + qtyParam * 420) * tmpVal / 100); // +hp } } else { if (pos == 1) { uint256 attr3 = (210 + qtyParam * 210) * tmpVal / 100; // +atk attrs[4] = uint16(attr3 * 30 / 100); attrs[5] = uint16(attr3 * 170 / 100); } else if (pos == 2) { attrs[6] = uint16((38 + qtyParam * 38) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((570 + qtyParam * 570) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((57 + qtyParam * 57) * tmpVal / 100); // +def } else { attrs[3] = uint16((380 + qtyParam * 380) * tmpVal / 100); // +hp } } attrs[8] = 0; } function _addOrder(address _miner, uint64 _chestCnt) internal { uint64 newOrderId = uint64(ordersArray.length); ordersArray.length += 1; MiningOrder storage order = ordersArray[newOrderId]; order.miner = _miner; order.chestCnt = _chestCnt; order.tmCreate = uint64(block.timestamp); MiningOrderPlatCreated(newOrderId, _miner, _chestCnt); } function _transferHelper(address _player, uint256 _platVal) private { if (isRecommendOpen) { address recommender = dataContract.getRecommender(_player); if (recommender != address(0)) { uint256 rVal = _platVal.div(10); if (rVal > 0) { bitGuildContract.transfer(recommender, rVal); } } } } function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external whenNotPaused { require(msg.sender == address(bitGuildContract)); require(_extraData.length == 1); uint32 miningType = uint32(_extraData[0]); if (miningType == 0) { require(_value == miningOnePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _miningOneSelf(_sender); } else if (miningType == 10) { require(_value == miningTenPlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 10); } else if (miningType == 3) { require(_value == miningThreePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 3); } else if (miningType == 5) { require(_value == miningFivePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 5); } else if (miningType == 1) { require(_value == miningOnePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 1); } else { require(false); } _transferHelper(_sender, _value); } function _miningOneSelf(address _sender) internal { uint256 seed = _rand(); uint16[9] memory attrs = _getFashionParam(seed); tokenContract.createFashion(_sender, attrs, 6); MiningPlatResolved(0, _sender, 1); } function miningResolve(uint256 _orderIndex, uint256 _seed) external onlyService { require(_orderIndex > 0 && _orderIndex < ordersArray.length); MiningOrder storage order = ordersArray[_orderIndex]; require(order.tmResolve == 0); address miner = order.miner; require(miner != address(0)); uint64 chestCnt = order.chestCnt; require(chestCnt >= 1 && chestCnt <= 10); uint256 rdm = _seed; uint16[9] memory attrs; for (uint64 i = 0; i < chestCnt; ++i) { rdm = _randBySeed(rdm); attrs = _getFashionParam(rdm); tokenContract.createFashion(miner, attrs, 6); } order.tmResolve = uint64(block.timestamp); MiningPlatResolved(_orderIndex, miner, chestCnt); } }
@dev Equipment token ID vs owner address
mapping (uint256 => address) fashionIdToOwner;
2,160,045
[ 1, 13142, 11568, 1147, 1599, 6195, 3410, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 30957, 28803, 5541, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3d12d0edC8f0284A49FfAc3196Ee1f796b454757/sources/contracts/dandyducks.sol
Reserve 125 Ducks for team - Giveaways/Prizes etc
contract DandyDucks is ERC721, Ownable { using SafeMath for uint256; uint public constant maxDuckPurchase = 20; uint256 public constant MAX_DUCKS = 9999; bool public saleIsActive = false; mapping(uint => string) public duckNames; uint public duckReserve = 125; event duckNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("Dandy Ducks Club", "DDC") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reserveDucks(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= duckReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } duckReserve = duckReserve.sub(_reserveAmount); } function reserveDucks(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= duckReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } duckReserve = duckReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { DUCK_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 new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A DUCK WITHIN RANGE"); return LICENSE_TEXT; } function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintDandyDuck(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Duck"); require(numberOfTokens > 0 && numberOfTokens <= maxDuckPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DUCKS, "Purchase would exceed max supply of Ducks"); require(msg.value >= duckPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DUCKS) { _safeMint(msg.sender, mintIndex); } } } function mintDandyDuck(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Duck"); require(numberOfTokens > 0 && numberOfTokens <= maxDuckPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DUCKS, "Purchase would exceed max supply of Ducks"); require(msg.value >= duckPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DUCKS) { _safeMint(msg.sender, mintIndex); } } } function mintDandyDuck(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Duck"); require(numberOfTokens > 0 && numberOfTokens <= maxDuckPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DUCKS, "Purchase would exceed max supply of Ducks"); require(msg.value >= duckPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DUCKS) { _safeMint(msg.sender, mintIndex); } } } function changeDuckName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this duck!"); require(sha256(bytes(_name)) != sha256(bytes(duckNames[_tokenId])), "New name is same as the current one"); duckNames[_tokenId] = _name; emit duckNameChange(msg.sender, _tokenId, _name); } function viewDuckName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a duck within range" ); return duckNames[_tokenId]; } function duckNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = duckNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } function duckNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = duckNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } } else { function duckNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = duckNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
8,464,423
[ 1, 607, 6527, 30616, 463, 9031, 87, 364, 5927, 300, 22374, 69, 3052, 19, 2050, 3128, 5527, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 464, 93, 40, 9031, 87, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 203, 203, 565, 2254, 1071, 5381, 943, 40, 9031, 23164, 273, 4200, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 16214, 3507, 55, 273, 30082, 31, 203, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 203, 565, 2874, 12, 11890, 516, 533, 13, 1071, 302, 9031, 1557, 31, 203, 203, 565, 2254, 1071, 302, 9031, 607, 6527, 273, 30616, 31, 203, 203, 565, 871, 302, 9031, 461, 3043, 12, 2867, 389, 1637, 16, 2254, 389, 2316, 548, 16, 533, 389, 529, 1769, 203, 203, 565, 871, 8630, 291, 8966, 12, 1080, 389, 12687, 1528, 1769, 203, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 40, 464, 93, 463, 9031, 87, 3905, 373, 3113, 315, 40, 5528, 7923, 288, 289, 203, 565, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 3639, 2254, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 12296, 1769, 203, 565, 289, 203, 203, 565, 445, 20501, 40, 9031, 87, 12, 2867, 389, 869, 16, 2254, 5034, 389, 455, 6527, 6275, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 14467, 273, 2078, 3088, 1283, 5621, 203, 3639, 2583, 24899, 455, 6527, 6275, 405, 374, 597, 389, 455, 6527, 6275, 1648, 302, 9031, 607, 6527, 16, 315, 1248, 7304, 20501, 2002, 364, 5927, 8863, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IStrategyV2.sol"; import "../../ValueVaultMaster.sol"; interface IOneSplit { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns( uint256 returnAmount, uint256[] memory distribution ); } interface IUniswapRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); 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); } interface IValueLiquidPool { function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint); function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint); function calcInGivenOut(uint, uint, uint, uint, uint, uint) external pure returns (uint); function calcOutGivenIn(uint, uint, uint, uint, uint, uint) external pure returns (uint); function getDenormalizedWeight(address) external view returns (uint); function getBalance(address) external view returns (uint); function swapFee() external view returns (uint); } interface IStakingRewards { function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardRate() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } interface ISushiPool { function deposit(uint256 _poolId, uint256 _amount) external; function claim(uint256 _poolId) external; function withdraw(uint256 _poolId, uint256 _amount) external; function emergencyWithdraw(uint256 _poolId) external; } interface IProfitSharer { function shareProfit() external returns (uint256); } interface IValueVaultBank { function make_profit(uint256 _poolId, uint256 _amount) external; } // Deposit UNIv2ETHUSDC to a standard StakingRewards pool (eg. UNI Pool - https://app.uniswap.org/#/uni) // Wait for Vault commands: deposit, withdraw, claim, harvest (can be called by public via Vault) contract Univ2ETHUSDCMultiPoolStrategy is IStrategyV2 { using SafeMath for uint256; address public strategist; address public governance; uint256 public constant FEE_DENOMINATOR = 10000; IERC20 public weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IOneSplit public onesplit = IOneSplit(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); ValueVaultMaster public valueVaultMaster; IERC20 public lpPair; // ETHUSDC_UNIv2 IERC20 public lpPairTokenA; // USDC IERC20 public lpPairTokenB; // For this contract it will be always be WETH mapping(address => mapping(address => address[])) public uniswapPaths; // [input -> output] => uniswap_path mapping(address => mapping(address => address)) public liquidPools; // [input -> output] => value_liquid_pool (valueliquid.io) struct PoolInfo { address vault; IERC20 targetToken; address targetPool; uint256 targetPoolId; // poolId in soda/chicken pool (no use for IStakingRewards pool eg. golff.finance) uint256 minHarvestForTakeProfit; uint8 poolType; // 0: IStakingRewards, 1: ISushiPool, 2: ISodaPool uint256 poolQuota; // set 0 to disable quota (no limit) uint256 balance; } mapping(uint256 => PoolInfo) public poolMap; // poolIndex -> poolInfo bool public aggressiveMode; // will try to stake all lpPair tokens available (be forwarded from bank or from another strategies) uint8[] public poolPreferredIds; // sorted by preference // lpPair: ETHUSDC_UNIv2 = 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc // lpPairTokenA: USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // lpPairTokenB: WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 constructor(ValueVaultMaster _valueVaultMaster, IERC20 _lpPair, IERC20 _lpPairTokenA, IERC20 _lpPairTokenB, bool _aggressiveMode) public { valueVaultMaster = _valueVaultMaster; lpPair = _lpPair; lpPairTokenA = _lpPairTokenA; lpPairTokenB = _lpPairTokenB; aggressiveMode = _aggressiveMode; governance = tx.origin; strategist = tx.origin; // Approve all lpPairTokenA.approve(address(unirouter), type(uint256).max); lpPairTokenB.approve(address(unirouter), type(uint256).max); } // [0] targetToken: uniToken = 0x1f9840a85d5af5bf1d1762f925bdaddc4201f984 // targetPool: ETHUSDCUniPool = 0x7fba4b8dc5e7616e59622806932dbea72537a56b // [1] targetToken: draculaToken = 0xb78B3320493a4EFaa1028130C5Ba26f0B6085Ef8 // targetPool: MasterVampire[32] = 0xD12d68Fd52b54908547ebC2Cd77Ec6EbbEfd3099 // targetPoolId = 32 function setPoolInfo(uint256 _poolId, address _vault, IERC20 _targetToken, address _targetPool, uint256 _targetPoolId, uint256 _minHarvestForTakeProfit, uint8 _poolType, uint256 _poolQuota) external { require(msg.sender == governance, "!governance"); poolMap[_poolId].vault = _vault; poolMap[_poolId].targetToken = _targetToken; poolMap[_poolId].targetPool = _targetPool; poolMap[_poolId].targetPoolId = _targetPoolId; poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit; poolMap[_poolId].poolType = _poolType; poolMap[_poolId].poolQuota = _poolQuota; _targetToken.approve(address(unirouter), type(uint256).max); lpPair.approve(_vault, type(uint256).max); lpPair.approve(address(_targetPool), type(uint256).max); } function approve(IERC20 _token) external override { require(msg.sender == governance, "!governance"); _token.approve(valueVaultMaster.bank(), type(uint256).max); _token.approve(address(unirouter), type(uint256).max); } function approveForSpender(IERC20 _token, address spender) external override { require(msg.sender == governance, "!governance"); _token.approve(spender, type(uint256).max); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setStrategist(address _strategist) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); strategist = _strategist; } function setPoolPreferredIds(uint8[] memory _poolPreferredIds) public { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); delete poolPreferredIds; for (uint8 i = 0; i < _poolPreferredIds.length; ++i) { poolPreferredIds.push(_poolPreferredIds[i]); } } function setMinHarvestForTakeProfit(uint256 _poolId, uint256 _minHarvestForTakeProfit) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit; } function setPoolQuota(uint256 _poolId, uint256 _poolQuota) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); poolMap[_poolId].poolQuota = _poolQuota; } // Sometime the balance could be slightly changed (due to the pool, or because we call xxxByGov methods) function setPoolBalance(uint256 _poolId, uint256 _balance) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); poolMap[_poolId].balance = _balance; } function setTotalBalance(uint256 _totalBalance) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); totalBalance = _totalBalance; } function setAggressiveMode(bool _aggressiveMode) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); aggressiveMode = _aggressiveMode; } function setWETH(IERC20 _weth) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); weth = _weth; } function setOnesplit(IOneSplit _onesplit) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); onesplit = _onesplit; } function setUnirouter(IUniswapRouter _unirouter) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); unirouter = _unirouter; lpPairTokenA.approve(address(unirouter), type(uint256).max); lpPairTokenB.approve(address(unirouter), type(uint256).max); } /** * @dev See {IStrategyV2-deposit}. */ function deposit(uint256 _poolId, uint256 _amount) public override { PoolInfo storage pool = poolMap[_poolId]; require(pool.vault == msg.sender, "sender not vault"); if (aggressiveMode) { _amount = lpPair.balanceOf(address(this)); } if (pool.poolType == 0) { IStakingRewards(pool.targetPool).stake(_amount); } else { ISushiPool(pool.targetPool).deposit(pool.targetPoolId, _amount); } pool.balance = pool.balance.add(_amount); totalBalance = totalBalance.add(_amount); } /** * @dev See {IStrategyV2-claim}. */ function claim(uint256 _poolId) external override { require(poolMap[_poolId].vault == msg.sender, "sender not vault"); _claim(_poolId); } function _claim(uint256 _poolId) internal { PoolInfo storage pool = poolMap[_poolId]; if (pool.poolType == 0) { IStakingRewards(pool.targetPool).getReward(); } else if (pool.poolType == 1) { ISushiPool(pool.targetPool).deposit(pool.targetPoolId, 0); } else { ISushiPool(pool.targetPool).claim(pool.targetPoolId); } } /** * @dev See {IStrategyV2-withdraw}. */ function withdraw(uint256 _poolId, uint256 _amount) external override { PoolInfo storage pool = poolMap[_poolId]; require(pool.vault == msg.sender, "sender not vault"); if (pool.poolType == 0) { IStakingRewards(pool.targetPool).withdraw(_amount); } else { ISushiPool(pool.targetPool).withdraw(pool.targetPoolId, _amount); } if (pool.balance < _amount) { _amount = pool.balance; } pool.balance = pool.balance - _amount; if (totalBalance >= _amount) totalBalance = totalBalance - _amount; } function depositByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); if (_poolType == 0) { IStakingRewards(pool).stake(_amount); } else { ISushiPool(pool).deposit(_targetPoolId, _amount); } } function claimByGov(address pool, uint8 _poolType, uint256 _targetPoolId) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); if (_poolType == 0) { IStakingRewards(pool).getReward(); } else if (_poolType == 1) { ISushiPool(pool).deposit(_targetPoolId, 0); } else { ISushiPool(pool).claim(_targetPoolId); } } function withdrawByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); if (_poolType == 0) { IStakingRewards(pool).withdraw(_amount); } else { ISushiPool(pool).withdraw(_targetPoolId, _amount); } } function emergencyWithdrawByGov(address pool, uint256 _targetPoolId) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); ISushiPool(pool).emergencyWithdraw(_targetPoolId); } /** * @dev See {IStrategyV2-poolQuota}. */ function poolQuota(uint256 _poolId) external override view returns (uint256) { return poolMap[_poolId].poolQuota; } function forwardToAnotherStrategy(address _dest, uint256 _amount) external override returns (uint256 sent) { require(valueVaultMaster.isVault(msg.sender), "not vault"); require(valueVaultMaster.isStrategy(_dest), "not strategy"); require(IStrategyV2(_dest).getLpToken() == address(lpPair), "!lpPair"); uint256 lpPairBal = lpPair.balanceOf(address(this)); sent = (_amount < lpPairBal) ? _amount : lpPairBal; lpPair.transfer(_dest, sent); } function setUnirouterPath(address _input, address _output, address [] memory _path) public { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); uniswapPaths[_input][_output] = _path; } function setLiquidPool(address _input, address _output, address _pool) public { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); liquidPools[_input][_output] = _pool; IERC20(_input).approve(_pool, type(uint256).max); } function _swapTokens(address _input, address _output, uint256 _amount) internal { address _pool = liquidPools[_input][_output]; if (_pool != address(0)) { // use ValueLiquid // swapExactAmountIn(tokenIn, tokenAmountIn, tokenOut, minAmountOut, maxPrice) IValueLiquidPool(_pool).swapExactAmountIn(_input, _amount, _output, 1, type(uint256).max); } else { // use Uniswap address[] memory path = uniswapPaths[_input][_output]; if (path.length == 0) { // path: _input -> _output path = new address[](2); path[0] = _input; path[1] = _output; } // swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline) unirouter.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(1800)); } } function _addLiquidity() internal { // addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) unirouter.addLiquidity(address(lpPairTokenA), address(lpPairTokenB), lpPairTokenA.balanceOf(address(this)), lpPairTokenB.balanceOf(address(this)), 1, 1, address(this), now.add(1800)); } /** * @dev See {IStrategyV2-harvest}. */ function harvest(uint256 _bankPoolId, uint256 _poolId) external override { address bank = valueVaultMaster.bank(); address _vault = msg.sender; require(valueVaultMaster.isVault(_vault), "!vault"); // additional protection so we don't burn the funds PoolInfo storage pool = poolMap[_poolId]; _claim(_poolId); IERC20 targetToken = pool.targetToken; uint256 targetTokenBal = targetToken.balanceOf(address(this)); if (targetTokenBal < pool.minHarvestForTakeProfit) return; _swapTokens(address(targetToken), address(weth), targetTokenBal); uint256 wethBal = weth.balanceOf(address(this)); if (wethBal > 0) { uint256 _reserved = 0; uint256 _gasFee = 0; uint256 _govVaultProfitShareFee = 0; if (valueVaultMaster.gasFee() > 0) { _gasFee = wethBal.mul(valueVaultMaster.gasFee()).div(FEE_DENOMINATOR); _reserved = _reserved.add(_gasFee); } if (valueVaultMaster.govVaultProfitShareFee() > 0) { _govVaultProfitShareFee = wethBal.mul(valueVaultMaster.govVaultProfitShareFee()).div(FEE_DENOMINATOR); _reserved = _reserved.add(_govVaultProfitShareFee); } uint256 wethToBuyTokenA = wethBal.sub(_reserved).div(2); // we have TokenB (WETH) already, so use 1/2 bal to buy TokenA (USDC) _swapTokens(address(weth), address(lpPairTokenA), wethToBuyTokenA); _addLiquidity(); wethBal = weth.balanceOf(address(this)); { address profitSharer = valueVaultMaster.profitSharer(); address performanceReward = valueVaultMaster.performanceReward(); if (_gasFee > 0 && performanceReward != address(0)) { if (_gasFee.add(_govVaultProfitShareFee) < wethBal) { _gasFee = wethBal.sub(_govVaultProfitShareFee); } weth.transfer(performanceReward, _gasFee); wethBal = weth.balanceOf(address(this)); } if (_govVaultProfitShareFee > 0 && profitSharer != address(0)) { address govToken = valueVaultMaster.govToken(); _swapTokens(address(weth), govToken, wethBal); IERC20(govToken).transfer(profitSharer, IERC20(govToken).balanceOf(address(this))); IProfitSharer(profitSharer).shareProfit(); } } uint256 balanceLeft = lpPair.balanceOf(address(this)); if (balanceLeft > 0) { if (_bankPoolId == type(uint256).max) { // this called by governance of vault, send directly to bank (dont make profit) lpPair.transfer(bank, balanceLeft); } else { if (lpPair.allowance(address(this), bank) < balanceLeft) { lpPair.approve(bank, 0); lpPair.approve(bank, balanceLeft); } IValueVaultBank(bank).make_profit(_bankPoolId, balanceLeft); } } } } /** * @dev See {IStrategyV2-getLpToken}. */ function getLpToken() external view override returns(address) { return address(lpPair); } /** * @dev See {IStrategyV2-getTargetToken}. */ function getTargetToken(uint256 _poolId) external override view returns(address) { return address(poolMap[_poolId].targetToken); } function balanceOf(uint256 _poolId) public override view returns (uint256) { return poolMap[_poolId].balance; } // Only support IStakingRewards pool function pendingReward(uint256 _poolId) public override view returns (uint256) { if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types return IStakingRewards(poolMap[_poolId].targetPool).earned(address(this)); } // Helper function, Should never use it on-chain. // Return 1e18x of APY. _lpPairUsdcPrice = current lpPair price (1-wei in USDC-wei) multiple by 1e18 function expectedAPY(uint256, uint256) public override view returns (uint256) { return 0; // not implemented } /** * @dev if there is any token stuck we will need governance support to rescue the fund */ function governanceRescueToken(IERC20 _token) external override returns (uint256 balance) { address bank = valueVaultMaster.bank(); require(bank == msg.sender, "sender not bank"); balance = _token.balanceOf(address(this)); _token.transfer(bank, balance); } event ExecuteTransaction(address indexed target, uint value, string signature, bytes data); function executeTransaction(address target, uint value, string memory signature, bytes memory data) public returns (bytes memory) { require(msg.sender == governance, "!governance"); 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, "Univ2ETHUSDCMultiPoolStrategy::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } }
Sometime the balance could be slightly changed (due to the pool, or because we call xxxByGov methods)
function setPoolBalance(uint256 _poolId, uint256 _balance) external { require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist"); poolMap[_poolId].balance = _balance; }
5,504,759
[ 1, 55, 362, 2374, 326, 11013, 3377, 506, 21980, 3550, 261, 24334, 358, 326, 2845, 16, 578, 2724, 732, 745, 23354, 858, 43, 1527, 2590, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 2864, 13937, 12, 11890, 5034, 389, 6011, 548, 16, 2254, 5034, 389, 12296, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 314, 1643, 82, 1359, 747, 1234, 18, 15330, 422, 609, 1287, 376, 16, 17528, 75, 1643, 82, 1359, 597, 401, 701, 1287, 376, 8863, 203, 3639, 2845, 863, 63, 67, 6011, 548, 8009, 12296, 273, 389, 12296, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; 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 getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } pragma solidity ^0.4.24; /** * @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 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); } } } pragma solidity ^0.4.24; 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); } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; // "./PlayerBookInterface.sol"; // "./SafeMath.sol"; // "./NameFilter.sol"; // 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { /* event debug ( uint16 code, uint256 value, bytes32 msg ); */ // 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 mktAmount, // uint256 comAmount, 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 mktAmount, 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 mktAmount, 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 mktAmount, 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, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularLong is F3Devents {} contract FoMo3DWorld is modularLong, Ownable { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x789C537cE585595596D3905f401235f5A85B11d7); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D World"; string constant public symbol = "F3DW"; // uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO uint256 constant private rndGap_ = 0; // 120 seconds; // length of ICO phase. 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 uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop 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 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.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 => F3Ddatasets.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 //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30, 6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43, 0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56, 10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43, 8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15, 10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25, 0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20, 20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30, 10); //48% to winner, 10% to next round, 2% to com } /** * @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; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @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"); _; } /** * @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 F3Ddatasets.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 buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.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 == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } 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 F3Ddatasets.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 not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // 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 reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.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 == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.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]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // 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 F3Ddatasets.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 F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _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 F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @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 registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @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) ); } /** * @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 whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ 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 airDropTracker_ + (airDropPot_ * 1000) //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) { // 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 ); } /** * @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, F3Ddatasets.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 F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _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, F3Ddatasets.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 F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _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, F3Ddatasets.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; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // 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_); // 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 */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) 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; } /** * @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 */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_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; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ 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, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.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_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.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, // p3d 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 _mkt = (_pot.mul(potSplit_[_winTID].marketing)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen).sub(_mkt); // 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); // community rewards _com = _com.add(_mkt); if (!owner.send(_com)) { _com = 0; _res = _res.add(_com); } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // 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_.mktAmount = _mkt; // _eventData_.comAmount = _com; _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); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked((block.timestamp).add(block.difficulty).add((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add(block.gaslimit).add((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add(block.number)))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 10; // 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 != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100; _com = _com.add(_mkt); owner.transfer(_com); _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.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, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); uint256 cut = (fees_[_team].marketing).add(13); _eth = _eth.sub(_eth.mul(cut) / 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, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, // _eventData_.comAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** 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() public onlyOwner { // make sure that its been linked. // require(address(otherF3D_) != 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; round_[1].end = now + rndInit_; } } library F3Ddatasets { //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 mktAmount; // amount distributed for marketing // uint256 comAmount; 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 } 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 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 marketing; // % of buy in thats paid for marketing } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 marketing; // % of pot thats paid to for marketing } } library F3DKeysCalcLong { 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()); } }
* @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) ); }
1,205,455
[ 1, 12780, 815, 640, 23455, 425, 1303, 899, 261, 3732, 17264, 16, 1552, 486, 1089, 3066, 13, 327, 425, 1303, 899, 316, 732, 77, 740, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7029, 984, 5796, 329, 41, 1303, 899, 12, 11890, 5034, 389, 84, 734, 16, 2254, 5034, 389, 86, 734, 2722, 13, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 12, 225, 261, 12443, 2260, 67, 63, 67, 86, 734, 2722, 8009, 4455, 2934, 16411, 12, 1283, 86, 54, 82, 2377, 67, 63, 67, 84, 734, 6362, 67, 86, 734, 2722, 8009, 2452, 3719, 342, 261, 21, 12648, 2787, 9449, 13, 2934, 1717, 12, 1283, 86, 54, 82, 2377, 67, 63, 67, 84, 734, 6362, 67, 86, 734, 2722, 8009, 4455, 13, 225, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; contract ArrayExample { // dynamic length array bytes32[] public names; // fixed length array bytes[4] public fNames; function arrTest() public returns(uint) { // assign inline string[4] memory _inlineArray = ["sam","mike","peter","mckay"]; // multi dimensional array uint[3][] memory multiArray; fNames[0] = "Matt"; names.push("JON"); names.push("PURDY"); // initializing multi dimensional array multiArray = new uint[3][](2); // number of rows = 2 multiArray[0][1] = 20; return multiArray[0][1]; } function getFNamesLength() public view returns(uint256){ return fNames.length; } function getNamesLength() public view returns(uint256){ return names.length; } }
dynamic length array fixed length array
contract ArrayExample { bytes32[] public names; bytes[4] public fNames; function arrTest() public returns(uint) { string[4] memory _inlineArray = ["sam","mike","peter","mckay"]; uint[3][] memory multiArray; fNames[0] = "Matt"; names.push("JON"); names.push("PURDY"); multiArray[0][1] = 20; return multiArray[0][1]; } function getFNamesLength() public view returns(uint256){ return fNames.length; } function getNamesLength() public view returns(uint256){ return names.length; } }
14,070,323
[ 1, 14507, 769, 526, 5499, 769, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1510, 10908, 288, 203, 203, 565, 1731, 1578, 8526, 1071, 1257, 31, 203, 377, 203, 565, 1731, 63, 24, 65, 1071, 284, 1557, 31, 203, 377, 203, 203, 565, 445, 2454, 4709, 1435, 1071, 1135, 12, 11890, 13, 288, 203, 3639, 533, 63, 24, 65, 3778, 389, 10047, 1076, 273, 8247, 20353, 15937, 81, 2547, 15937, 84, 847, 15937, 81, 363, 528, 11929, 31, 203, 540, 203, 3639, 2254, 63, 23, 6362, 65, 3778, 3309, 1076, 31, 203, 540, 203, 3639, 284, 1557, 63, 20, 65, 273, 315, 49, 4558, 14432, 203, 540, 203, 3639, 1257, 18, 6206, 2932, 46, 673, 8863, 203, 3639, 1257, 18, 6206, 2932, 52, 1099, 40, 61, 8863, 203, 540, 203, 540, 203, 3639, 3309, 1076, 63, 20, 6362, 21, 65, 273, 4200, 31, 203, 540, 203, 3639, 327, 3309, 1076, 63, 20, 6362, 21, 15533, 203, 565, 289, 203, 377, 203, 565, 445, 2812, 1557, 1782, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 284, 1557, 18, 2469, 31, 203, 565, 289, 203, 377, 203, 565, 445, 336, 1557, 1782, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 1257, 18, 2469, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x3Fd3C966381b668EFc5A5Efbc55BFAEd652Bb1AE/sources/project:/contracts/shard_warriors.sol
start time of construction
uint256 startTs;
3,234,504
[ 1, 1937, 813, 434, 16171, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 787, 17218, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ 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 - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Finalizable * @dev Base contract which allows children to implement a finalization mechanism. * inspired by FinalizableCrowdsale from zeppelin */ contract Finalizable is Ownable { event Finalized(); bool public isFinalized = false; /** * @dev Modifier to make a function callable only when the contract is not finalized. */ modifier whenNotFinalized() { require(!isFinalized); _; } /** * @dev called by the owner to finalize */ function finalize() onlyOwner whenNotFinalized public { 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 Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @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 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)); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title EtherSportCrowdsale */ contract EtherSportCrowdsale is usingOraclize, Pausable, Finalizable, Destructible, HasNoTokens, HasNoContracts { using SafeMath for uint256; using SafeERC20 for ERC20; // EtherSport token ERC20 public token; // wallet with token allowance address public tokenFrom; // start timestamp uint256 public startTime; // end timestamp uint256 public endTime; // tokens sold uint256 public sold; // wei raised uint256 public raised; // address where funds are collected address public wallet; // funders mapping (address => bool) public funders; // oraclize funding order struct Order { address beneficiary; uint256 funds; uint256 bonus; uint256 rate; uint256 specialPrice; address referer; } // oraclize funding orders mapping (bytes32 => Order) public orders; // offer with special price struct Offer { uint256 condition; uint256 specialPrice; } // special offers mapping (address => Offer) public offers; // oraclize gas limit uint256 public oraclizeGasLimit = 200000; // bonused purchases counter uint256 public bonusedPurchases; // minimum funding amount uint256 public constant MIN_FUNDING_AMOUNT = 0.04 ether; // oraclize commission uint256 public constant ORACLIZE_COMMISSION = 0.0025 ether; // bonused purchases limit (+ 2 for test) uint256 public constant BONUSED_PURCHASES_LIMIT = 202; // minimum funding amount for 30% volume bonus uint256 public constant VOLUME_BONUS_CONDITION = 7 ether; // 30% volume bonus uint256 public constant VOLUME_BONUS = 30; // 15% first purchases bonus uint256 public constant PURCHASES_BONUS = 15; // token price (usd), using PRICE_EXPONENT uint256 public constant TOKEN_PRICE = 100; // exponent for the token price uint256 public constant PRICE_EXPONENT = 2; // exponent for the eth/usd rate uint256 public constant RATE_EXPONENT = 4; // token decimals uint256 public constant TOKEN_DECIMALS = 18; // hard cap of tokens proposed to purchase uint256 public constant TOKENS_HARD_CAP = 55000000 * (10 ** TOKEN_DECIMALS); // eth/usd rate url string public ethRateURL = "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd"; /** * event for token purchase logging * @param beneficiary Who got the tokens * @param orderId Oraclize orderId * @param value Weis paid for purchase * @param amount Amount of tokens purchased */ event TokenPurchaseEvent(address indexed beneficiary, bytes32 indexed orderId, uint256 value, uint256 amount); /** * event for token accrual to referer logging * @param beneficiary Who has made the token purchase * @param referer Beneficiary's referer * @param orderId Oraclize orderId * @param bonusAmount Amount of bonus tokens transfered to referer */ event RefererBonusEvent(address indexed beneficiary, address indexed referer, bytes32 indexed orderId, uint256 bonusAmount); /** * event for funding order logging * @param beneficiary Who has done the order * @param orderId Oraclize orderId */ event OrderEvent(address indexed beneficiary, bytes32 indexed orderId); /** * event for funding logging * @param funder Who has done the payment * @param referer Beneficiary's referer * @param orderId Oraclize orderId * @param beneficiary Who will get the tokens * @param funds Funds sent by funder */ event FundingEvent(address indexed funder, address indexed referer, bytes32 indexed orderId, address beneficiary, uint256 funds); /** * CONSTRUCTOR * * @dev Initialize the EtherSportCrowdsale * @param _startTime Start time timestamp * @param _endTime End time timestamp * @param _token EtherSport ERC20 token * @param _from Wallet address with token allowance * @param _wallet Wallet address to transfer direct funding to */ function EtherSportCrowdsale( uint256 _startTime, uint256 _endTime, address _token, address _from, address _wallet ) public { require(_startTime < _endTime); require(_token != address(0)); require(_from != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; token = ERC20(_token); tokenFrom = _from; wallet = _wallet; } // fallback function can be used to buy tokens function () public payable { if (msg.sender != owner) buyTokensFor(msg.sender, address(0)); } /** * @dev Makes order for tokens purchase. * @param _referer Funder's referer (optional) */ function buyTokens(address _referer) public payable { buyTokensFor(msg.sender, _referer); } /** * @dev Makes order for tokens purchase. * @param _beneficiary Who will get the tokens * @param _referer Beneficiary's referer (optional) */ function buyTokensFor( address _beneficiary, address _referer ) public payable { require(_beneficiary != address(0)); require(_beneficiary != _referer); require(msg.value >= MIN_FUNDING_AMOUNT); require(liveEtherSportCampaign()); require(oraclize_getPrice("URL") <= this.balance); uint256 _funds = msg.value; address _funder = msg.sender; bytes32 _orderId = oraclize_query("URL", ethRateURL, oraclizeGasLimit); OrderEvent(_beneficiary, _orderId); orders[_orderId].beneficiary = _beneficiary; orders[_orderId].funds = _funds; orders[_orderId].referer = _referer; uint256 _offerCondition = offers[_funder].condition; uint256 _bonus; // in case of special offer if (_offerCondition > 0 && _offerCondition <= _funds) { uint256 _offerPrice = offers[_funder].specialPrice; offers[_funder].condition = 0; offers[_funder].specialPrice = 0; orders[_orderId].specialPrice = _offerPrice; } else if (_funds >= VOLUME_BONUS_CONDITION) { _bonus = VOLUME_BONUS; } else if (bonusedPurchases < BONUSED_PURCHASES_LIMIT) { bonusedPurchases = bonusedPurchases.add(1); _bonus = PURCHASES_BONUS; } orders[_orderId].bonus = _bonus; uint256 _transferFunds = _funds.sub(ORACLIZE_COMMISSION); wallet.transfer(_transferFunds); raised = raised.add(_funds); funders[_funder] = true; FundingEvent(_funder, _referer, _orderId, _beneficiary, _funds); // solium-disable-line arg-overflow } /** * @dev Get current rate from oraclize and transfer tokens. * @param _orderId Oraclize order id * @param _result Current rate */ function __callback(bytes32 _orderId, string _result) public { // solium-disable-line mixedcase require(msg.sender == oraclize_cbAddress()); uint256 _rate = parseInt(_result, RATE_EXPONENT); address _beneficiary = orders[_orderId].beneficiary; uint256 _funds = orders[_orderId].funds; uint256 _bonus = orders[_orderId].bonus; address _referer = orders[_orderId].referer; uint256 _specialPrice = orders[_orderId].specialPrice; orders[_orderId].rate = _rate; uint256 _tokens = _funds.mul(_rate); if (_specialPrice > 0) { _tokens = _tokens.div(_specialPrice); } else { _tokens = _tokens.div(TOKEN_PRICE); } _tokens = _tokens.mul(10 ** PRICE_EXPONENT).div(10 ** RATE_EXPONENT); uint256 _bonusTokens = _tokens.mul(_bonus).div(100); _tokens = _tokens.add(_bonusTokens); //change of funds will be returned to funder if (sold.add(_tokens) > TOKENS_HARD_CAP) { _tokens = TOKENS_HARD_CAP.sub(sold); } token.safeTransferFrom(tokenFrom, _beneficiary, _tokens); sold = sold.add(_tokens); if (funders[_referer]) { uint256 _refererBonus = _tokens.mul(5).div(100); if (sold.add(_refererBonus) > TOKENS_HARD_CAP) { _refererBonus = TOKENS_HARD_CAP.sub(sold); } if (_refererBonus > 0) { token.safeTransferFrom(tokenFrom, _referer, _refererBonus); sold = sold.add(_refererBonus); RefererBonusEvent(_beneficiary, _referer, _orderId, _refererBonus); } } TokenPurchaseEvent(_beneficiary, _orderId, _funds, _tokens); } /** * @dev Set offer with special price. * @param _beneficiary Who got the offer * @param _condition Minimum wei amount for offer purchase * @param _specialPrice Price value for the offer (usd), using PRICE_EXPONENT */ function setOffer(address _beneficiary, uint256 _condition, uint256 _specialPrice) onlyOwner public { require(_beneficiary != address(0)); require(_condition >= MIN_FUNDING_AMOUNT); require(_specialPrice > 0); offers[_beneficiary].condition = _condition; offers[_beneficiary].specialPrice = _specialPrice; } /** * @dev Withdraw ether from contract * @param _amount Amount to withdraw */ function withdrawEther(uint256 _amount) onlyOwner public { require(this.balance >= _amount); owner.transfer(_amount); } /** * @dev Set oraclize gas limit * @param _gasLimit New oraclize gas limit */ function setOraclizeGasLimit(uint256 _gasLimit) onlyOwner public { require(_gasLimit > 0); oraclizeGasLimit = _gasLimit; } /** * @dev Set oraclize gas price * @param _gasPrice New oraclize gas price */ function setOraclizeGasPrice(uint256 _gasPrice) onlyOwner public { require(_gasPrice > 0); oraclize_setCustomGasPrice(_gasPrice); } /** * @return true if the EtherSport campaign is alive */ function liveEtherSportCampaign() internal view returns (bool) { return now >= startTime && now <= endTime && !paused && !isFinalized && sold < TOKENS_HARD_CAP; // solium-disable-line security/no-block-members } }
minimum funding amount for 30% volume bonus
uint256 public constant VOLUME_BONUS_CONDITION = 7 ether;
5,910,217
[ 1, 15903, 22058, 3844, 364, 5196, 9, 3940, 324, 22889, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 776, 1741, 24027, 67, 38, 673, 3378, 67, 22017, 273, 2371, 225, 2437, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/CrypTotems.sol // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/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. */ //Todo: Method out // abstract contract Context { // function _msgSender() internal view virtual returns (address) { // return msg.sender; // } // function _msgData() internal view virtual returns (bytes calldata) { // return msg.data; // } // } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); //Counter(); } /** * @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"); _; } // function Counter() public { // for(uint i=1; i <=4500;i++){ // arr2.push(i); // } // } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; //Todo: BUradaki CrypTicket'in Refactor edilmesi gerekiyor!!! contract CrypTicket is ERC20{ constructor() ERC20("Token06","TKN6"){ _mint(msg.sender,2000*10**18); } function mint(address to,uint256 value) internal{ _mint(to,value); } function specialBurn(address from,uint256 amount) public { _burn(from,amount*10**18); } } contract CrypTotems is ERC721Enumerable, Ownable,ReentrancyGuard { using Strings for uint256; string baseURI; string public baseExtension = ".json"; address payable _contractOwner; uint256 private maxPublicSaleMint = 2; uint256 public maxSupply = 4444; uint256 public cost = 0.04 ether; bool public paused = true; bool public revealed; string public notRevealedUri; bool public preSale ; constructor( string memory _initNotRevealedUri) ERC721("CrypTotems", "TOTEMS") { setNotRevealedURI(_initNotRevealedUri); token = CrypTicket(address(0xC2Cfbd487fE9c42aa5A92C222261B1AD8fdFc6F1)); _contractOwner = payable(msg.sender); } function setPresale(bool _data) external onlyOwner { preSale = _data; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function publicMint(uint256 mintAmount) external payable nonReentrant { uint256 supply = totalSupply(); require(supply + mintAmount <= maxSupply,"Error : Max supply exceeded."); require(!paused,"Contract minting is paused!"); require(!preSale,"Public minting is not active."); require(mintAmount <= maxPublicSaleMint,"You can mint maximum 2 NFTs at once."); require(mintAmount > 0 ,"You must mint at least 1 NFT"); require(msg.value == cost * mintAmount,"Enter the exact total price!"); //_contractOwner.transfer(msg.value); for(uint256 i =0;i<mintAmount;i++){ _safeMint(msg.sender, supply + 1); supply+=1; } } // public function mint(uint256 mintAmount) external { uint256 supply = totalSupply(); require(!paused,"Contract minting is paused."); require(supply + mintAmount <= maxSupply,"Error : Max supply exceeded!"); require(preSale,"Error: Presale is closed!"); require(token.balanceOf(msg.sender)>=mintAmount*10**18,"You can not free mint! You do not own enough CRTK tokens"); decrease(mintAmount); for(uint256 i =0;i<mintAmount;i++){ _safeMint(msg.sender, supply + 1); supply+=1; } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function setNotRevealedURI(string memory _notRevealedURI) internal onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; revealed = true; } function pause(bool _state) external onlyOwner { paused = _state; } function balanceOfTickets() public view returns(uint){ return token.balanceOf(msg.sender); } CrypTicket private token; function decrease(uint256 amount) internal { token.specialBurn(msg.sender,amount); } function withdrawBalance() external{ require(msg.sender == _contractOwner,"You are not the owner of this contract"); _contractOwner.transfer(address(this).balance); } function showContractBalance() external onlyOwner view returns (uint256) { return address(this).balance; } }
* @dev Returns the total amount of tokens stored by the contract./* @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./* @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./ File: @openzeppelin/contracts/utils/introspection/ERC165.sol* @dev Implementation of the {IERC165} interface. Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check for the additional interface id that will be supported. For example: ```solidity function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); } ``` Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation./
abstract contract ERC165 is IERC165 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. pragma solidity ^0.8.0; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
1,259,662
[ 1, 1356, 326, 2078, 3844, 434, 2430, 4041, 635, 326, 6835, 18, 19, 225, 2860, 279, 1147, 1599, 16199, 635, 1375, 8443, 68, 622, 279, 864, 1375, 1615, 68, 434, 2097, 1147, 666, 18, 2672, 7563, 598, 288, 12296, 951, 97, 358, 4241, 777, 434, 12176, 8443, 10335, 11, 87, 2430, 18, 19, 225, 2860, 279, 1147, 1599, 622, 279, 864, 1375, 1615, 68, 434, 777, 326, 2430, 4041, 635, 326, 6835, 18, 2672, 7563, 598, 288, 4963, 3088, 1283, 97, 358, 4241, 777, 2430, 18, 19, 1387, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 474, 26362, 19, 654, 39, 28275, 18, 18281, 225, 25379, 434, 326, 288, 45, 654, 39, 28275, 97, 1560, 18, 30131, 716, 2545, 358, 2348, 4232, 39, 28275, 1410, 6811, 628, 333, 6835, 471, 3849, 288, 28064, 1358, 97, 358, 866, 364, 326, 3312, 1560, 612, 716, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 4232, 39, 28275, 353, 467, 654, 39, 28275, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 203, 565, 401, 1669, 830, 69, 4417, 5, 203, 565, 8646, 20092, 1240, 2118, 1399, 358, 752, 268, 22378, 87, 16, 203, 565, 471, 1703, 2522, 364, 326, 13115, 358, 6489, 497, 16951, 203, 565, 3661, 358, 752, 13706, 20092, 603, 326, 16766, 18, 203, 565, 9582, 10725, 333, 981, 603, 3433, 4953, 1865, 1450, 1281, 434, 203, 565, 326, 3751, 981, 364, 12449, 18, 203, 565, 2474, 48, 7146, 903, 486, 506, 328, 2214, 316, 1281, 4031, 309, 364, 326, 999, 7010, 565, 434, 326, 981, 18, 12466, 3832, 7864, 350, 16, 326, 981, 711, 2118, 18432, 7010, 565, 358, 326, 3796, 434, 326, 21701, 11, 20272, 358, 1440, 487, 12613, 18, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 2 ]
./partial_match/1/0xEb0C29Cb76E673dAA6fc24822909968E27BE41a2/sources/ETHStakingContract0xBoost41.sol
0.042857142857143%
currentInterestRate = 42857142857143;
15,467,933
[ 1, 20, 18, 3028, 6030, 10321, 3461, 6030, 10321, 28643, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 783, 29281, 4727, 273, 1059, 6030, 10321, 3461, 6030, 10321, 28643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x33E82253e8b84e7Ea95B7eDC710Be3bF576A975E/sources/AccessControlledAggregator.sol
* @notice get data about the latest round. Consumers are encouraged to check that they're receiving fresh data by inspecting the updatedAt and answeredInRound return values. Consumers are encouraged to use this more fully featured method over the "legacy" getAnswer/ latestAnswer/getTimestamp/latestTimestamp functions. Consumers are encouraged to check that they're receiving fresh data by inspecting the updatedAt and answeredInRound return values. @return roundId is the round ID for which data was retrieved @return answer is the answer for the given round @return startedAt is the timestamp when the round was started. This is 0 if the round hasn't been started yet. @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) @return answeredInRound is the round ID of the round in which the answer was computed. answeredInRound may be smaller than roundId when the round timed out. answerInRound is equal to roundId when the round didn't time out and was completed regularly. @dev Note that for in-progress rounds (i.e. rounds that haven't yet received maxSubmissions) answer and updatedAt may change between queries./
function latestRoundData() public view override checkAccess() returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound ) { return super.latestRoundData(); }
4,154,589
[ 1, 588, 501, 2973, 326, 4891, 3643, 18, 22210, 414, 854, 2446, 477, 11349, 358, 866, 716, 2898, 4565, 15847, 12186, 501, 635, 5334, 310, 326, 31944, 471, 5803, 329, 382, 11066, 327, 924, 18, 22210, 414, 854, 2446, 477, 11349, 358, 999, 333, 1898, 7418, 2572, 72, 707, 1879, 326, 315, 17386, 6, 336, 13203, 19, 4891, 13203, 19, 588, 4921, 19, 13550, 4921, 4186, 18, 22210, 414, 854, 2446, 477, 11349, 358, 866, 716, 2898, 4565, 15847, 12186, 501, 635, 5334, 310, 326, 31944, 471, 5803, 329, 382, 11066, 327, 924, 18, 327, 3643, 548, 353, 326, 3643, 1599, 364, 1492, 501, 1703, 10295, 327, 5803, 353, 326, 5803, 364, 326, 864, 3643, 327, 5746, 861, 353, 326, 2858, 1347, 326, 3643, 1703, 5746, 18, 1220, 353, 374, 309, 326, 3643, 13342, 1404, 2118, 5746, 4671, 18, 327, 31944, 353, 326, 2858, 1347, 326, 3643, 1142, 1703, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 4891, 11066, 751, 1435, 203, 565, 1071, 203, 565, 1476, 203, 565, 3849, 203, 565, 28484, 1435, 203, 565, 1135, 261, 203, 1377, 2254, 5034, 3643, 548, 16, 203, 1377, 509, 5034, 5803, 16, 203, 1377, 2254, 5034, 5746, 861, 16, 203, 1377, 2254, 5034, 31944, 16, 203, 1377, 2254, 5034, 5803, 329, 382, 11066, 203, 565, 262, 203, 225, 288, 203, 565, 327, 2240, 18, 13550, 11066, 751, 5621, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /** * 10X contract * Copyright 2017, TheWolf * * An infinite crowdfunding lottery token * Using a permanent delivery of tokens as a reward to the lost bids. * With a bullet proof random generation algorithm and a lot of inovative features * With a state machine switching automatically from game mode to crowdfunding mode * * Note: the code is free to use for learning purpose or inspiration, * but identical code used in a commercial product or similar games * is prohibited: be creative! */ /* Math operations with safety checks */ contract safeMath { function safeMul(uint a, uint b) internal constant returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal constant returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal constant returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal constant returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } /* owned class */ contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) revert(); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } /* pass class */ contract pass is owned{ bytes32 internalPass; function storePassword(string password) internal onlyOwner{ internalPass = sha256(password); } modifier protected(string password) { if ( internalPass!= sha256(password)) revert(); _; } function changePassword(string oldPassword, string newPassword) onlyOwner returns(bool) { if (internalPass== sha256(oldPassword)) { internalPass = sha256(newPassword); return true; } return false; } } /* blacklist */ contract blacklist is owned, pass{ // change the blacklist status of an address function setBlacklist(address _adr, bool _value, string _password ) onlyOwner external protected(_password){ require(_adr>0); require(_adr!=owner); blacklist[_adr]=_value; } // change the blacklist status of an address internal version function setBlacklistInternal(address _adr, bool _value) onlyOwner internal { require(_adr>0); require(_adr!=owner); blacklist[_adr]=_value; } // get the current status of an address, blacklisted or not? function checkBlacklist(address _adr ) constant external onlyOwner returns(bool){ return blacklist[_adr]; } mapping (address => bool) blacklist; } /* ERC20 Contract definitions */ contract ERC20 { uint256 public totalETHSupply; // added to the ERC20 for convenience, does not change the protocol function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /* 10X Token Creation and Functionality */ contract TokenBase is ERC20, blacklist, safeMath{ uint public totalAddress; function TokenBase() { // constructor, first address is owner addr[0]=msg.sender; totalAddress=1; } // Send to the address _to, value money function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } // Transfer money from one adress _from to another adress _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value ) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } // get the current owner balance function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // transaction approval : check if everything is ok before transfering function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function getAddress(uint _index) constant returns(address adr) { require(_index>=0); require(_index<totalAddress); return(addr[_index]); } function getTotalAddresses() constant returns(uint) { return(totalAddress); } // allowance function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } mapping (uint => address) addr; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract THEWOLF10XToken is TokenBase{ string public constant name = "10X Game"; // contract name string public constant symbol = "10X"; // symbol name uint256 public constant decimals = 18; // standard size string public constant version="1.46"; bool public isfundingGoalReached; bool public isGameOn; bool public isPaused; bool public isDebug; bool public isAutopilot; bool public isLimited; bool public isPrintTokenInfinite; bool public isMaxCap10XReached; uint public limitMaxCrowdsale; uint public limitMaxGame; uint public fundingGoal; uint public totalTokenSupply; uint public timeStarted; uint public deadline; uint public maxPlayValue; uint public betNumber; uint public restartGamePeriod; uint public playValue; uint public tokenDeliveryCrowdsalePrice; uint public tokenDeliveryPlayPrice; uint private seed; uint private exresult; uint256 public tokenCreationCap; struct transactions { // Struct address playeraddress; uint time; uint betinwai; uint numberdrawn; uint playerbet; bool winornot; } event Create10X(address indexed _to, uint256 _value); event LogMsg(address indexed _from, string Msg); event FundingReached(address beneficiary, uint fundingRaised); event GameOnOff(bool state); event GoalReached(address owner, uint256 goal); event SwitchingToFundingMode(uint totalETHSupply, uint fundingCurrent); event InPauseMode(uint date,bool status); mapping (uint => transactions) public bettable; // contructor debugging : 5000,2000,10,"10000000","0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db", "0x14723a09acff6d2a60dcdf7aa4aff308fddc160c", "zzzzz",10,4 // Testnet: https://gist.github.com/TheWolf-Patarawan/ae9e8ecf7300fc3abcc8d0863d6f4245 // need this gas to create the contract: 6000000 function THEWOLF10XToken( uint _fundingGoalInEthers, uint _tokenPriceForEachEtherCrowdsale, uint _tokenPriceGame, uint _tokenInitialSupplyIn10X, address _addressOwnerTrading1, address _addressOwnerTrading2, string _password, uint _durationInDays ) { require(_tokenPriceForEachEtherCrowdsale<=10000 && _tokenPriceForEachEtherCrowdsale>0); require(_tokenInitialSupplyIn10X * 1 ether>=10000000 * 1 ether); // cannot run with less than 10x4 Million 10X total, safety test in case slippy finger misses a 0 require(msg.sender>0); // using 0 as address is not allowed isGameOn=false; // open the crowdsale per default isfundingGoalReached = false; isPaused=false; isMaxCap10XReached=false; fundingGoal = _fundingGoalInEthers * 1 ether; // calculate the funding goal in eth // WARNING THIS IS FOR DEBUGGING, THIS VALUE MUST BE 0 IN THE LIVE CONTRACT //------------------------------------------------------------------------ totalETHSupply = 100 ether; // initial ETH funding for testing //------------------------------------------------------------------------ owner = msg.sender; // save the address of the contract initiator for later use balances[owner] =_tokenInitialSupplyIn10X * 2 ether; // tokens for the contract (used to deliver tokens to the player) 2x 10 Millions. balances[_addressOwnerTrading1] = _tokenInitialSupplyIn10X * 1 ether; // 10 M tokens for escrow 1 (buy) balances[_addressOwnerTrading2] = _tokenInitialSupplyIn10X * 1 ether; // 10 M tokens for escrow 2 (sale) timeStarted=now; // initialize the timer for the crowdsale, starting now tokenDeliveryCrowdsalePrice = _tokenPriceForEachEtherCrowdsale; // how many 10X tokens are delivered during the crowdsale tokenDeliveryPlayPrice=_tokenPriceGame; // price of a token when the game starts totalTokenSupply=_tokenInitialSupplyIn10X * 1 ether; // initial supply of tokens tokenCreationCap=_tokenInitialSupplyIn10X * 2 ether; // 20 Millions 10X tokens in the game /10 for ICO / 10 for the game. storePassword(_password); // hash the password and store the admin password betNumber=0; // starting, no bets yet seed=now/4000000000000*3141592653589; // random seed exresult=1; // random result storage deadline==now + (_durationInDays * 1 days); // date of the end of the current crowdsale starting now restartGamePeriod=1; // automatic crowdfunding reset for this time period in days by default maxPlayValue=safeDiv(totalETHSupply,100); // at starting we can play no more than 2 Eth isLimited=false; // not limit for buying tokens isPrintTokenInfinite= false; // we deliver only the tokens we have in stock of true we mint on demand. limitMaxCrowdsale=0; // the upper limit in case of we want to limit the value per transaction in crowdsale mode isAutopilot=false; // do not let the contract change its status alone. Set it to true if the owner cannot manage the contract anymore. limitMaxGame= 2 ether; // cannot play more than 2 ether at the game, if 0 unlimited } // determines the token rate function tokenRate() constant returns(uint) { if (now>timeStarted && now<deadline && !isGameOn) return tokenDeliveryCrowdsalePrice; // when we are in crowdsale mode return tokenDeliveryPlayPrice; // when the game is on } // Generates and delivers the tokens and the ethers function makeTokens() payable returns(bool) { uint256 tokens; uint256 checkTokenSupply; maxPlayValue=safeDiv(totalETHSupply,100); playValue=msg.value; // check if we exceed the maximum bet possible according to the fund we have. if (isGameOn==true) { if (playValue>maxPlayValue) { LogMsg(msg.sender, "This bet exceed the maximum play value, we cannot accept it, try with a lower amount."); revert(); } } // case of we limit the number of transaction in the Crowdsale mode if (isLimited==true && isGameOn==false) { if (balances[msg.sender]>limitMaxCrowdsale) { LogMsg(msg.sender, "limiting: I am in limited crowdsale mode. You have too many tokens to participate."); revert(); } } if (now<timeStarted) return false; //do not create tokens before it is started if (playValue == 0) { //LogMsg(msg.sender, "makeTokens: Cannot receive 0 ETH."); // do not log message, no need to help hackers return false; // cannot receive 0 ETH } if (msg.sender == 0) return false; // sender cannot be null if (isGameOn) { // check if we are out of limit if (limitMaxGame>0) { // 0 is unlimited <>0 then we limit the maximum bet for the game if (playValue>limitMaxGame) { LogMsg(msg.sender, "Your bet is > to the limitMaxGame limit. Check the website to see what is the maximum value to bet in the game at this time."); revert(); } } // this is when the game is on (crowdsale finished) uint bet=lastDecimal(playValue); // this is the number the player bet uint drawn=rand(0,9); // store the bets so that the website can list the results // address playeraddress; // uint time; // uint betinwai; // uint numberdrawn; // bool winornot; bettable[betNumber].playeraddress=msg.sender; bettable[betNumber].time=now; bettable[betNumber].betinwai=msg.value; bettable[betNumber].numberdrawn=drawn; bettable[betNumber].playerbet=bet; // check if win or not if (bet==drawn) bettable[betNumber].winornot=true; else bettable[betNumber].winornot=false; // case 1 the player wins => we send x*his bet if (bettable[betNumber].winornot==true) { uint moneytosend=playValue*tokenRate(); require(totalETHSupply>moneytosend); // not enough money? cancel the transaction sendEthBack(moneytosend); // x time the ETH bet back to the player and eventually switch to ICO mode }else{ // case 2 the player looses => we send tokenrate*his bet if (!isMaxCap10XReached) { // we still have tokens in stock tokens = safeMul(msg.value,tokenRate()); // send 10X * current rate checkTokenSupply = safeAdd(totalTokenSupply,tokens); // temporary variable to check the total supply if (tokens >= totalTokenSupply-(10 ether)) { // we cannot run the game with less than 100 ETH LogMsg(msg.sender, "Game mode: You are running out of tokens, please add more."); // need to switch to crowdfunding mode betNumber++; resetInternal(restartGamePeriod); // do a new ICO for x day. x is 1 by default but can be changed with externals return false; } // case 3, we have reached the max cap, we cannot deliver any tokens anymore, but the game can continue }else{ LogMsg(msg.sender, "Cannot deliver tokens. All tokens have been distributed. Hopefully the owner will mint more."); } if (checkTokenSupply >= tokenCreationCap) { // isMaxCap10XReached=true; LogMsg(msg.sender, "Game mode: We have reached the maximum capitalization."); betNumber++; return false; } // we are here -> giving tokens to the player. totalTokenSupply = checkTokenSupply; balances[msg.sender] += tokens; } Create10X(msg.sender, tokens); // event betNumber++; // increase the bet number index }else { // crowdfunding mode tokens = safeMul(msg.value,tokenRate()); // send 10X * current rate checkTokenSupply = safeAdd(totalTokenSupply,tokens); // temporary variable to check the total supply if (!isMaxCap10XReached) { // case 4, we are in normal crowdfunding mode if (tokens >= totalTokenSupply-(10 ether) || totalTokenSupply<=10 ether) { // LogMsg(msg.sender, "Crowdfunding mode: You are running out of tokens, please add more."); return false; // cannot continue } }else{ // case 3, we have reached the max cap, we cannot deliver any tokens anymore. if (isAutopilot) { isGameOn=true; // we switch in game mode, since there is no reason to raise any money. End of the crowdsale GameOnOff(isGameOn); LogMsg(msg.sender, "Max Cap reached, switching to game mode. End of the Crowdsale"); }else{ LogMsg(msg.sender, "End of the crowdsale. Autopilot is off and I am waiting for the owner to unPause me."); // we are in manual mode, so we pause the game and wait that owner decide. isGameOn=true; // we prepare everything to switch to game when owner is ready. GameOnOff(isGameOn); isPaused=true; InPauseMode(now,isPaused); } } // here if we are still in crowdsale mode updateStatusInternal(); // are we at the end of the crowdsale and other test? totalETHSupply+=msg.value; // updating the total ETH we received since if we are here that meant that the transaction was successfull balances[msg.sender] += tokens; // update the balance of the sender with the tokens he purchased totalTokenSupply = checkTokenSupply; // update the total token supplied } return true; } function() payable { require(blacklist[msg.sender]!=true); // blacklist system do not access if in the blacklist if (isDebug) { LogMsg(msg.sender, "Debugging something...we will be back soon. Your transaction has been cancelled."); revert(); } if (!isPaused) { // if the contract is not paused, otherwise, do nothing if (!makeTokens()) { LogMsg(msg.sender, "10X token cannot be delivered. Transaction cancelled."); revert(); } }else { LogMsg(msg.sender, "10X is paused. Please wait until it is running again."); revert(); } } // Reset manually the ICO to do another crowdfunding from external function reset(uint _value_goal, uint _value_crowdsale, uint _value_game,uint _value_duration, string _password) external onlyOwner protected(_password){ isGameOn=false; isfundingGoalReached = false; isPaused=false; InPauseMode(now,isPaused); isMaxCap10XReached=false; tokenDeliveryCrowdsalePrice=_value_crowdsale; tokenDeliveryPlayPrice=_value_game; fundingGoal = _value_goal * 1 ether; owner = msg.sender; deadline = now + ( _value_duration * 1 days); timeStarted=now; updateStatusInternal(); } // Reset automatically the ICO to do another crowdfunding, duration is in seconds, this is the internal version cheaper in gas function resetInternal( uint _value_duration) internal { isGameOn=false; // game mode is off we are doing a crowdfunding isfundingGoalReached = false; isPaused=false; InPauseMode(now,isPaused); isMaxCap10XReached=false; deadline = now + (_value_duration* 1 days); // set new duration in days timeStarted=now; } // get the info of a bet in a json table, I want it public for transparency, also the website need this. function getBet(uint256 _value) public constant returns(uint, uint, uint, uint,bool) { require(_value<betNumber && _value>=0); return (bettable[_value].time,bettable[_value].betinwai,bettable[_value].numberdrawn,bettable[_value].playerbet,bettable[_value].winornot); } // Sends eth to ethFundAddress (the contract owner) manually function sendEth(uint256 _value) external onlyOwner { require(_value >= totalETHSupply); if(!owner.send(_value) ) { // using send, checking that the operation was successful LogMsg(msg.sender, "sendEth: 10X cannot send this value of ETH, transaction cancelled."); revert(); } // if here send was sucessful } // Sends eth back to the player function sendEthBack(uint256 _value) internal { require (msg.sender>0); require (msg.sender != owner); // owner cannot send to himself uint tmpvalue=_value; // debugging otherwise cannot see this value in the debugger require (_value>0); if (_value > totalETHSupply-(10 ether) && totalETHSupply>=10 ether ) { // 100 ETH is the minium for the Bank to run, also check hack attempt with impossible values. resetInternal(restartGamePeriod); // in days, restartGamePeriod can be set to whatever LogMsg(msg.sender, "sendEthBack: not enough ETH to perform this operation."); if (!isAutopilot) { // if we are not in auto pilot, pause the game and let the owner decide. isPaused=true; InPauseMode(now,isPaused); } } if(!msg.sender.send(_value) ) { LogMsg(msg.sender, "sendEthBack: 10X cannot send this value of ETH. Refunding."); revert(); } // if here send was sucessful } // checks if the goal or time limit has been reached and ends the campaign (switch back in game mode) function updateStatusInternal() internal returns(bool){ if (now >= deadline) { // did we reached the deadline? if ( totalETHSupply >= fundingGoal){ // did we raised enough ETH? isfundingGoalReached = true; // end the crowdfunding GoalReached(owner, totalETHSupply); // shoot an event to log it } isGameOn = true; // crowdsale is closed, let's play the game. GameOnOff(isGameOn); if (!isAutopilot) { // we are not in autopilot mode, then pause the game and let the owner decide when to switch to game more. isPaused=true; InPauseMode(now,isPaused); } }else{ isGameOn=false;} // still in crowdfunding mode, let's continue in this mode if (totalTokenSupply >= tokenCreationCap) { isMaxCap10XReached=true; } else isMaxCap10XReached=false; return(isGameOn); } // checks if the goal or time limit has been reached and ends the campaign (switch back in game mode) function updateStatus() external onlyOwner returns(bool){ // if (now >= deadline) { // did we reached the deadline? if ( totalETHSupply >= fundingGoal){ // did we raised enough ETH? isfundingGoalReached = true; GoalReached(owner, totalETHSupply); // shoot an event to log it } isGameOn = true; // crowdsale is closed, let's play the game. GameOnOff(isGameOn); if (!isAutopilot) { // we are not in autopilot mode, then pause the game and let the owner decide when to switch to game more. isPaused=true; InPauseMode(now,isPaused); } }else{ isGameOn=false;} if (totalTokenSupply >= tokenCreationCap) { isMaxCap10XReached=true; } else isMaxCap10XReached=false; return(isGameOn); } // Add ETH manually function addEth() payable external onlyOwner{ if (!isGameOn) { LogMsg(msg.sender, "addEth: 10X crowdfunding is has not ended. Cannot do that now."); revert(); } totalETHSupply += msg.value; } // Add tokens manually to the game in ether function addTokens(uint256 _mintedAmount,string _password) external onlyOwner protected(_password) { require(_mintedAmount * 1 ether <= 10000000 * 1 ether); // do not add more than 1 Million token, avoid mistake safeAdd(totalTokenSupply ,_mintedAmount * 1 ether); } // Sub tokens manually from the game function subTokens(uint256 _mintedAmount,string _password) external onlyOwner protected(_password) { require(_mintedAmount * 1 ether <= 10000000 * 1 ether); // do not sub more than 1 Million Ether, avoid mistake require(_mintedAmount * 1 ether > totalTokenSupply); // do not go under 0 safeSub(totalTokenSupply ,_mintedAmount * 1 ether); } // Give tokens to someone function giveToken(address _target, uint256 _mintedAmount,string _password) external onlyOwner protected(_password) { safeAdd(balances[_target],_mintedAmount); safeAdd(totalTokenSupply,_mintedAmount); if (isPrintTokenInfinite==true) Transfer(0, owner, _mintedAmount); // if we want to mint ad infinity create token from thin air Transfer(owner, _target, _mintedAmount); // event } // Take tokens from someone function takeToken(address _target, uint256 _mintedAmount, string _password) external onlyOwner protected(_password) { safeSub(balances[_target], _mintedAmount); safeSub(totalTokenSupply,_mintedAmount); Transfer(0, owner, _mintedAmount); // event Transfer(owner, _target, _mintedAmount); // event } // Is an expeditive way to switch from crowdsale to game mode function switchToGame(string _password) external onlyOwner protected(_password) { require(!isGameOn); // re-entrance check isGameOn = true; // start the game GameOnOff(isGameOn); } // Is an expeditive way to switch from game mode to crowdsale function switchToCrowdsale(string _password) external onlyOwner protected(_password) { require(isGameOn); // re-entrance check isGameOn = false; // start the game GameOnOff(isGameOn); } // random number (miner proof) function rand(uint _min, uint _max) internal returns (uint){ require(_min>=0); require(_max>_min); bytes32 hashVal = bytes32(block.blockhash(block.number - exresult)); if (seed==0) seed=uint(hashVal); else { safeAdd(safeDiv(seed,2),safeDiv(uint(hashVal),2)); } uint result=safeAdd(uint(hashVal)%_max,_min)+1; exresult=safeAdd(result%200,1); return uint(result); } // Destroy this contract (cry) function destroyContract(string _password) external onlyOwner protected(_password) { selfdestruct(owner); // commit suicide! } // convert a string to bytes function stringToBytes( string _s) internal constant returns (bytes){ bytes memory b3 = bytes(_s); return b3; } // take the last byte and extract a number between 1-9 (drawn number) function lastChar(string _x) internal constant returns (uint8) { bytes memory a=stringToBytes(_x); if (a.length<=1) revert(); uint8 b=uint8(a[a.length-1])-48; b=b%10; if (b<0) { LogMsg(msg.sender, "tochar: Impossible, address logged"); if (msg.sender!=owner) blacklist[msg.sender]=true; revert(); } return b; } // get the last char from a string exclude 0 function lastCharNoZero(string _x) internal constant returns (uint8) { bytes memory a=stringToBytes(_x); uint len=a.length; if (len<=1) revert(); uint8 b=uint8(a[len-1])-48; b=b%10; while (b==0 && len>0) { len--; b=uint8(a[len-1])-48; } if (b<0) { LogMsg(msg.sender, "tochar: Impossible, address blacklisted"); blacklist[msg.sender]; revert(); } return b; } // last decimal ex:"1945671234000000000" => 4 function lastDecimal(uint256 _x) internal constant returns (uint) { //$a=$x/(pow(10,$i)); //$b=$a%10; uint a; for (uint i=1;i<20;i++) { a=(_x/(10**i)%10); if (a>0) return a; } return 0; } // change the current play price function setPlayPrice(uint _value, string _password ) onlyOwner external protected(_password) { require(_value<=1000); // security, we can get crazy and offer 1000 tokens for a special promotion but no more, written in the marble of the blockchain tokenDeliveryPlayPrice=_value; } // get play price function getTotalTokenSupply() constant external returns(uint){ return tokenDeliveryPlayPrice; } // Change the max capitalisation token function setMaxCap10X(uint _value, string _password ) onlyOwner external protected(_password) { require(_value>tokenCreationCap); // we cannot set the max token capitalization lower than what it is otherwise we f*ck up the logic of the game and cannot go back require(_value>totalTokenSupply); // of course, the new max capitalization must be higher than the current token supply, otherwise, what is the point? totalTokenSupply=_value; // magic, creation of money isMaxCap10XReached=false; } // get number of tokens available for delivery function getMaxCap10X() constant external returns(uint){ return tokenCreationCap; } // Change the limit for a transaction at the crowdsale: in case we do not want people to buy too much at the time, we can limit the max value a transaction can be function setLimitMaxCrowdsale(uint _value, string _password ) onlyOwner external protected(_password){ require(_value>=0); // of course cannot be 0 require(_value<100000 ether); // if it is >100000 there must be an error or a mistake limitMaxCrowdsale=_value; } // Get the current limit function getLimitMaxGame() constant external returns(uint){ return limitMaxGame; } // Change the limit for a transaction in the game : for example we have ETH in the bank but want to limit the game to bets <=2 ETH function setLimitGame(uint _value, string _password ) onlyOwner external protected(_password){ require(_value>=0); // of course cannot be 0 require(_value<100000 ether); // if it is >100000 there must be an error or a mistake limitMaxGame=_value; } // Get the current limit function getLimitMaxCrowdsale() constant external returns(uint){ return limitMaxCrowdsale; } // get max the current crowdsale price function getCrowdsalePrice( ) constant external returns(uint){ return tokenDeliveryCrowdsalePrice; } // change the current crowdsale status, different variant just in case, spend some gas for nothing. function setGameStatus(bool _value,string _password ) onlyOwner external protected(_password) { isGameOn=_value; GameOnOff(isGameOn); } // get the status of the game true= game / false = crowdfunding function getGameStatus( ) constant external returns(bool){ return isGameOn; } // limit the ICO to 1 transaction per address function setIsLimited(bool _value,string _password ) onlyOwner external protected(_password) { isLimited=_value; } // get limited status function getIsLimited( ) constant external returns(bool){ return isLimited; } // change the current crowdsale price function setCrowdsalePrice(uint _value,string _password ) onlyOwner external protected(_password) returns(bool){ require(_value<=10000); // crowdsale price cannot be >10,000 / ETH let's not do like SNT tokenDeliveryCrowdsalePrice=_value; return true; } // change the current contract owner function changeContractOwner(address _value,string _password) onlyOwner external protected(_password){ owner = _value; } // get the current contract owner function getContractOwner( ) constant external onlyOwner returns(address){ return owner; } // change the restart time period for the temp ICO function setRestartGamePeriod(uint _value, string _password ) onlyOwner external protected(_password){ require(_value>=1 && _value<= 365); // value is in days, cannot be less than 1 day or > 365 days restartGamePeriod=_value; // in days } }
take the last byte and extract a number between 1-9 (drawn number)
function lastChar(string _x) internal constant returns (uint8) { bytes memory a=stringToBytes(_x); if (a.length<=1) revert(); uint8 b=uint8(a[a.length-1])-48; b=b%10; if (b<0) { LogMsg(msg.sender, "tochar: Impossible, address logged"); if (msg.sender!=owner) blacklist[msg.sender]=true; revert(); } return b; }
12,609,358
[ 1, 22188, 326, 1142, 1160, 471, 2608, 279, 1300, 3086, 404, 17, 29, 261, 9446, 82, 1300, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23914, 12, 1080, 389, 92, 13, 225, 2713, 5381, 1135, 261, 11890, 28, 13, 288, 203, 3639, 1731, 3778, 279, 33, 1080, 21033, 24899, 92, 1769, 203, 3639, 309, 261, 69, 18, 2469, 32, 33, 21, 13, 15226, 5621, 203, 3639, 2254, 28, 324, 33, 11890, 28, 12, 69, 63, 69, 18, 2469, 17, 21, 5717, 17, 8875, 31, 203, 3639, 324, 33, 70, 9, 2163, 31, 203, 3639, 309, 261, 70, 32, 20, 13, 288, 203, 5411, 1827, 3332, 12, 3576, 18, 15330, 16, 315, 869, 3001, 30, 2221, 12708, 16, 1758, 7545, 8863, 203, 5411, 309, 261, 3576, 18, 15330, 5, 33, 8443, 13, 11709, 63, 3576, 18, 15330, 65, 33, 3767, 31, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 327, 324, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8f07ABE7FA18a56930889a7FFEB9d78D8361DFd7/sources/contracts/BeardGangLandNFTICO.sol
* @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 conforms the base architecture for crowdsales. It is not intended to be modified / overridden. The internal interface conforms the extensible and modifiable surface of crowdsales. Override the methods to add functionality. Consider using 'super' where appropriate to concatenate behavior./ The token being sold Amount of wei raised Address where funds are collected Private Sale price is 0.05ETH
contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; IBeardGangLandNFTToken private _token; uint256 private _weiRaised; address payable private _wallet; uint256 internal _rate = 50000000000000000; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 mintAmount); constructor (address payable __wallet, IBeardGangLandNFTToken __token) public { require(__wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(__token) != address(0), "Crowdsale: token is the zero address"); _wallet = __wallet; _token = __token; } function token() public view virtual returns (IBeardGangLandNFTToken) { return _token; } function wallet() public view virtual returns (address payable) { return _wallet; } function rate() public view virtual returns (uint256) { return _rate; } function weiRaised() public view virtual returns (uint256) { return _weiRaised; } function buyNFT(address beneficiary, uint256 mintAmount) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, mintAmount, weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, mintAmount); emit TokensPurchased(_msgSender(), beneficiary, mintAmount); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(beneficiary, weiAmount); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 mintAmount, uint256 weiAmount) internal virtual { } function _processPurchase(address beneficiary, uint256 mintAmount) internal virtual { _deliverTokens(beneficiary, mintAmount); } function _deliverTokens(address beneficiary, uint256 mintAmount) internal { require( token().mint(beneficiary, mintAmount) , "Crowdsale: transfer failed" ); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual { } function _forwardFunds(address /*beneficiary*/, uint256 /*weiAmount*/) internal virtual { _wallet.transfer(msg.value); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { } }
9,605,295
[ 1, 39, 492, 2377, 5349, 225, 385, 492, 2377, 5349, 353, 279, 1026, 6835, 364, 30632, 279, 1147, 276, 492, 2377, 5349, 16, 15632, 2198, 395, 1383, 358, 23701, 2430, 598, 225, 2437, 18, 1220, 6835, 4792, 4123, 14176, 316, 2097, 4486, 284, 1074, 14773, 287, 646, 471, 848, 506, 7021, 358, 5615, 3312, 14176, 471, 19, 280, 1679, 6885, 18, 1021, 3903, 1560, 8686, 326, 5337, 1560, 364, 5405, 343, 11730, 2430, 16, 471, 356, 9741, 326, 1026, 27418, 364, 276, 492, 2377, 5408, 18, 2597, 353, 486, 12613, 358, 506, 4358, 342, 11000, 18, 1021, 2713, 1560, 356, 9741, 326, 1110, 773, 1523, 471, 681, 8424, 9034, 434, 276, 492, 2377, 5408, 18, 1439, 326, 2590, 358, 527, 14176, 18, 23047, 1450, 296, 9565, 11, 1625, 5505, 358, 11361, 6885, 18, 19, 1021, 1147, 3832, 272, 1673, 16811, 434, 732, 77, 11531, 5267, 1625, 284, 19156, 854, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 385, 492, 2377, 5349, 353, 1772, 16, 868, 8230, 12514, 16709, 225, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 1919, 1060, 43, 539, 29398, 50, 4464, 1345, 3238, 389, 2316, 31, 203, 203, 565, 2254, 5034, 3238, 389, 1814, 77, 12649, 5918, 31, 203, 203, 565, 1758, 8843, 429, 3238, 389, 19177, 31, 203, 203, 565, 2254, 5034, 2713, 389, 5141, 273, 1381, 12648, 12648, 31, 203, 203, 565, 871, 13899, 10262, 343, 8905, 12, 2867, 8808, 5405, 343, 14558, 16, 1758, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 312, 474, 6275, 1769, 203, 203, 203, 565, 3885, 261, 2867, 8843, 429, 1001, 19177, 16, 467, 1919, 1060, 43, 539, 29398, 50, 4464, 1345, 1001, 2316, 13, 1071, 288, 203, 3639, 2583, 12, 972, 19177, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 9230, 353, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 2867, 12, 972, 2316, 13, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 1147, 353, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 19177, 273, 1001, 19177, 31, 203, 3639, 389, 2316, 273, 1001, 2316, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 1435, 1071, 1476, 5024, 1135, 261, 45, 1919, 1060, 43, 539, 29398, 50, 4464, 1345, 13, 288, 203, 3639, 327, 389, 2316, 31, 203, 565, 289, 203, 203, 565, 445, 9230, 1435, 1071, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 389, 19177, 31, 203, 565, 289, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-08-29 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Interface for discreet in addition to the standard ERC721 interface. */ interface discreetNFTInterface { /** * @dev Mint token with the supplied tokenId if it is currently available. */ function mint(uint256 tokenId) external; /** * @dev Mint token with the supplied tokenId if it is currently available to * another address. */ function mint(address to, uint256 tokenId) external; /** * @dev Burn token with the supplied tokenId if it is owned, approved or * reclaimable. Tokens become reclaimable after ~4 million blocks without a * mint or transfer. */ function burn(uint256 tokenId) external; /** * @dev Check the current block number at which a given token will become * reclaimable. */ function reclaimableThreshold(uint256 tokenId) external view returns (uint256); } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title 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); } /** * @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); } interface IENSReverseRegistrar { function claim(address owner) external returns (bytes32 node); function setName(string calldata name) external returns (bytes32 node); } /** * @dev Implementation of the {IERC165} interface. */ 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 ERC165, IERC721, IERC721Metadata { // Token name bytes14 private immutable _name; // Token symbol bytes13 private immutable _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(bytes14 name_, bytes13 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() external view virtual override returns (string memory) { return string(abi.encodePacked(_name)); } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external view virtual override returns (string memory) { return string(abi.encodePacked(_symbol)); } /** * @dev NOTE: standard functionality overridden. */ function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {} /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "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) external virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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 ) external virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 ) external 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(msg.sender, 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 { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, ""), "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) { uint256 size; assembly { size := extcodesize(to) } if (size > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, 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 {} } /** * @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) external 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) external 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(); } } /** * @dev extra-discreet * @author 0age */ contract extraDiscreetNFT is discreetNFTInterface, ERC721, ERC721Enumerable { // Map tokenIds to block numbers past which they are burnable by any caller. mapping(uint256 => uint256) private _reclaimableThreshold; // Map transaction submitters to the block number of their last token mint. mapping(address => uint256) private _lastTokenMinted; // Fixed base64-encoded SVG fragments used across all images. bytes32 private constant h0 = 'data:image/svg+xml;base64,PD94bW'; bytes32 private constant h1 = 'wgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz'; bytes32 private constant h2 = '0iVVRGLTgiPz48c3ZnIHZpZXdCb3g9Ij'; bytes32 private constant h3 = 'AgMCA1MDAgNTAwIiB4bWxucz0iaHR0cD'; bytes32 private constant h4 = 'ovL3d3dy53My5vcmcvMjAwMC9zdmciIH'; bytes32 private constant h5 = 'N0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOi'; bytes4 private constant m0 = 'iPjx'; bytes10 private constant m1 = 'BmaWxsPSIj'; bytes16 private constant f0 = 'IiAvPjwvc3ZnPg=='; address public constant discreet = 0x3c77065B584D4Af705B3E38CC35D336b081E4948; address private immutable _admin; uint256 private immutable _deployedAt; mapping(address => bool) private _hasMintedAnOutOfRangeToken; /** * @dev Deploy discreet as an ERC721 NFT. */ constructor() ERC721("extra-discreet", "EXTRADISCREET") { // Set up ENS reverse registrar. IENSReverseRegistrar _ensReverseRegistrar = IENSReverseRegistrar( 0x084b1c3C81545d370f3634392De611CaaBFf8148 ); _ensReverseRegistrar.claim(msg.sender); _ensReverseRegistrar.setName("extra.discreet.eth"); _admin = tx.origin; _deployedAt = block.number; } /** * @dev Throttle minting to once a block and reset the reclamation threshold * whenever a new token is minted or transferred. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); // If minting: ensure it's the only one from this tx origin in the block. if (from == address(0)) { require( block.number > _lastTokenMinted[tx.origin], "extra-discreet: cannot mint multiple tokens per block from a single origin" ); _lastTokenMinted[tx.origin] = block.number; } // If not burning: reset tokenId's reclaimable threshold block number. if (to != address(0)) { _reclaimableThreshold[tokenId] = block.number + 0x400000; } } /** * @dev Mint a given discreet NFT if it is currently available. */ function mint(uint256 tokenId) external override { require(tokenId < 0x120, "extra-discreet: cannot mint out-of-range token"); require( msg.sender == _admin || block.number > _deployedAt + 0x10000, "extra-discreet: only admin can mint directly for initial period" ); _safeMint(msg.sender, tokenId); } /** * @dev Mint a given NFT if it is currently available to a given address. */ function mint(address to, uint256 tokenId) external override { require(tokenId < 0x120, "extra-discreet: cannot mint out-of-range token"); require( msg.sender == _admin || block.number > _deployedAt + 0x10000, "extra-discreet: only admin can mint directly for initial period" ); _safeMint(to, tokenId); } /** * @dev Mint a given NFT if it is currently available to a given address. */ function mintFromOutOfRangeDiscreet(uint256 oldDiscreetTokenId, uint256 newExtraDiscreetTokenId) external { require( newExtraDiscreetTokenId < 0x120, "extra-discreet: cannot mint out-of-range token" ); // old token needs to be out of range require( oldDiscreetTokenId >= 0x240, "extra-discreet: cannot mint using in-range discreet token" ); // old token needs to be owned by caller address oldOwner = IERC721(discreet).ownerOf(oldDiscreetTokenId); require( oldOwner == msg.sender, "extra-discreet: cannot mint using unowned discreet token" ); // token needs to be "old" (i.e. hasn't been minted or transferred since // deploying this contract) uint256 oldReclaimableThreshold = discreetNFTInterface(discreet).reclaimableThreshold(oldDiscreetTokenId); uint256 lastMoved = oldReclaimableThreshold - 0x400000; require( lastMoved < _deployedAt, "extra-discreet: cannot mint using out-of-range discreet token that has moved since deployment of this contract" ); // Only one token can be minted per caller using this method require( !_hasMintedAnOutOfRangeToken[msg.sender], "extra-discreet: can only mint using out-of-range discreet token once per caller" ); _hasMintedAnOutOfRangeToken[msg.sender] = true; _safeMint(msg.sender, newExtraDiscreetTokenId); } /** * @dev Burn a given discreet NFT if it is owned, approved or reclaimable. * Tokens become reclaimable after ~4 million blocks without a transfer. */ function burn(uint256 tokenId) external override { // Only enforce check if tokenId has not reached reclaimable threshold. if (_reclaimableThreshold[tokenId] < block.number) { require( _isApprovedOrOwner(msg.sender, tokenId), "extra-discreet: caller is not owner nor approved" ); } _burn(tokenId); } /** * @dev Check the current block number at which the given token will become * reclaimable. */ function reclaimableThreshold(uint256 tokenId) external view override returns (uint256) { return _reclaimableThreshold[tokenId]; } /** * @dev Derive and return a discreet tokenURI formatted as a data URI. */ function tokenURI(uint256 tokenId) external pure virtual override returns (string memory) { require(tokenId < 0x120, "extra-discreet: URI query for out-of-range token"); // Nine base64-encoded SVG fragments for background colors. bytes9[9] memory c0 = [ bytes9('MwMDAwMDA'), 'M2OWZmMzc', 'NmZjM3Njk', 'MzNzY5ZmY', 'NmZmZmOTA', 'M5MGZmZmY', 'NmZjkwZmY', 'NmZmZmZmY', 'M4MDgwODA' ]; // Four base64-encoded SVG fragments for primary shapes. string[4] memory s0 = [ 'wb2x5Z29uIHBvaW50cz0iNDAwLDEwMCA0MDAsNDAwIDEwMCw0MDAiIC', 'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsNDAwIDEwMCwxMDAiIC', 'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC', 'wb2x5Z29uIHBvaW50cz0iNDAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC' ]; // Nine base64-encoded SVG fragments for primary colors. bytes8[9] memory c1 = [ bytes8('NjlmZjM3'), 'ZmYzNzY5', 'Mzc2OWZm', 'ZmZmZjkw', 'OTBmZmZm', 'ZmY5MGZm', 'ZmZmZmZm', 'ODA4MDgw', 'MDAwMDAw' ]; // Construct a discrete tokenURI from a unique combination of the above. uint256 c0i = (tokenId % 72) / 8; uint256 s0i = tokenId / 72; uint256 c1i = (tokenId % 8 + (tokenId / 8)) % 9; return string( abi.encodePacked( h0, h1, h2, h3, h4, h5, c0[c0i], m0, s0[s0i], m1, c1[c1i], f0 ) ); } /** * @dev Coalesce supportsInterface from inherited contracts. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
* @dev Interface for discreet in addition to the standard ERC721 interface./
interface discreetNFTInterface { function mint(uint256 tokenId) external; function mint(address to, uint256 tokenId) external; function burn(uint256 tokenId) external; function reclaimableThreshold(uint256 tokenId) external view returns (uint256); pragma solidity 0.8.7; }
7,702,837
[ 1, 1358, 364, 1015, 1793, 278, 316, 2719, 358, 326, 4529, 4232, 39, 27, 5340, 1560, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1015, 1793, 278, 50, 4464, 1358, 288, 203, 565, 445, 312, 474, 12, 11890, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 18305, 12, 11890, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 283, 14784, 429, 7614, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: NONE pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @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; } } // File: DAWG.sol contract DAWG { /// @notice EIP-20 token name for this token string public constant name = "Inumaki"; /// @notice EIP-20 token symbol for this token string public constant symbol = "DAWG"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 1_000_000_000e18; // 100 million DAWG mapping (address => mapping (address => uint96)) internal allowances; mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DAWG token */ constructor() public { balances[msg.sender] = uint96(totalSupply); emit Transfer(address(0), msg.sender, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "DAWG::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline 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 permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "DAWG::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "DAWG::permit: invalid signature"); require(signatory == owner, "DAWG::permit: unauthorized"); require(now <= deadline, "DAWG::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "DAWG::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "DAWG::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) 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), "DAWG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DAWG::delegateBySig: invalid nonce"); require(now <= expiry, "DAWG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "DAWG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "DAWG::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "DAWG::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "DAWG::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "DAWG::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "DAWG::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "DAWG::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "DAWG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @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/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "DAWG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
59,205
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 3903, 1476, 1135, 261, 11890, 10525, 13, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 9793, 59, 43, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xE4ED7dc465A367F8a1A58526Da407dDD5a232E0C/sources/contracts/SonicaERC721DelayedReveal.sol
@dev Checks whether platform fee info can be set in the given execution context.
function _canSetClaimConditions() internal view virtual returns (bool) { return msg.sender == owner(); }
5,574,061
[ 1, 4081, 2856, 4072, 14036, 1123, 848, 506, 444, 316, 326, 864, 4588, 819, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4169, 694, 9762, 8545, 1435, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 1234, 18, 15330, 422, 3410, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {IOracle} from "./interfaces/IOracle.sol"; import "./interfaces/IButtonToken.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @title The ButtonToken ERC20 wrapper. * * @dev The ButtonToken is a rebasing wrapper for fixed balance ERC-20 tokens. * * Users deposit the "underlying" (wrapped) tokens and are * minted button (wrapper) tokens with elastic balances * which change up or down when the value of the underlying token changes. * * For example: Manny “wraps” 1 Ether when the price of Ether is $1800. * Manny receives 1800 ButtonEther tokens in return. * The overall value of their ButtonEther is the same as their original Ether, * however each unit is now priced at exactly $1. The next day, * the price of Ether changes to $1900. The ButtonEther system detects * this price change, and rebases such that Manny’s balance is * now 1900 ButtonEther tokens, still priced at $1 each. * * The ButtonToken math is almost identical to Ampleforth's μFragments. * * For AMPL, internal balances are represented using `gons` and * -> internal account balance `_gonBalances[account]` * -> internal supply scalar `gonsPerFragment = TOTAL_GONS / _totalSupply` * -> public balance `_gonBalances[account] * gonsPerFragment` * -> public total supply `_totalSupply` * * In our case internal balances are stored as 'bits'. * -> underlying token unit price `p_u = price / 10 ^ (PRICE_DECIMALS)` * -> total underlying tokens `_totalUnderlying` * -> internal account balance `_accountBits[account]` * -> internal supply scalar `_bitsPerToken` ` = TOTAL_BITS / (MAX_UNDERLYING*p_u)` * ` = BITS_PER_UNDERLYING*(10^PRICE_DECIMALS)/price` * ` = PRICE_BITS / price` * -> user's underlying balance `(_accountBits[account] / BITS_PER_UNDERLYING` * -> public balance `_accountBits[account] * _bitsPerToken` * -> public total supply `_totalUnderlying * p_u` * * */ contract ButtonToken is IButtonToken, Initializable, OwnableUpgradeable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // We make the following guarantees: // - If address 'A' transfers x button tokens to address 'B'. // A's resulting external balance will be decreased by "precisely" x button tokens, // and B's external balance will be "precisely" increased by x button tokens. // - If address 'A' deposits y underlying tokens, // A's resulting underlying balance will increase by "precisely" y. // - If address 'A' withdraws y underlying tokens, // A's resulting underlying balance will decrease by "precisely" y. // using SafeERC20 for IERC20; //-------------------------------------------------------------------------- // Constants /// @dev The price has a 8 decimal point precision. uint256 public constant PRICE_DECIMALS = 8; /// @dev Math constants. uint256 private constant MAX_UINT256 = type(uint256).max; /// @dev The maximum units of the underlying token that can be deposited into this contract /// ie) for a underlying token with 18 decimals, MAX_UNDERLYING is 1B tokens. uint256 public constant MAX_UNDERLYING = 1_000_000_000e18; /// @dev TOTAL_BITS is a multiple of MAX_UNDERLYING so that {BITS_PER_UNDERLYING} is an integer. /// Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_BITS = MAX_UINT256 - (MAX_UINT256 % MAX_UNDERLYING); /// @dev Number of BITS per unit of deposit. uint256 private constant BITS_PER_UNDERLYING = TOTAL_BITS / MAX_UNDERLYING; /// @dev Number of BITS per unit of deposit * (1 USD). uint256 private constant PRICE_BITS = BITS_PER_UNDERLYING * (10**PRICE_DECIMALS); /// @dev TRUE_MAX_PRICE = maximum integer < (sqrt(4*PRICE_BITS + 1) - 1) / 2 /// Setting MAX_PRICE to the closest two power which is just under TRUE_MAX_PRICE. uint256 public constant MAX_PRICE = (2**96 - 1); // (2^96) - 1 //-------------------------------------------------------------------------- // Attributes /// @inheritdoc IButtonWrapper address public override underlying; /// @inheritdoc IButtonToken address public override oracle; /// @inheritdoc IButtonToken uint256 public override lastPrice; /// @dev Rebase counter uint256 _epoch; /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @dev internal balance, bits issued per account mapping(address => uint256) private _accountBits; /// @dev ERC20 allowances mapping(address => mapping(address => uint256)) private _allowances; //-------------------------------------------------------------------------- // Modifiers modifier validRecipient(address to) { require(to != address(0x0), "ButtonToken: recipient zero address"); require(to != address(this), "ButtonToken: recipient token address"); _; } modifier onAfterRebase() { uint256 price; bool valid; (price, valid) = _queryPrice(); if (valid) { _rebase(price); } _; } //-------------------------------------------------------------------------- /// @param underlying_ The underlying ERC20 token address. /// @param name_ The ERC20 name. /// @param symbol_ The ERC20 symbol. /// @param oracle_ The oracle which provides the underlying token price. function initialize( address underlying_, string memory name_, string memory symbol_, address oracle_ ) public override initializer { require(underlying_ != address(0), "ButtonToken: invalid underlying reference"); // Initializing ownership to `msg.sender` __Ownable_init(); underlying = underlying_; name = name_; symbol = symbol_; // MAX_UNDERLYING worth bits are 'pre-mined' to `address(0x)` // at the time of construction. // // During mint, bits are transferred from `address(0x)` // and during burn, bits are transferred back to `address(0x)`. // // No more than MAX_UNDERLYING can be deposited into the ButtonToken contract. _accountBits[address(0)] = TOTAL_BITS; updateOracle(oracle_); } //-------------------------------------------------------------------------- // Owner only actions /// @inheritdoc IButtonToken function updateOracle(address oracle_) public override onlyOwner { uint256 price; bool valid; oracle = oracle_; (price, valid) = _queryPrice(); require(valid, "ButtonToken: unable to fetch data from oracle"); emit OracleUpdated(oracle); _rebase(price); } //-------------------------------------------------------------------------- // ERC20 description attributes /// @inheritdoc IERC20Metadata function decimals() external view override returns (uint8) { return IERC20Metadata(underlying).decimals(); } //-------------------------------------------------------------------------- // ERC-20 token view methods /// @inheritdoc IERC20 function totalSupply() external view override returns (uint256) { uint256 price; (price, ) = _queryPrice(); return _bitsToAmount(_activeBits(), price); } /// @inheritdoc IERC20 function balanceOf(address account) external view override returns (uint256) { if (account == address(0)) { return 0; } uint256 price; (price, ) = _queryPrice(); return _bitsToAmount(_accountBits[account], price); } /// @inheritdoc IRebasingERC20 function scaledTotalSupply() external view override returns (uint256) { return _bitsToUAmount(_activeBits()); } /// @inheritdoc IRebasingERC20 function scaledBalanceOf(address account) external view override returns (uint256) { if (account == address(0)) { return 0; } return _bitsToUAmount(_accountBits[account]); } /// @inheritdoc IERC20 function allowance(address owner_, address spender) external view override returns (uint256) { return _allowances[owner_][spender]; } //-------------------------------------------------------------------------- // ButtonWrapper view methods /// @inheritdoc IButtonWrapper function totalUnderlying() external view override returns (uint256) { return _bitsToUAmount(_activeBits()); } /// @inheritdoc IButtonWrapper function balanceOfUnderlying(address who) external view override returns (uint256) { if (who == address(0)) { return 0; } return _bitsToUAmount(_accountBits[who]); } /// @inheritdoc IButtonWrapper function underlyingToWrapper(uint256 uAmount) external view override returns (uint256) { uint256 price; (price, ) = _queryPrice(); return _bitsToAmount(_uAmountToBits(uAmount), price); } /// @inheritdoc IButtonWrapper function wrapperToUnderlying(uint256 amount) external view override returns (uint256) { uint256 price; (price, ) = _queryPrice(); return _bitsToUAmount(_amountToBits(amount, price)); } //-------------------------------------------------------------------------- // ERC-20 write methods /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override validRecipient(to) onAfterRebase returns (bool) { _transfer(_msgSender(), to, _amountToBits(amount, lastPrice), amount); return true; } /// @inheritdoc IRebasingERC20 function transferAll(address to) external override validRecipient(to) onAfterRebase returns (bool) { uint256 bits = _accountBits[_msgSender()]; _transfer(_msgSender(), to, bits, _bitsToAmount(bits, lastPrice)); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override validRecipient(to) onAfterRebase returns (bool) { if (_allowances[from][_msgSender()] != type(uint256).max) { _allowances[from][_msgSender()] -= amount; emit Approval(from, _msgSender(), _allowances[from][_msgSender()]); } _transfer(from, to, _amountToBits(amount, lastPrice), amount); return true; } /// @inheritdoc IRebasingERC20 function transferAllFrom(address from, address to) external override validRecipient(to) onAfterRebase returns (bool) { uint256 bits = _accountBits[from]; uint256 amount = _bitsToAmount(bits, lastPrice); if (_allowances[from][_msgSender()] != type(uint256).max) { _allowances[from][_msgSender()] -= amount; emit Approval(from, _msgSender(), _allowances[from][_msgSender()]); } _transfer(from, to, bits, amount); return true; } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { _allowances[_msgSender()][spender] = amount; emit Approval(_msgSender(), spender, amount); return true; } // @inheritdoc IERC20 function increaseAllowance(address spender, uint256 addedAmount) external returns (bool) { _allowances[_msgSender()][spender] += addedAmount; emit Approval(_msgSender(), spender, _allowances[_msgSender()][spender]); return true; } // @inheritdoc IERC20 function decreaseAllowance(address spender, uint256 subtractedAmount) external returns (bool) { if (subtractedAmount >= _allowances[_msgSender()][spender]) { delete _allowances[_msgSender()][spender]; } else { _allowances[_msgSender()][spender] -= subtractedAmount; } emit Approval(_msgSender(), spender, _allowances[_msgSender()][spender]); return true; } //-------------------------------------------------------------------------- // RebasingERC20 write methods /// @inheritdoc IRebasingERC20 function rebase() external override onAfterRebase { return; } //-------------------------------------------------------------------------- // ButtonWrapper write methods /// @inheritdoc IButtonWrapper function mint(uint256 amount) external override onAfterRebase returns (uint256) { uint256 bits = _amountToBits(amount, lastPrice); uint256 uAmount = _bitsToUAmount(bits); _deposit(_msgSender(), _msgSender(), uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function mintFor(address to, uint256 amount) external override onAfterRebase returns (uint256) { uint256 bits = _amountToBits(amount, lastPrice); uint256 uAmount = _bitsToUAmount(bits); _deposit(_msgSender(), to, uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function burn(uint256 amount) external override onAfterRebase returns (uint256) { uint256 bits = _amountToBits(amount, lastPrice); uint256 uAmount = _bitsToUAmount(bits); _withdraw(_msgSender(), _msgSender(), uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function burnTo(address to, uint256 amount) external override onAfterRebase returns (uint256) { uint256 bits = _amountToBits(amount, lastPrice); uint256 uAmount = _bitsToUAmount(bits); _withdraw(_msgSender(), to, uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function burnAll() external override onAfterRebase returns (uint256) { uint256 bits = _accountBits[_msgSender()]; uint256 uAmount = _bitsToUAmount(bits); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), _msgSender(), uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function burnAllTo(address to) external override onAfterRebase returns (uint256) { uint256 bits = _accountBits[_msgSender()]; uint256 uAmount = _bitsToUAmount(bits); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), to, uAmount, amount, bits); return uAmount; } /// @inheritdoc IButtonWrapper function deposit(uint256 uAmount) external override onAfterRebase returns (uint256) { uint256 bits = _uAmountToBits(uAmount); uint256 amount = _bitsToAmount(bits, lastPrice); _deposit(_msgSender(), _msgSender(), uAmount, amount, bits); return amount; } /// @inheritdoc IButtonWrapper function depositFor(address to, uint256 uAmount) external override onAfterRebase returns (uint256) { uint256 bits = _uAmountToBits(uAmount); uint256 amount = _bitsToAmount(bits, lastPrice); _deposit(_msgSender(), to, uAmount, amount, bits); return amount; } /// @inheritdoc IButtonWrapper function withdraw(uint256 uAmount) external override onAfterRebase returns (uint256) { uint256 bits = _uAmountToBits(uAmount); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), _msgSender(), uAmount, amount, bits); return amount; } /// @inheritdoc IButtonWrapper function withdrawTo(address to, uint256 uAmount) external override onAfterRebase returns (uint256) { uint256 bits = _uAmountToBits(uAmount); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), to, uAmount, amount, bits); return amount; } /// @inheritdoc IButtonWrapper function withdrawAll() external override onAfterRebase returns (uint256) { uint256 bits = _accountBits[_msgSender()]; uint256 uAmount = _bitsToUAmount(bits); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), _msgSender(), uAmount, amount, bits); return amount; } /// @inheritdoc IButtonWrapper function withdrawAllTo(address to) external override onAfterRebase returns (uint256) { uint256 bits = _accountBits[_msgSender()]; uint256 uAmount = _bitsToUAmount(bits); uint256 amount = _bitsToAmount(bits, lastPrice); _withdraw(_msgSender(), to, uAmount, amount, bits); return amount; } //-------------------------------------------------------------------------- // Private methods /// @dev Internal method to commit deposit state. /// NOTE: Expects bits, uAmount, amount to be pre-calculated. function _deposit( address from, address to, uint256 uAmount, uint256 amount, uint256 bits ) private { require(amount > 0, "ButtonToken: too few button tokens to mint"); IERC20(underlying).safeTransferFrom(from, address(this), uAmount); _transfer(address(0), to, bits, amount); } /// @dev Internal method to commit withdraw state. /// NOTE: Expects bits, uAmount, amount to be pre-calculated. function _withdraw( address from, address to, uint256 uAmount, uint256 amount, uint256 bits ) private { require(amount > 0, "ButtonToken: too few button tokens to burn"); _transfer(from, address(0), bits, amount); IERC20(underlying).safeTransfer(to, uAmount); } /// @dev Internal method to commit transfer state. /// NOTE: Expects bits/amounts to be pre-calculated. function _transfer( address from, address to, uint256 bits, uint256 amount ) private { _accountBits[from] -= bits; _accountBits[to] += bits; emit Transfer(from, to, amount); if (_accountBits[from] == 0) { delete _accountBits[from]; } } /// @dev Updates the `lastPrice` and recomputes the internal scalar. function _rebase(uint256 price) private { if (price > MAX_PRICE) { price = MAX_PRICE; } lastPrice = price; _epoch++; emit Rebase(_epoch, price); } /// @dev Returns the active "un-mined" bits function _activeBits() private view returns (uint256) { return TOTAL_BITS - _accountBits[address(0)]; } /// @dev Queries the oracle for the latest price /// If fetched oracle price isn't valid returns the last price, /// else returns the new price from the oracle. function _queryPrice() private view returns (uint256, bool) { uint256 newPrice; bool valid; (newPrice, valid) = IOracle(oracle).getData(); // Note: we consider newPrice == 0 to be invalid because accounting fails with price == 0 // For example, _bitsPerToken needs to be able to divide by price so a div/0 is caused return (valid && newPrice > 0 ? newPrice : lastPrice, valid && newPrice > 0); } /// @dev Convert button token amount to bits. function _amountToBits(uint256 amount, uint256 price) private pure returns (uint256) { return amount * _bitsPerToken(price); } /// @dev Convert underlying token amount to bits. function _uAmountToBits(uint256 uAmount) private pure returns (uint256) { return uAmount * BITS_PER_UNDERLYING; } /// @dev Convert bits to button token amount. function _bitsToAmount(uint256 bits, uint256 price) private pure returns (uint256) { return bits / _bitsPerToken(price); } /// @dev Convert bits to underlying token amount. function _bitsToUAmount(uint256 bits) private pure returns (uint256) { return bits / BITS_PER_UNDERLYING; } /// @dev Internal scalar to convert bits to button tokens. function _bitsPerToken(uint256 price) private pure returns (uint256) { return PRICE_BITS / price; } } // SPDX-License-Identifier: GPL-3.0-or-later interface IOracle { function getData() external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0-or-later import "./IRebasingERC20.sol"; import "./IButtonWrapper.sol"; // Interface definition for the ButtonToken ERC20 wrapper contract interface IButtonToken is IButtonWrapper, IRebasingERC20 { /// @dev The reference to the oracle which feeds in the /// price of the underlying token. function oracle() external view returns (address); /// @dev Most recent price recorded from the oracle. function lastPrice() external view returns (uint256); /// @dev Update reference to the oracle contract and resets price. /// @param oracle_ The address of the new oracle. function updateOracle(address oracle_) external; /// @dev Log to record changes to the oracle. /// @param oracle The address of the new oracle. event OracleUpdated(address oracle); /// @dev Contract initializer function initialize( address underlying_, string memory name_, string memory symbol_, address oracle_ ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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: GPL-3.0-or-later import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; // Interface definition for Rebasing ERC20 tokens which have a "elastic" external // balance and "fixed" internal balance. Each user's external balance is // represented as a product of a "scalar" and the user's internal balance. // // From time to time the "Rebase" event updates scaler, // which increases/decreases all user balances proportionally. // // The standard ERC-20 methods are denominated in the elastic balance // interface IRebasingERC20 is IERC20, IERC20Metadata { /// @notice Returns the fixed balance of the specified address. /// @param who The address to query. function scaledBalanceOf(address who) external view returns (uint256); /// @notice Returns the total fixed supply. function scaledTotalSupply() external view returns (uint256); /// @notice Transfer all of the sender's balance to a specified address. /// @param to The address to transfer to. /// @return True on success, false otherwise. function transferAll(address to) external returns (bool); /// @notice Transfer all balance tokens from one address to another. /// @param from The address to send tokens from. /// @param to The address to transfer to. function transferAllFrom(address from, address to) external returns (bool); /// @notice Triggers the next rebase, if applicable. function rebase() external; /// @notice Event emitted when the balance scalar is updated. /// @param epoch The number of rebases since inception. /// @param newScalar The new scalar. event Rebase(uint256 indexed epoch, uint256 newScalar); } // SPDX-License-Identifier: GPL-3.0-or-later // Interface definition for ButtonWrapper contract, which wraps an // underlying ERC20 token into a new ERC20 with different characteristics. // NOTE: "uAmount" => underlying token (wrapped) amount and // "amount" => wrapper token amount interface IButtonWrapper { //-------------------------------------------------------------------------- // ButtonWrapper write methods /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens. /// @param amount The amount of wrapper tokens to mint. /// @return The amount of underlying tokens deposited. function mint(uint256 amount) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param amount The amount of wrapper tokens to mint. /// @return The amount of underlying tokens deposited. function mintFor(address to, uint256 amount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param amount The amount of wrapper tokens to burn. /// @return The amount of underlying tokens withdrawn. function burn(uint256 amount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param amount The amount of wrapper tokens to burn. /// @return The amount of underlying tokens withdrawn. function burnTo(address to, uint256 amount) external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @return The amount of underlying tokens withdrawn. function burnAll() external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param to The beneficiary account. /// @return The amount of underlying tokens withdrawn. function burnAllTo(address to) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param uAmount The amount of underlying tokens to deposit. /// @return The amount of wrapper tokens mint. function deposit(uint256 uAmount) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param uAmount The amount of underlying tokens to deposit. /// @return The amount of wrapper tokens mint. function depositFor(address to, uint256 uAmount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param uAmount The amount of underlying tokens to withdraw. /// @return The amount of wrapper tokens burnt. function withdraw(uint256 uAmount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back to the specified beneficiary. /// @param to The beneficiary account. /// @param uAmount The amount of underlying tokens to withdraw. /// @return The amount of wrapper tokens burnt. function withdrawTo(address to, uint256 uAmount) external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @return The amount of wrapper tokens burnt. function withdrawAll() external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param to The beneficiary account. /// @return The amount of wrapper tokens burnt. function withdrawAllTo(address to) external returns (uint256); //-------------------------------------------------------------------------- // ButtonWrapper view methods /// @return The address of the underlying token. function underlying() external view returns (address); /// @return The total underlying tokens held by the wrapper contract. function totalUnderlying() external view returns (uint256); /// @param who The account address. /// @return The underlying token balance of the account. function balanceOfUnderlying(address who) external view returns (uint256); /// @param uAmount The amount of underlying tokens. /// @return The amount of wrapper tokens exchangeable. function underlyingToWrapper(uint256 uAmount) external view returns (uint256); /// @param amount The amount of wrapper tokens. /// @return The amount of underlying tokens exchangeable. function wrapperToUnderlying(uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // 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 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); } } } }
@inheritdoc IRebasingERC20
function scaledTotalSupply() external view override returns (uint256) { return _bitsToUAmount(_activeBits()); }
86,031
[ 1, 36, 10093, 467, 426, 9157, 310, 654, 39, 3462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12304, 5269, 3088, 1283, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 6789, 774, 57, 6275, 24899, 3535, 6495, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ /** *Submitted for verification at Etherscan.io on 2022-01-13 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract Downdle is ERC721Enumerable, Ownable { event PaymentReleased(address to, uint256 amount); mapping(address => bool) whitelistedAddresses; address[3] private _shareholders; uint[3] private _shares; using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.01 ether; uint256 public mintCount = 0; uint256 public maxSupply = 3333; uint256 public maxMintAmount = 20; bool public paused = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { // uint256 supply = totalSupply(); require(!paused, "Mint is currently paused"); require(_mintAmount > 0, "Mint amount must be greater than or equal to one"); require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per mint tx"); require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens"); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "Value does not match mint cost"); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, mintCount + i); } mintCount+=_mintAmount; } function walletOfOwner(address _owner) public view returns (uint256[] memory){ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function getMintCount() external view returns (uint256){ return mintCount; } function burn(uint256 tokenId) public virtual { _burn(tokenId); } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function pause(bool _state) public onlyOwner { paused = _state; } modifier isWhitelisted(address _address) { require(whitelistedAddresses[_address], "You need to be whitelisted"); _; } function checkIsWalletWhitelisted() public view isWhitelisted(msg.sender) returns(bool){ return (true); } function whitelistMint(uint256 _mintAmount) public payable { require(!paused, "Mint is currently paused"); require(_mintAmount > 0, "Mint amount must be greater than or equal to one"); require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per wallet"); require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens"); require(whitelistedAddresses[msg.sender], "Wallet is not whitelisted"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, mintCount + i); } mintCount+=_mintAmount; } function addWalletToWhiteList(address _addressToWhitelist) public onlyOwner { whitelistedAddresses[_addressToWhitelist] = true; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
* @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]; }
101,859
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 12296, 951, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 11013, 843, 364, 326, 3634, 1758, 8863, 203, 565, 327, 389, 70, 26488, 63, 8443, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface token { function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function allowance(address, address) external constant returns (uint256); function balanceOf(address) external constant returns (uint256); } /** LOGIC DESCRIPTION * 11% fees in and out for ETH * 11% fees in and out for NOVA * * ETH fees split: * 6% to nova holders * 4% to eth holders * 1% to fixed address * * NOVA fees split: * 6% to nova holders * 4% to eth holders * 1% airdrop to a random address based on their nova shares * rules: * - you need to have both nova and eth to get dividends */ contract NovaBox is Ownable { using SafeMath for uint; token tokenReward; constructor() public { tokenReward = token(0x72FBc0fc1446f5AcCC1B083F0852a7ef70a8ec9f); } event AirDrop(address to, uint amount, uint randomTicket); event DividendsTransferred(address to, uint ethAmount, uint novaAmount); // ether contributions mapping (address => uint) public contributionsEth; // token contributions mapping (address => uint) public contributionsToken; // investors list who have deposited BOTH ether and token mapping (address => uint) public indexes; mapping (uint => address) public addresses; uint256 public lastIndex = 0; mapping (address => bool) public addedToList; uint _totalTokens = 0; uint _totalWei = 0; uint pointMultiplier = 1e18; mapping (address => uint) public last6EthDivPoints; uint public total6EthDivPoints = 0; // uint public unclaimed6EthDivPoints = 0; mapping (address => uint) public last4EthDivPoints; uint public total4EthDivPoints = 0; // uint public unclaimed4EthDivPoints = 0; mapping (address => uint) public last6TokenDivPoints; uint public total6TokenDivPoints = 0; // uint public unclaimed6TokenDivPoints = 0; mapping (address => uint) public last4TokenDivPoints; uint public total4TokenDivPoints = 0; // uint public unclaimed4TokenDivPoints = 0; function ethDivsOwing(address _addr) public view returns (uint) { return eth4DivsOwing(_addr).add(eth6DivsOwing(_addr)); } function eth6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth6DivPoints = total6EthDivPoints.sub(last6EthDivPoints[_addr]); return contributionsToken[_addr].mul(newEth6DivPoints).div(pointMultiplier); } function eth4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth4DivPoints = total4EthDivPoints.sub(last4EthDivPoints[_addr]); return contributionsEth[_addr].mul(newEth4DivPoints).div(pointMultiplier); } function tokenDivsOwing(address _addr) public view returns (uint) { return token4DivsOwing(_addr).add(token6DivsOwing(_addr)); } function token6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken6DivPoints = total6TokenDivPoints.sub(last6TokenDivPoints[_addr]); return contributionsToken[_addr].mul(newToken6DivPoints).div(pointMultiplier); } function token4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken4DivPoints = total4TokenDivPoints.sub(last4TokenDivPoints[_addr]); return contributionsEth[_addr].mul(newToken4DivPoints).div(pointMultiplier); } function updateAccount(address account) private { uint owingEth6 = eth6DivsOwing(account); uint owingEth4 = eth4DivsOwing(account); uint owingEth = owingEth4.add(owingEth6); uint owingToken6 = token6DivsOwing(account); uint owingToken4 = token4DivsOwing(account); uint owingToken = owingToken4.add(owingToken6); if (owingEth > 0) { // send ether dividends to account account.transfer(owingEth); } if (owingToken > 0) { // send token dividends to account tokenReward.transfer(account, owingToken); } last6EthDivPoints[account] = total6EthDivPoints; last4EthDivPoints[account] = total4EthDivPoints; last6TokenDivPoints[account] = total6TokenDivPoints; last4TokenDivPoints[account] = total4TokenDivPoints; emit DividendsTransferred(account, owingEth, owingToken); } function addToList(address sender) private { addedToList[sender] = true; // if the sender is not in the list if (indexes[sender] == 0) { _totalTokens = _totalTokens.add(contributionsToken[sender]); _totalWei = _totalWei.add(contributionsEth[sender]); // add the sender to the list lastIndex++; addresses[lastIndex] = sender; indexes[sender] = lastIndex; } } function removeFromList(address sender) private { addedToList[sender] = false; // if the sender is in temp eth list if (indexes[sender] > 0) { _totalTokens = _totalTokens.sub(contributionsToken[sender]); _totalWei = _totalWei.sub(contributionsEth[sender]); // remove the sender from temp eth list addresses[indexes[sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[sender]; indexes[sender] = 0; delete addresses[lastIndex]; lastIndex--; } } // desposit ether function () payable public { address sender = msg.sender; // size of code at target address uint codeLength; // get the length of code at the sender address assembly { codeLength := extcodesize(sender) } // don't allow contracts to deposit ether require(codeLength == 0); uint weiAmount = msg.value; updateAccount(sender); // number of ether sent must be greater than 0 require(weiAmount > 0); uint _89percent = weiAmount.mul(89).div(100); uint _6percent = weiAmount.mul(6).div(100); uint _4percent = weiAmount.mul(4).div(100); uint _1percent = weiAmount.mul(1).div(100); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); //1% goes to REX Investors owner.transfer(_1percent); contributionsEth[sender] = contributionsEth[sender].add(_89percent); // if the sender is in list if (indexes[sender]>0) { // increase _totalWei _totalWei = _totalWei.add(_89percent); } // if the sender has also deposited tokens, add sender to list if (contributionsToken[sender]>0) addToList(sender); } // withdraw ether function withdrawEth(uint amount) public { address sender = msg.sender; require(amount>0 && contributionsEth[sender] >= amount); updateAccount(sender); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsEth[sender] = contributionsEth[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total wei _totalWei = _totalWei.sub(amount); } // if the sender has withdrawn all their eth // remove the sender from list if (contributionsEth[sender] == 0) removeFromList(sender); sender.transfer(_89percent); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); owner.transfer(_1percent); //1% goes to REX Investors } // deposit tokens function depositTokens(address randomAddr, uint randomTicket) public { updateAccount(msg.sender); address sender = msg.sender; uint amount = tokenReward.allowance(sender, address(this)); // number of allowed tokens must be greater than 0 // if it is then transfer the allowed tokens from sender to the contract // if not transferred then throw require(amount>0 && tokenReward.transferFrom(sender, address(this), amount)); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); tokenReward.transfer(randomAddr, _1percent); // 1% for Airdrop emit AirDrop(randomAddr, _1percent, randomTicket); contributionsToken[sender] = contributionsToken[sender].add(_89percent); // if sender is in list if (indexes[sender]>0) { // increase totaltokens _totalTokens = _totalTokens.add(_89percent); } // if the sender has also contributed ether add sender to list if (contributionsEth[sender]>0) addToList(sender); } // withdraw tokens function withdrawTokens(uint amount, address randomAddr, uint randomTicket) public { address sender = msg.sender; updateAccount(sender); // requested amount must be greater than 0 and // the sender must have contributed tokens no less than `amount` require(amount>0 && contributionsToken[sender]>=amount); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsToken[sender] = contributionsToken[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total tokens _totalTokens = _totalTokens.sub(amount); } // if sender withdrawn all their tokens, remove them from list if (contributionsToken[sender] == 0) removeFromList(sender); tokenReward.transfer(sender, _89percent); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); // airdropToRandom(_1percent); tokenReward.transfer(randomAddr, _1percent); emit AirDrop(randomAddr, _1percent, randomTicket); } function distributeTokens(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei == 0 || totalTokens == 0) return; total4TokenDivPoints = total4TokenDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4TokenDivPoints = unclaimed4TokenDivPoints.add(_4percent); total6TokenDivPoints = total6TokenDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6TokenDivPoints = unclaimed6TokenDivPoints.add(_6percent); } function distributeEth(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei ==0 || totalTokens == 0) return; total4EthDivPoints = total4EthDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4EthDivPoints += _4percent; total6EthDivPoints = total6EthDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6EthDivPoints += _6percent; } // get sum of tokens contributed by the ether investors function getTotalTokens() public view returns (uint) { return _totalTokens; } // get the sum of wei contributed by the token investors function getTotalWei() public view returns (uint) { return _totalWei; } function withdrawDivs() public { updateAccount(msg.sender); } // get the list of investors function getList() public view returns (address[], uint[]) { address[] memory _addrs = new address[](lastIndex); uint[] memory _contributions = new uint[](lastIndex); for (uint i = 1; i <= lastIndex; i++) { _addrs[i-1] = addresses[i]; _contributions[i-1] = contributionsToken[addresses[i]]; } return (_addrs, _contributions); } }
if the sender is not in the list add the sender to the list
function addToList(address sender) private { addedToList[sender] = true; if (indexes[sender] == 0) { _totalTokens = _totalTokens.add(contributionsToken[sender]); _totalWei = _totalWei.add(contributionsEth[sender]); lastIndex++; addresses[lastIndex] = sender; indexes[sender] = lastIndex; } }
2,501,394
[ 1, 430, 326, 5793, 353, 486, 316, 326, 666, 527, 326, 5793, 358, 326, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 9604, 682, 12, 2867, 5793, 13, 3238, 288, 203, 565, 3096, 25772, 63, 15330, 65, 273, 638, 31, 203, 565, 309, 261, 11265, 63, 15330, 65, 422, 374, 13, 288, 203, 1377, 389, 4963, 5157, 273, 389, 4963, 5157, 18, 1289, 12, 591, 15326, 1345, 63, 15330, 19226, 203, 1377, 389, 4963, 3218, 77, 273, 389, 4963, 3218, 77, 18, 1289, 12, 591, 15326, 41, 451, 63, 15330, 19226, 203, 203, 1377, 7536, 9904, 31, 203, 1377, 6138, 63, 2722, 1016, 65, 273, 5793, 31, 203, 1377, 5596, 63, 15330, 65, 273, 7536, 31, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); 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 returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @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 increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor(uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns(uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, 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); _; } /** * @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() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, 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 increaseAllowance( address spender, uint addedValue ) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance( address spender, uint subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } // File: openzeppelin-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 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); 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 getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public; } // File: contracts/AdminRole.sol contract AdminRole { using Roles for Roles.Role; event AdminAdded(address indexed account); event AdminRemoved(address indexed account); Roles.Role private admins; modifier onlyAdmin() { require(isAdmin(msg.sender)); _; } function isAdmin(address account) public view returns (bool) { return admins.has(account); } function renounceAdmin() public { _removeAdmin(msg.sender); } function _addAdmin(address account) internal { admins.add(account); emit AdminAdded(account); } function _removeAdmin(address account) internal { admins.remove(account); emit AdminRemoved(account); } } // File: contracts/SpenderRole.sol contract SpenderRole { using Roles for Roles.Role; event SpenderAdded(address indexed account); event SpenderRemoved(address indexed account); Roles.Role private spenders; modifier onlySpender() { require(isSpender(msg.sender)); _; } function isSpender(address account) public view returns (bool) { return spenders.has(account); } function renounceSpender() public { _removeSpender(msg.sender); } function _addSpender(address account) internal { spenders.add(account); emit SpenderAdded(account); } function _removeSpender(address account) internal { spenders.remove(account); emit SpenderRemoved(account); } } // File: contracts/RecipientRole.sol contract RecipientRole { using Roles for Roles.Role; event RecipientAdded(address indexed account); event RecipientRemoved(address indexed account); Roles.Role private recipients; modifier onlyRecipient() { require(isRecipient(msg.sender)); _; } function isRecipient(address account) public view returns (bool) { return recipients.has(account); } function renounceRecipient() public { _removeRecipient(msg.sender); } function _addRecipient(address account) internal { recipients.add(account); emit RecipientAdded(account); } function _removeRecipient(address account) internal { recipients.remove(account); emit RecipientRemoved(account); } } // File: contracts/Fider.sol contract Fider is ERC20Detailed, ERC20Burnable, ERC20Capped, ERC20Pausable, AdminRole, SpenderRole, RecipientRole { using SafeERC20 for IERC20; address private root; modifier onlyRoot() { require(msg.sender == root, "This operation can only be performed by root account"); _; } constructor(string name, string symbol, uint8 decimals, uint256 cap) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) ERC20Mintable() ERC20() public { // Contract deployer (root) is automatically added as a minter in the MinterRole constructor // We revert this in here in order to separate the responsibilities of Root and Minter _removeMinter(msg.sender); // Contract deployer (root) is automatically added as a pauser in the PauserRole constructor // We revert this in here in order to separate the responsibilities of Root and Pauser _removePauser(msg.sender); root = msg.sender; } /*** ACCESS CONTROL MANAGEMENT ***/ /** * This is particularly for the cases where there is a chance that the keys are compromised * but no one has attacked/abused them yet, this function gives company the option to be on * the safe side and start using another address. * @dev Transfers control of the contract to a newRoot. * @param _newRoot The address to transfer ownership to. */ function transferRoot(address _newRoot) external onlyRoot { require(_newRoot != address(0)); root = _newRoot; } /** * Designates a given account as an authorized Minter, where minter are the only ones who * can call the mint function to create new tokens. * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will be able to mint */ function addMinter(address account) public onlyRoot { _addMinter(account); } /** * Revokes a given account as an authorized Minter, where minter are the only ones who * can call the mint function to create new tokens. * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will not be able to mint anymore */ function removeMinter(address account) external onlyRoot { _removeMinter(account); } /** * Designates a given account as an authorized Pauser, where pausers are the only ones who * can call the pause and unpause functions to freeze or unfreeze the transfer functions. * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will be able to pause/unpause the token */ function addPauser(address account) public onlyRoot { _addPauser(account); } /** * Revokes a given account as an authorized Pauser, where pausers are the only ones who * can call the pause and unpause functions to freeze or unfreeze the transfer functions. * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will not be able to pause/unpause the token anymore */ function removePauser(address account) external onlyRoot { _removePauser(account); } /** * Designates a given account as an authorized Admin, where admins are the only ones who * can call the addRecipient, removeRecipient, addSpender and removeSpender functions * to authorize or revoke spenders and recipients * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will be able to administer spenders and recipients */ function addAdmin(address account) external onlyRoot { _addAdmin(account); } /** * Revokes a given account as an authorized Admin, where admins are the only ones who * can call the addRecipient, removeRecipient, addSpender and removeSpender functions * to authorize or revoke spenders and recipients * This function can only be called by Root, which is the account who deployed the contract. * @param account address The account who will not be able to administer spenders and recipients anymore */ function removeAdmin(address account) external onlyRoot { _removeAdmin(account); } /** * Designates a given account as an authorized Spender, where spenders are the only ones who * can call the transfer, approve, increaseAllowance, decreaseAllowance and transferFrom functions * to send tokens to other accounts * This function can only be called by an authorized admin * @param account address The account who will be able to send tokens */ function addSpender(address account) external onlyAdmin { _addSpender(account); } /** * Revokes a given account as an authorized Spender, where spenders are the only ones who * can call the transfer, approve, increaseAllowance, decreaseAllowance and transferFrom functions * to send tokens to other accounts * This function can only be called by an authorized admin * @param account address The account who will not be able to send tokens anymore */ function removeSpender(address account) external onlyAdmin { _removeSpender(account); } /** * Designates a given account as an authorized Recipient, where recipients are the only ones who * can be on the receiving end of a transfer, either through a normal transfer, or through a third * party payment process (approve/transferFrom or increaseAllowance/transferFrom) * This function can only be called by an authorized admin * @param account address The account who will be able to receive tokens */ function addRecipient(address account) external onlyAdmin { _addRecipient(account); } /** * Revokes a given account as an authorized Recipient, where recipients are the only ones who * can be on the receiving end of a transfer, either through a normal transfer, or through a third * party payment process (approve/transferFrom or increaseAllowance/transferFrom) * This function can only be called by an authorized admin * @param account address The account who will not be able to receive tokens anymore */ function removeRecipient(address account) external onlyAdmin { _removeRecipient(account); } /*** MINTING ***/ /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. Must be an authorized spender. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { require(isSpender(to), "To must be an authorized spender"); return super.mint(to, value); } /*** BURNING ***/ /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * This function can only be called by an authorized minter. * @param from address The address which you want to burn tokens from * @param value uint256 The amount of tokens to be burned */ function burnFrom(address from, uint256 value) public onlyMinter { _burnFrom(from, value); } /*** TRANSFER ***/ /** * @dev Transfer token for a specified address * This function can only be called by an authorized spender. * @param to The address to transfer to. Must be an authorized recipient. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public onlySpender returns (bool) { require(isRecipient(to), "To must be an authorized recipient"); return super.transfer(to, value); } /** * @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 * This function can only be called by an authorized spender * @param spender The address which will spend the funds. Must be an authorized spender or minter. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public onlySpender returns (bool) { require(isSpender(spender) || isMinter(spender), "Spender must be an authorized spender or a minter"); return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * This function can only be called by an authorized spender. * @param from address The address which you want to send tokens from. Must be an authorized spender. * @param to address The address which you want to transfer to. Must be an authorized recipient. * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public onlySpender returns (bool) { require(isSpender(from), "From must be an authorized spender"); require(isRecipient(to), "To must be an authorized recipient"); return super.transferFrom(from, to, value); } /** * @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 * This function can only be called by an authorized spender. * @param spender The address which will spend the funds. Must be an authorized spender or minter. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public onlySpender returns (bool) { require(isSpender(spender) || isMinter(spender), "Spender must be an authorized spender or a minter"); return super.increaseAllowance(spender, addedValue); } /** * @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 * This function can only be called by an authorized spender. * @param spender The address which will spend the funds. Must be an authorized spender or minter. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public onlySpender returns (bool) { require(isSpender(spender) || isMinter(spender), "Spender must be an authorized spender or a minter"); return super.decreaseAllowance(spender, subtractedValue); } /** RECOVERING ASSETS MISTAKENLY SENT TO CONTRACT **/ /** * @dev Disallows direct send by setting a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the root. */ function reclaimEther() external onlyRoot { root.transfer(address(this).balance); } /** * @dev Reclaim all IERC20 compatible tokens * @param _token IERC20 The address of the token contract */ function reclaimERC20Token(IERC20 _token) external onlyRoot { uint256 balance = _token.balanceOf(this); _token.safeTransfer(root, balance); } }
* @dev Reclaim all IERC20 compatible tokens @param _token IERC20 The address of the token contract/
function reclaimERC20Token(IERC20 _token) external onlyRoot { uint256 balance = _token.balanceOf(this); _token.safeTransfer(root, balance); }
12,780,369
[ 1, 426, 14784, 777, 467, 654, 39, 3462, 7318, 2430, 225, 389, 2316, 467, 654, 39, 3462, 1021, 1758, 434, 326, 1147, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 14784, 654, 39, 3462, 1345, 12, 45, 654, 39, 3462, 389, 2316, 13, 3903, 1338, 2375, 288, 203, 3639, 2254, 5034, 11013, 273, 389, 2316, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 389, 2316, 18, 4626, 5912, 12, 3085, 16, 11013, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21<0.6.0; // --------------------------------------------- // CryptoVote.sol // --------------------------------------------- // Copyright (c) 2018 PLUSPLUS CO.,LTD. // Released under the MIT license // https://www.plusplus.jp/ // --------------------------------------------- contract CryptoVote { // 投票キャンペーン struct Campaign { //キャンペーンハッシュID(内部生成) bytes32 campaignId; // Campaignの情報のJSON文字列 string campaignData; // 選択肢の数 uint optionNumber; // 投票開始タイムスタンプ // Voting start timestamp uint voteStartAt; //投票終了タイムスタンプ // Voting end timestamp uint voteEndAt; // 投票者リストを保持する mapping(bytes32 => bool) voters; // 投票済みリストを保持する mapping(bytes32 => bool) votedList; // campaign登録者 address campaignOwner; // campaign登録日時 uint createdAt; bool isExist; } // Owner of Smart Contract // スマートコントラクトのオーナー address public owner; // Keep a list of hashes // ハッシュの一覧を保持する mapping(bytes32 => Campaign) public CampaignList; // 投票結果を保持する mapping(bytes32 => uint[]) private RecordList; // *********************************** // スマートコントラクトのオーナーであること // *********************************** modifier onlyOwner() { require(msg.sender == owner, "Only the owner is available."); _; } // *********************************** // 投票キャンペーンのオーナーであること // *********************************** modifier onlyCampaignOwner(bytes32 _campaignId) { require(isExist(_campaignId) == true, NO_DATA); require(msg.sender == CampaignList[_campaignId].campaignOwner, "Only the owner is available."); _; } // *********************************** // 投票受付中であること // *********************************** modifier acceptingPolling(bytes32 _campaignId) { require(isExist(_campaignId) == true, NO_DATA); uint ts = block.timestamp; require(CampaignList[_campaignId].voteStartAt <= ts && ts <= CampaignList[_campaignId].voteEndAt, "Outside the voting period"); _; } // *********************************** // 投票開始前であること // *********************************** modifier beforeVoteStart(bytes32 _campaignId) { require(isExist(_campaignId) == true, NO_DATA); uint ts = block.timestamp; require(ts < CampaignList[_campaignId].voteStartAt); _; } // *********************************** // 投票終了前であること // *********************************** modifier beforeVoteEnd(bytes32 _campaignId) { require(isExist(_campaignId) == true, NO_DATA); uint ts = block.timestamp; require(ts < CampaignList[_campaignId].voteEndAt); _; } // *********************************** // 投票締め切り後であること // *********************************** modifier afterVoteEnd(bytes32 _campaignId) { require(isExist(_campaignId) == true, NO_DATA); uint ts = block.timestamp; require(CampaignList[_campaignId].voteEndAt <= ts); _; } string private NO_DATA = "Data does not exist"; string private ALREADY_REGISTERED = "It is already registered"; string private NO_DELETE_AUTHORITY = "You do not have permission to delete"; // Events // *********************************** // キャンペーン作成 // *********************************** event NewCampaign(address indexed _from, bytes32 _campaignId, string _campaignData, uint _voteStartAt, uint _voteEndAt); // *********************************** // キャンペーン削除 // *********************************** event DeletedCampaign(address indexed _from, bytes32 _campaignId); // *********************************** // 投票 // *********************************** event Vote(address indexed _from, bytes32 _campaignId, bytes32 _voterId, uint _optionNumber, uint _timestamp); // *********************************** // 投票者追加 // *********************************** event AddVoter(address indexed _from, bytes32 _campaignId, uint256 _newVoters); // *********************************** // コンストラクタ // *********************************** constructor() public { // The owner address is maintained. owner = msg.sender; } // *********************************** // Obtain a hash value // ハッシュ値を得る // *********************************** function getKeccak256Hash(string _sha3hash) public pure returns (bytes32) { bytes32 keccak256hash = keccak256(abi.encodePacked(_sha3hash)); return keccak256hash; } // *********************************** // campaign existence check // キャンペーン存在チェック // *********************************** function isExist(bytes32 _campaignId) public view returns (bool) { if (CampaignList[_campaignId].isExist == true) { // exist return true; } else { // not exist return false; } } // *********************************** // Whether you are the owner of the campaign // あなたがキャンペーンの登録者であるか // *********************************** function areYouCampaignOwner(bytes32 _campaignId) public view returns (bool) { require(isExist(_campaignId) == true, NO_DATA); if (msg.sender == CampaignList[_campaignId].campaignOwner) { return true; } else { return false; } } // *********************************** // campaign作成 // *********************************** function createCampaign(string _campaignData, uint _optionNumber, uint _voteStartAt, uint _voteEndAt) public returns (bool) { uint ts = block.timestamp; // voteStartAtが未来日であること require(ts < _voteStartAt); // voteStartAt < voteEndAt であること require(_voteStartAt < _voteEndAt); // voteEndAt - voteStartAt が1分以上あること require(_voteEndAt - _voteStartAt >= 1 minutes); bytes32 _campaignId = getKeccak256Hash(_campaignData); // 同じものが存在しないこと require(isExist(_campaignId) == false); CampaignList[_campaignId].isExist = true; CampaignList[_campaignId].campaignId = _campaignId; CampaignList[_campaignId].campaignData = _campaignData; CampaignList[_campaignId].optionNumber = _optionNumber; CampaignList[_campaignId].voteStartAt = _voteStartAt; CampaignList[_campaignId].voteEndAt = _voteEndAt; CampaignList[_campaignId].campaignOwner = msg.sender; CampaignList[_campaignId].createdAt = ts; // 投票結果の初期化 RecordList[_campaignId].length = _optionNumber; // 通知 emit NewCampaign(msg.sender, _campaignId, _campaignData, _voteStartAt, _voteEndAt); return true; } // *********************************** // campaign削除 // *********************************** function deleteCampaign(bytes32 _campaignId) public onlyOwner returns (bool) { CampaignList[_campaignId].isExist = false; CampaignList[_campaignId].campaignData = ""; CampaignList[_campaignId].voteStartAt = 0; CampaignList[_campaignId].voteEndAt = 0; CampaignList[_campaignId].createdAt = 0; // 通知 emit DeletedCampaign(msg.sender, _campaignId); return true; } // *********************************** // 投票者IDが存在するか // *********************************** function existVoterId(bytes32 _campaignId, bytes32 _voterHash) public view returns (bool) { return CampaignList[_campaignId].voters[_voterHash]; } // *********************************** // 投票済みか // *********************************** function isVoted(bytes32 _campaignId, bytes32 _voterHash) public view returns (bool) { return CampaignList[_campaignId].votedList[_voterHash]; } // *********************************** // 投票者の追加 // ----------------------------------- // 【条件】 // キャンペーンのオーナーであること // 投票期限前であること // *********************************** function addVoter(bytes32 _campaignId, bytes32[] _voterHashList) public onlyCampaignOwner(_campaignId) beforeVoteEnd(_campaignId) returns (bool) { require(_voterHashList.length <= 100); uint256 newVoters = 0; for (uint i = 0; i < _voterHashList.length; ++i) { if (existVoterId(_campaignId, _voterHashList[i])) { continue; } CampaignList[_campaignId].voters[_voterHashList[i]] = true; ++newVoters; } emit AddVoter(msg.sender, _campaignId, newVoters); return true; } // *********************************** // 投票 // ----------------------------------- // 【条件】 // 投票期間中であること // *********************************** function vote(bytes32 _campaignId, bytes32 _voterHash, uint _optionNumber) public acceptingPolling(_campaignId) returns (bool) { // 投票権があること require(existVoterId(_campaignId, _voterHash) == true, "投票権がありません"); // 未投票であること require(isVoted(_campaignId, _voterHash) == false, "投票済みです"); uint ts = block.timestamp; // 投票済みに変更 CampaignList[_campaignId].votedList[_voterHash] = true; // 一票加算 RecordList[_campaignId][_optionNumber]++; emit Vote(msg.sender, _campaignId, _voterHash, _optionNumber, ts); return true; } // *********************************** // 投票結果参照 // ----------------------------------- // 【条件】 // なし // *********************************** function getResult(bytes32 _campaignId) public view returns (uint[]) { require(isExist(_campaignId) == true); return RecordList[_campaignId]; } // --------------------------------------------- // Destruction of a contract (only owner) // --------------------------------------------- function destory(string _delete_me) public onlyOwner { // Delete by giving keyword require(getKeccak256Hash("delete me") == getKeccak256Hash(_delete_me), "The keywords do not match."); selfdestruct(owner); } }
*********************************** 投票結果参照 ----------------------------------- 【条件】 なし ***********************************
function getResult(bytes32 _campaignId) public view returns (uint[]) { require(isExist(_campaignId) == true); return RecordList[_campaignId]; }
12,642,130
[ 1, 167, 237, 248, 168, 103, 106, 168, 118, 243, 167, 257, 255, 166, 242, 229, 168, 232, 105, 19134, 413, 225, 164, 227, 243, 167, 256, 99, 165, 124, 119, 164, 227, 244, 225, 164, 228, 108, 164, 228, 250, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8601, 12, 3890, 1578, 389, 14608, 548, 13, 1071, 1476, 1135, 261, 11890, 63, 5717, 288, 203, 3639, 2583, 12, 291, 4786, 24899, 14608, 548, 13, 422, 638, 1769, 203, 3639, 327, 5059, 682, 63, 67, 14608, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; 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) { uint256 c = a / b; 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; } } interface ERC20 { function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool); function mint (address _to, uint256 _amount) external returns (bool); } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract Crowdsale is Ownable { using SafeMath for uint256; modifier onlyWhileOpen { require( (now >= preICOStartDate && now < preICOEndDate) || (now >= ICOStartDate && now < ICOEndDate) ); _; } modifier onlyWhileICOOpen { require(now >= ICOStartDate && now < ICOEndDate); _; } // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Адрес оператора бекЭнда для управления вайтлистом address public backendOperator = 0xd2420C5fDdA15B26AC3E13522e5cCD62CEB50e5F; // Сколько токенов покупатель получает за 1 эфир uint256 public rate = 100; // Сколько эфиров привлечено в ходе PreICO, wei uint256 public preICOWeiRaised = 1850570000000000000000; // Сколько эфиров привлечено в ходе ICO, wei uint256 public ICOWeiRaised; // Цена ETH в центах uint256 public ETHUSD; // Дата начала PreICO uint256 public preICOStartDate; // Дата окончания PreICO uint256 public preICOEndDate; // Дата начала ICO uint256 public ICOStartDate; // Дата окончания ICO uint256 public ICOEndDate; // Минимальный объем привлечения средств в ходе ICO в центах uint256 public softcap = 300000000; // Потолок привлечения средств в ходе ICO в центах uint256 public hardcap = 2500000000; // Бонус реферала, % uint8 public referalBonus = 3; // Бонус приглашенного рефералом, % uint8 public invitedByReferalBonus = 2; // Whitelist mapping(address => bool) public whitelist; // Инвесторы, которые купили токен mapping (address => uint256) public investors; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); function Crowdsale( address _wallet, uint256 _preICOStartDate, uint256 _preICOEndDate, uint256 _ICOStartDate, uint256 _ICOEndDate, uint256 _ETHUSD ) public { require(_preICOEndDate > _preICOStartDate); require(_ICOStartDate > _preICOEndDate); require(_ICOEndDate > _ICOStartDate); wallet = _wallet; preICOStartDate = _preICOStartDate; preICOEndDate = _preICOEndDate; ICOStartDate = _ICOStartDate; ICOEndDate = _ICOEndDate; ETHUSD = _ETHUSD; } modifier backEnd() { require(msg.sender == backendOperator || msg.sender == owner); _; } /* Публичные методы */ // Установить стоимость токена function setRate (uint16 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } // Установить адрес кошелька для сбора средств function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; } // Установить торгуемый токен function setToken (ERC20 _token) public onlyOwner { token = _token; } // Установить дату начала PreICO function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner { require(_preICOStartDate < preICOEndDate); preICOStartDate = _preICOStartDate; } // Установить дату окончания PreICO function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner { require(_preICOEndDate > preICOStartDate); preICOEndDate = _preICOEndDate; } // Установить дату начала ICO function setICOStartDate (uint256 _ICOStartDate) public onlyOwner { require(_ICOStartDate < ICOEndDate); ICOStartDate = _ICOStartDate; } // Установить дату окончания PreICO function setICOEndDate (uint256 _ICOEndDate) public onlyOwner { require(_ICOEndDate > ICOStartDate); ICOEndDate = _ICOEndDate; } // Установить стоимость эфира в центах function setETHUSD (uint256 _ETHUSD) public onlyOwner { ETHUSD = _ETHUSD; } // Установить оператора БекЭнда для управления вайтлистом function setBackendOperator(address newOperator) public onlyOwner { backendOperator = newOperator; } function () external payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; uint256 tokens; if(_isPreICO()){ _preValidatePreICOPurchase(beneficiary, weiAmount); tokens = weiAmount.mul(rate.add(rate.mul(30).div(100))); preICOWeiRaised = preICOWeiRaised.add(weiAmount); wallet.transfer(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } else if(_isICO()){ _preValidateICOPurchase(beneficiary, weiAmount); tokens = _getTokenAmountWithBonus(weiAmount); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } } // Покупка токенов с реферальным бонусом function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; _preValidateICOPurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2)); uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); _deliverTokens(_referal, referalTokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } // Добавить адрес в whitelist function addToWhitelist(address _beneficiary) public backEnd { whitelist[_beneficiary] = true; } // Добавить несколько адресов в whitelist function addManyToWhitelist(address[] _beneficiaries) public backEnd { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } // Исключить адрес из whitelist function removeFromWhitelist(address _beneficiary) public backEnd { whitelist[_beneficiary] = false; } // Узнать истек ли срок проведения PreICO function hasPreICOClosed() public view returns (bool) { return now > preICOEndDate; } // Узнать истек ли срок проведения ICO function hasICOClosed() public view returns (bool) { return now > ICOEndDate; } // Перевести собранные средства на кошелек для сбора function forwardFunds () public onlyOwner { require(now > ICOEndDate); require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap); wallet.transfer(ICOWeiRaised); } // Вернуть проинвестированные средства, если не был достигнут softcap function refund() public { require(now > ICOEndDate); require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap); require(investors[msg.sender] > 0); address investor = msg.sender; investor.transfer(investors[investor]); } /* Внутренние методы */ // Проверка актуальности PreICO function _isPreICO() internal view returns(bool) { return now >= preICOStartDate && now < preICOEndDate; } // Проверка актуальности ICO function _isICO() internal view returns(bool) { return now >= ICOStartDate && now < ICOEndDate; } // Валидация перед покупкой токенов function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require(now >= preICOStartDate && now <= preICOEndDate); } function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap); require(now >= ICOStartDate && now <= ICOEndDate); } // Подсчет бонусов с учетом бонусов за этап ICO и объем инвестиций function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256) { uint256 baseTokenAmount = _weiAmount.mul(rate); uint256 tokenAmount = baseTokenAmount; uint256 usdAmount = _weiAmount.mul(ETHUSD).div(10**18); // Считаем бонусы за объем инвестиций if(usdAmount >= 10000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(7).div(100)); } else if(usdAmount >= 5000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } else if(usdAmount >= 1000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(3).div(100)); } // Считаем бонусы за этап ICO if(now < ICOStartDate + 30 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(20).div(100)); } else if(now < ICOStartDate + 60 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(15).div(100)); } else if(now < ICOStartDate + 90 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(10).div(100)); } else { tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } return tokenAmount; } // Подсчет бонусов с учетом бонусов реферальной системы function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) { return _weiAmount.mul(rate).mul(_percent).div(100); } // Перевод токенов function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } }
Установить торгуемый токен
function setToken (ERC20 _token) public onlyOwner { token = _token; }
10,577,123
[ 1, 145, 101, 146, 228, 146, 229, 145, 113, 145, 126, 145, 127, 145, 115, 145, 121, 146, 229, 146, 239, 225, 146, 229, 145, 127, 146, 227, 145, 116, 146, 230, 145, 118, 145, 125, 146, 238, 145, 122, 225, 146, 229, 145, 127, 145, 123, 145, 118, 145, 126, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22629, 261, 654, 39, 3462, 389, 2316, 13, 1071, 1338, 5541, 288, 203, 3639, 1147, 273, 389, 2316, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xC428d51F3FA9DB2E6F9a7c57af3456e53512251b/sources/browser/GlacierProtocol.sol
* @dev Send token holding bonus to account/
function _sendBonus(address account) internal { if (account == address(0) || account == address(this) || isContract(account)) { return; } User storage u = _users[account]; if (!u.holdFlag) { return; uint256 tNow = now; uint256 bal = _balances[account]; if (bal >= MinHoldToReward) { uint256 bonus = bal.mul(tNow.sub(uint256(u.lastRewardTime))).mul(5).div(1000*24*3600); if (bonus > 0) { _mint(account, min(bonus, _maxSupply.sub(_totalSupply))); } } u.lastRewardTime = uint128(tNow); } }
670,008
[ 1, 3826, 1147, 19918, 324, 22889, 358, 2236, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4661, 38, 22889, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 309, 261, 4631, 422, 1758, 12, 20, 13, 747, 2236, 422, 1758, 12, 2211, 13, 747, 353, 8924, 12, 4631, 3719, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2177, 2502, 582, 273, 389, 5577, 63, 4631, 15533, 203, 3639, 309, 16051, 89, 18, 21056, 4678, 13, 288, 203, 5411, 327, 31, 203, 5411, 2254, 5034, 268, 8674, 273, 2037, 31, 203, 5411, 2254, 5034, 324, 287, 273, 389, 70, 26488, 63, 4631, 15533, 203, 5411, 309, 261, 70, 287, 1545, 5444, 20586, 774, 17631, 1060, 13, 288, 203, 7734, 2254, 5034, 324, 22889, 273, 324, 287, 18, 16411, 12, 88, 8674, 18, 1717, 12, 11890, 5034, 12, 89, 18, 2722, 17631, 1060, 950, 3719, 2934, 16411, 12, 25, 2934, 2892, 12, 18088, 14, 3247, 14, 5718, 713, 1769, 203, 7734, 309, 261, 18688, 407, 405, 374, 13, 288, 203, 10792, 389, 81, 474, 12, 4631, 16, 1131, 12, 18688, 407, 16, 389, 1896, 3088, 1283, 18, 1717, 24899, 4963, 3088, 1283, 3719, 1769, 203, 7734, 289, 203, 5411, 289, 203, 5411, 582, 18, 2722, 17631, 1060, 950, 273, 2254, 10392, 12, 88, 8674, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * Overflow aware uint math functions. * * Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol */ contract SafeMath { //internals function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } } /** * ERC 20 token * * https://github.com/ethereum/EIPs/issues/20 */ contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer 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 amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * ERC 20 token * * https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is Token { /** * Reviewed: * - Interger overflow = OK, checked */ function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } /** * Automobile Cyberchain Token crowdsale ICO contract. * */ contract AutomobileCyberchainToken is StandardToken, SafeMath { string public name = "Automobile Cyberchain Token"; string public symbol = "AMCC"; uint public decimals = 18; uint preSalePrice = 32000; uint crowSalePrice = 20000; uint prePeriod = 256 * 24 * 30;// unit: block count, estimate: 30 days, May 16 0:00, UTC-7 uint totalPeriod = 256 * 24 * 95; // unit: block count, estimate: 95 days, July 20, 0:00, UTC-7 uint public startBlock = 5455280; //crowdsale start block (set in constructor), April 16 0:00 UTC-7 uint public endBlock = startBlock + totalPeriod; //crowdsale end block // Initial founder address (set in constructor) // All deposited ETH will be instantly forwarded to this address. // Address is a multisig wallet. address public founder = 0xfD16CDC79382F86303E2eE8693C7f50A4d8b937F; uint256 public preEtherCap = 15625 * 10**18; // max amount raised during pre-ICO uint256 public etherCap = 88125 * 10**18; //max amount raised during crowdsale uint256 public bountyAllocation = 1050000000 * 10**18; uint256 public maxToken = 3000000000 * 10**18; // uint public transferLockup = 256 * 0; //transfers are locked for this many blocks after endBlock (assuming 14 second blocks) // uint public founderLockup = 256 * 0; //founder allocation cannot be created until this many blocks after endBlock uint256 public presaleTokenSupply = 0; //this will keep track of the token supply created during the pre-crowdsale uint256 public totalEtherRaised = 0; bool public halted = false; //the founder address can set this to true to halt the crowdsale due to emergency event Buy(address indexed sender, uint eth, uint fbt); function AutomobileCyberchainToken() { balances[founder] = bountyAllocation; totalSupply = bountyAllocation; Transfer(address(0), founder, bountyAllocation); } function price() constant returns(uint) { if (block.number<startBlock || block.number > endBlock) return 0; //this will not happen according to the buyToken block check, but still set it to 0. else if (block.number>=startBlock && block.number<startBlock+prePeriod) return preSalePrice; //pre-ICO else return crowSalePrice; // default-ICO } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function() public payable { buyToken(msg.sender, msg.value); } // Buy entry point function buy(address recipient, uint256 value) public payable { if (value> msg.value) throw; if (value < msg.value) { require(msg.sender.call.value(msg.value - value)()); //refund the extra ether } buyToken(recipient, value); } function buyToken(address recipient, uint256 value) internal { if (block.number<startBlock || block.number>endBlock || safeAdd(totalEtherRaised,value)>etherCap || halted) throw; if (block.number>=startBlock && block.number<=startBlock+prePeriod && safeAdd(totalEtherRaised,value) > preEtherCap) throw; //preSale Cap limitation uint tokens = safeMul(value, price()); balances[recipient] = safeAdd(balances[recipient], tokens); totalSupply = safeAdd(totalSupply, tokens); totalEtherRaised = safeAdd(totalEtherRaised, value); if (block.number<=startBlock+prePeriod) { presaleTokenSupply = safeAdd(presaleTokenSupply, tokens); } Transfer(address(0), recipient, tokens); //Transaction record for token perchaise if (!founder.call.value(value)()) throw; //immediately send Ether to founder address Buy(recipient, value, tokens); //Buy event } /** * Emergency Stop ICO. * * Applicable tests: * * - Test unhalting, buying, and succeeding */ function halt() { if (msg.sender!=founder) throw; halted = true; } function unhalt() { if (msg.sender!=founder) throw; halted = false; } /** * Change founder address (where ICO ETH is being forwarded). * * Applicable tests: * * - Test founder change by hacker * - Test founder change * - Test founder token allocation twice * */ function changeFounder(address newFounder) { if (msg.sender!=founder) throw; founder = newFounder; } function withdrawExtraToken(address recipient) public { require(msg.sender == founder && block.number > endBlock && totalSupply < maxToken); uint256 leftTokens = safeSub(maxToken, totalSupply); balances[recipient] = safeAdd(balances[recipient], leftTokens); totalSupply = maxToken; Transfer(address(0), recipient, leftTokens); } /** * ERC 20 Standard Token interface transfer function * * Prevent transfers until freeze period is over. * * Applicable tests: * * - Test restricted early transfer * - Test transfer after restricted period */ // function transfer(address _to, uint256 _value) returns (bool success) { // if (block.number <= startBlock + transferLockup && msg.sender!=founder) throw; // return super.transfer(_to, _value); // } /** * ERC 20 Standard Token interface transfer function * * Prevent transfers until freeze period is over. */ // function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { // if (block.number <= startBlock + transferLockup && msg.sender!=founder) throw; // return super.transferFrom(_from, _to, _value); // } }
unit: block count, estimate: 95 days, July 20, 0:00, UTC-7
uint totalPeriod = 256 * 24 * 95;
2,484,428
[ 1, 4873, 30, 1203, 1056, 16, 11108, 30, 16848, 4681, 16, 804, 332, 93, 4200, 16, 374, 30, 713, 16, 9951, 17, 27, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 2078, 5027, 273, 8303, 380, 4248, 380, 16848, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x54253de6f4119b99FB507bE99d87EF5C94c343E6/sources/localhost/contracts/FLReceiver.sol
address private constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
IERC20 private constant enterToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
9,746,162
[ 1, 2867, 3238, 5381, 463, 18194, 67, 15140, 273, 374, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 654, 39, 3462, 3238, 5381, 6103, 1345, 273, 467, 654, 39, 3462, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6c51041A91C91C86f3F08a72cB4D3F67f1208897/sources/src/base/Cellar.sol
* @notice Simulate the effects of redeeming shares at the current block, given current on-chain conditions. @param shares amount of shares to redeem @return assets that will be returned/
function previewRedeem(uint256 shares) public view override returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); assets = _convertToAssets(shares, _totalAssets, _totalSupply); }
5,008,865
[ 1, 7993, 6243, 326, 16605, 434, 283, 24903, 310, 24123, 622, 326, 783, 1203, 16, 864, 783, 603, 17, 5639, 4636, 18, 225, 24123, 3844, 434, 24123, 358, 283, 24903, 327, 7176, 716, 903, 506, 2106, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10143, 426, 24903, 12, 11890, 5034, 24123, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 7176, 13, 288, 203, 3639, 261, 11890, 5034, 389, 4963, 10726, 16, 2254, 5034, 389, 4963, 3088, 1283, 13, 273, 389, 588, 5269, 10726, 1876, 5269, 3088, 1283, 12, 5743, 1769, 203, 3639, 7176, 273, 389, 6283, 774, 10726, 12, 30720, 16, 389, 4963, 10726, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xEA541B886E3Dd7c3557ecFA23845Cc8644efC250/sources/JOKE.sol
* @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), "JOKE: approve from the zero address"); require(spender != address(0), "JOKE: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
8,220,710
[ 1, 2785, 1375, 8949, 68, 487, 326, 1699, 1359, 434, 1375, 87, 1302, 264, 68, 1879, 326, 1375, 8443, 68, 272, 2430, 18, 1220, 2713, 445, 353, 7680, 358, 1375, 12908, 537, 9191, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 444, 5859, 1699, 6872, 364, 8626, 15359, 87, 16, 5527, 18, 7377, 1282, 392, 288, 23461, 97, 871, 18, 29076, 30, 300, 1375, 8443, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 12908, 537, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 46, 3141, 41, 30, 6617, 537, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 3631, 315, 46, 3141, 41, 30, 6617, 537, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 8443, 16, 17571, 264, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // File: contracts/Owned.sol // ---------------------------------------------------------------------------- // Ownership functionality for authorization controls and user permissions // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/Pausable.sol // ---------------------------------------------------------------------------- // Pause functionality // ---------------------------------------------------------------------------- contract Pausable is Owned { event Pause(); event Unpause(); bool public paused = false; // Modifier to make a function callable only when the contract is not paused. modifier whenNotPaused() { require(!paused); _; } // Modifier to make a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } // Called by the owner to pause, triggers stopped state function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } // Called by the owner to unpause, returns to normal state function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/SafeMath.sol // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // File: contracts/ERC20.sol // ---------------------------------------------------------------------------- // ERC20 Standard Interface // ---------------------------------------------------------------------------- contract ERC20 { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // File: contracts/UncToken.sol // ---------------------------------------------------------------------------- // 'UNC' 'Uncloak' token contract // Symbol : UNC // Name : Uncloak // Total supply: 4,200,000,000 // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // Receives ETH and generates tokens // ---------------------------------------------------------------------------- contract UncToken is SafeMath, Owned, ERC20 { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; // Track whether the coin can be transfered bool private transferEnabled = false; // track addresses that can transfer regardless of whether transfers are enables mapping(address => bool) public transferAdmins; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) internal allowed; event Burned(address indexed burner, uint256 value); // Check if transfer is valid modifier canTransfer(address _sender) { require(transferEnabled || transferAdmins[_sender]); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "UNC"; name = "Uncloak"; decimals = 18; _totalSupply = 4200000000 * 10**uint(decimals); transferAdmins[owner] = true; // Enable transfers for owner balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) canTransfer (msg.sender) public returns (bool success) { require(to != address(this)); //make sure we're not transfering to this contract //check edge cases if (balances[msg.sender] >= tokens && tokens > 0) { //update balances balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(msg.sender, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { // Ownly allow changes to or from 0. Mitigates vulnerabiilty of race description // described here: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((tokens == 0) || (allowed[msg.sender][spender] == 0)); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) canTransfer(from) public returns (bool success) { require(to != address(this)); //check edge cases if (allowed[from][msg.sender] >= tokens && balances[from] >= tokens && tokens > 0) { //update balances and allowances balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(from, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // Owner can allow transfers for a particular address. Use for crowdsale contract. function setTransferAdmin(address _addr, bool _canTransfer) onlyOwner public { transferAdmins[_addr] = _canTransfer; } // Enable transfers for token holders function enablesTransfers() public onlyOwner { transferEnabled = true; } // ------------------------------------------------------------------------ // Burns a specific number of tokens // ------------------------------------------------------------------------ function burn(uint256 _value) public onlyOwner { require(_value > 0); address burner = msg.sender; balances[burner] = safeSub(balances[burner], _value); _totalSupply = safeSub(_totalSupply, _value); emit Burned(burner, _value); } // ------------------------------------------------------------------------ // Doesn't Accept Eth // ------------------------------------------------------------------------ function () public payable { revert(); } } // File: contracts/TimeLock.sol // ---------------------------------------------------------------------------- // The timeLock contract is used for locking up the tokens of early backers. // It distributes 40% at launch, 40% 3 months later, 20% 6 months later. // ---------------------------------------------------------------------------- contract TimeLock is SafeMath, Owned { // Token we are using UncToken public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime1; uint256 public releaseTime2; uint256 public releaseTime3; // track initial balance of time lock uint256 public initialBalance; // Keep track of step of distribution uint public step = 0; // constructor constructor(UncToken _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime1 = _releaseTime; releaseTime2 = safeAdd(releaseTime1, 7776000); // Add 3 months releaseTime3 = safeAdd(releaseTime1, 15552000); // Add 6 months } // Sets the initial balance, used because timelock distribution based on % of initial balance function setInitialBalance() public onlyOwner { initialBalance = token.balanceOf(address(this)); } // Function to move release time frame earlier if needed function updateReleaseTime(uint256 _releaseTime) public onlyOwner { // Check that release schedule has not started require(now < releaseTime1); require(_releaseTime < releaseTime1); // Update times releaseTime1 = _releaseTime; releaseTime2 = safeAdd(releaseTime1, 7776000); // Add 3 months releaseTime3 = safeAdd(releaseTime1, 15552000); // Add 6 months } // Transfers tokens held by timelock to beneficiary. function release() public { require(now >= releaseTime1); uint256 unlockAmount = 0; // Initial balance of tokens in this contract uint256 amount = initialBalance; require(amount > 0); // Determine release amount if (step == 0 && now > releaseTime1) { unlockAmount = safeDiv(safeMul(amount, 4), 10); //40% } else if (step == 1 && now > releaseTime2) { unlockAmount = safeDiv(safeMul(amount, 4), 10); //40% } else if (step == 2 && now > releaseTime3) { unlockAmount = token.balanceOf(address(this)); } // Make sure there is new tokens to release, otherwise don't advance step require(unlockAmount != 0); // Increase step for next time require(token.transfer(beneficiary, unlockAmount)); step++; } } // File: contracts/UncTokenSale.sol // ---------------------------------------------------------------------------- // The UncTokenSale smart contract is used for selling UncToken (UNC). // It calculates UNC allocation based on the ETH contributed and the sale stage. // ---------------------------------------------------------------------------- contract UncTokenSale is SafeMath, Pausable { // The beneficiary is the address that receives the ETH raised if sale is successful address public beneficiary; // Token to be sold UncToken public token; // Crowdsale variables set in constructor uint public hardCap; uint public highBonusRate = 115; uint public lowBonusRate = 110; uint public constant highBonus = 160000000000000000000; // 160 Eth uint public constant minContribution = 4000000000000000000; // 4 Eth uint public constant preMaxContribution = 200000000000000000000; // 200 Eth uint public constant mainMaxContribution = 200000000000000000000; // 200 Eth // List of addresses that can add KYC verified addresses mapping(address => bool) public isVerifier; // List of addresses that are kycVerified mapping(address => bool) public kycVerified; // Time periods of sale stages uint public preSaleTime; uint public mainSaleTime; uint public endSaleTime; // Keeps track of amount raised uint public amountRaised; // Booleans to track sale state bool public beforeSale = true; bool public preSale = false; bool public mainSale = false; bool public saleEnded = false; bool public hardCapReached = false; // Mapping of token timelocks mapping(address => address) public timeLocks; // Ratio of Wei to UNC. LOW HIGH NEED TO BE UPDATED uint public rate = 45000; // $0.01 per UNC uint public constant lowRate = 10000; uint public constant highRate = 1000000; // Mapping to track contributions mapping(address => uint256) public contributionAmtOf; // The tokens allocated to an address mapping(address => uint256) public tokenBalanceOf; // A mapping that tracks the tokens allocated to team and advisors mapping(address => uint256) public teamTokenBalanceOf; event HardReached(address _beneficiary, uint _amountRaised); event BalanceTransfer(address _to, uint _amount); event AddedOffChain(address indexed _beneficiary, uint256 tokensAllocated); event RateChanged(uint newRate); event VerifiedKYC(address indexed person); //other potential events: transfer of tokens to investors, modifier beforeEnd() { require (now < endSaleTime); _; } modifier afterEnd() { require (now >= endSaleTime); _; } modifier afterStart() { require (now >= preSaleTime); _; } modifier saleActive() { require (!(beforeSale || saleEnded)); _; } modifier verifierOnly() { require(isVerifier[msg.sender]); _; } // Constructor, lay out the structure of the sale constructor ( UncToken _token, address _beneficiary, uint _preSaleTime, uint _mainSaleTime, uint _endSaleTime, uint _hardCap ) public { //require(_beneficiary != address(0) && _beneficiary != address(this)); //require(_endSaleTime > _mainSaleTime && _mainSaleTime > _preSaleTime); // This sets the contract owner as a verifier, then they can add other verifiers isVerifier[msg.sender] = true; token = _token; beneficiary = _beneficiary; preSaleTime = _preSaleTime; mainSaleTime = _mainSaleTime; endSaleTime = _endSaleTime; hardCap = _hardCap; //may want to deal with vesting and lockup here } /* Fallback function is called when Ether is sent to the contract. It can * Only be executed when the crowdsale is not closed, paused, or before the * deadline is reached. The function will update state variables and make * a function call to calculate number of tokens to be allocated to investor */ function () public payable whenNotPaused { // Contribution amount in wei uint amount = msg.value; uint newTotalContribution = safeAdd(contributionAmtOf[msg.sender], msg.value); // amount must be greater than or equal to the minimum contribution amount require(amount >= minContribution); if (preSale) { require(newTotalContribution <= preMaxContribution); } if (mainSale) { require(newTotalContribution <= mainMaxContribution); } // Convert wei to UNC and allocate token amount allocateTokens(msg.sender, amount); } // Caluclates the number of tokens to allocate to investor and updates balance function allocateTokens(address investor, uint _amount) internal { // Make sure investor has been verified require(kycVerified[investor]); // Calculate baseline number of tokens uint numTokens = safeMul(_amount, rate); //logic for adjusting the number of tokens they get based on stage and amount if (preSale) { // greater than 160 Eth if (_amount >= highBonus) { numTokens = safeDiv(safeMul(numTokens, highBonusRate), 100); } else { numTokens = safeDiv(safeMul(numTokens, lowBonusRate), 100); } } else { numTokens = safeDiv(safeMul(numTokens, lowBonusRate), 100); } // Check that there are enough tokens left for sale to execute purchase and update balances require(token.balanceOf(address(this)) >= numTokens); tokenBalanceOf[investor] = safeAdd(tokenBalanceOf[investor], numTokens); // Crowdsale contract sends investor their tokens token.transfer(investor, numTokens); // Update the amount this investor has contributed contributionAmtOf[investor] = safeAdd(contributionAmtOf[investor], _amount); amountRaised = safeAdd(amountRaised, _amount); } // Function to transfer tokens from this contract to an address function tokenTransfer(address recipient, uint numToks) public onlyOwner { token.transfer(recipient, numToks); } /* * Owner can call this function to withdraw funds sent to this contract. * The funds will be sent to the beneficiary specified when the * crowdsale was created. */ function beneficiaryWithdrawal() external onlyOwner { uint contractBalance = address(this).balance; // Send eth in contract to the beneficiary beneficiary.transfer(contractBalance); emit BalanceTransfer(beneficiary, contractBalance); } // The owner can end crowdsale at any time. function terminate() external onlyOwner { saleEnded = true; } // Allows owner to update the rate (UNC to ETH) function setRate(uint _rate) public onlyOwner { require(_rate >= lowRate && _rate <= highRate); rate = _rate; emit RateChanged(rate); } // Checks if there are any tokens left to sell. Updates // state variables and triggers event hardReached function checkHardReached() internal { if(!hardCapReached) { if (token.balanceOf(address(this)) == 0) { hardCapReached = true; saleEnded = true; emit HardReached(beneficiary, amountRaised); } } } // Starts the preSale stage. function startPreSale() public onlyOwner { beforeSale = false; preSale = true; } // Starts the mainSale stage function startMainSale() public afterStart onlyOwner { preSale = false; mainSale = true; } // Ends the preSale and mainSale stage. function endSale() public afterStart onlyOwner { preSale = false; mainSale = false; saleEnded = true; } /* * Function to update the start time of the pre-sale. Checks that the sale * has not started and that the new time is valid */ function updatePreSaleTime(uint newTime) public onlyOwner { require(beforeSale == true); require(now < preSaleTime); require(now < newTime); preSaleTime = newTime; } /* * Function to update the start time of the main-sale. Checks that the main * sale has not started and that the new time is valid */ function updateMainSaleTime(uint newTime) public onlyOwner { require(mainSale != true); require(now < mainSaleTime); require(now < newTime); mainSaleTime = newTime; } /* * Function to update the end of the sale. Checks that the main * sale has not ended and that the new time is valid */ function updateEndSaleTime(uint newTime) public onlyOwner { require(saleEnded != true); require(now < endSaleTime); require(now < newTime); endSaleTime = newTime; } // Function to burn all unsold tokens after sale has ended function burnUnsoldTokens() public afterEnd onlyOwner { // All unsold tokens that are held by this contract get burned uint256 tokensToBurn = token.balanceOf(address(this)); token.burn(tokensToBurn); } // Adds an address to the list of verifiers function addVerifier (address _address) public onlyOwner { isVerifier[_address] = true; } // Removes an address from the list of verifiers function removeVerifier (address _address) public onlyOwner { isVerifier[_address] = false; } // Function to update an addresses KYC verification status function verifyKYC(address[] participants) public verifierOnly { require(participants.length > 0); // KYC verify all addresses in array participants for (uint256 i = 0; i < participants.length; i++) { kycVerified[participants[i]] = true; emit VerifiedKYC(participants[i]); } } // Function to update the start time of a particular timeLock function moveReleaseTime(address person, uint256 newTime) public onlyOwner { require(timeLocks[person] != 0x0); require(now < newTime); // Get the timeLock instance for this person TimeLock lock = TimeLock(timeLocks[person]); lock.updateReleaseTime(newTime); } // Release unlocked tokens function releaseLock(address person) public { require(timeLocks[person] != 0x0); // Get the timeLock instance for this person TimeLock lock = TimeLock(timeLocks[person]); // Release the vested tokens for this person lock.release(); } // Adds an address for commitments made off-chain function offChainTrans(address participant, uint256 tokensAllocated, uint256 contributionAmt, bool isFounder) public onlyOwner { uint256 startTime; // Store tokensAllocated in a variable uint256 tokens = tokensAllocated; // Check that there are enough tokens to allocate to participant require(token.balanceOf(address(this)) >= tokens); // Update how much this participant has contributed contributionAmtOf[participant] = safeAdd(contributionAmtOf[participant], contributionAmt); // increase tokenBalanceOf by tokensAllocated for this person tokenBalanceOf[participant] = safeAdd(tokenBalanceOf[participant], tokens); // Set the start date for their vesting. Founders: June 1, 2019. Everyone else: Aug 3, 2018 if (isFounder) { // June 1, 2019 startTime = 1559347200; } else { // October 30th, 2018 startTime = 1540886400; } // declare an object of type timeLock TimeLock lock; // Create or update timelock for this participant if (timeLocks[participant] == 0x0) { lock = new TimeLock(token, participant, startTime); timeLocks[participant] = address(lock); } else { lock = TimeLock(timeLocks[participant]); } // Transfer tokens to the time lock and set its initial balance token.transfer(lock, tokens); lock.setInitialBalance(); //Make event for private investor and invoke it here emit AddedOffChain(participant, tokensAllocated); } }
Function to burn all unsold tokens after sale has ended All unsold tokens that are held by this contract get burned
function burnUnsoldTokens() public afterEnd onlyOwner { uint256 tokensToBurn = token.balanceOf(address(this)); token.burn(tokensToBurn); }
12,639,801
[ 1, 2083, 358, 18305, 777, 16804, 1673, 2430, 1839, 272, 5349, 711, 16926, 4826, 16804, 1673, 2430, 716, 854, 15770, 635, 333, 6835, 336, 18305, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 984, 87, 1673, 5157, 1435, 1071, 1839, 1638, 1338, 5541, 288, 203, 377, 202, 11890, 5034, 2430, 774, 38, 321, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 377, 202, 2316, 18, 70, 321, 12, 7860, 774, 38, 321, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; contract PiggyBank { // State variables: address payable owner; // contract owner's address; uint limit; // piggybank's minimal limit to withdraw; uint128 balance; // piggybank's deposit balance; uint version = 1; // version of the PiggyBank. // Modifier that allows public function to accept all external calls. modifier alwaysAccept { // Runtime function that allows contract to process inbound messages spending // its own resources (it's necessary if contract should process all inbound messages, // not only those that carry value with them). tvm.accept(); _; } // Modifier that allows public function to be called only by message signed with owner's pubkey. modifier checkPubkeyAndAccept { require(msg.pubkey() == tvm.pubkey()); tvm.accept(); _; } // Modifier that allows public function to be called only from the owners address. modifier checkOwnerAndAccept { require(msg.sender == owner); tvm.accept(); _; } // Modifier that allows public function to be called only when the limit is reached. modifier checkBalance() { require(balance >= limit); _; } // Constructor saves the address of the contract owner in a state variable and // initializes the limit and the balance. constructor(address payable pb_owner, uint pb_limit) public alwaysAccept { owner = pb_owner; limit = pb_limit; balance = 0; } // Function that can be called by anyone. function deposit() public payable alwaysAccept { balance += uint128(msg.value); } // Function to change the PiggyBank limit that can be called only by the owner function setLimit(uint newLimit) public payable checkOwnerAndAccept { limit = newLimit; } // Function that can be called only by the owner after reaching the limit. function withdraw() public checkBalance checkOwnerAndAccept { msg.sender.transfer(balance); balance = 0; } // Function that changes the code of current contract. function setCode(TvmCell newcode) public checkPubkeyAndAccept { // Runtime function that creates an output action that would change this // smart contract code to that given by cell newcode. tvm.setcode(newcode); // Runtime function that replaces current code of the contract with newcode. tvm.setCurrentCode(newcode); // Call function onCodeUpgrade of the 'new' code. onCodeUpgrade(); } // After code upgrade caused by calling setCode function we may need to do some actions. // We can add them into this function with constant id. function onCodeUpgrade() private { version = 2; setLimit(limit * 2); } // Function to obtain contract version. function getVersion() public view alwaysAccept returns (uint) { return version; } }
Function that can be called only by the owner after reaching the limit.
function withdraw() public checkBalance checkOwnerAndAccept { msg.sender.transfer(balance); balance = 0; }
15,840,074
[ 1, 2083, 716, 848, 506, 2566, 1338, 635, 326, 3410, 1839, 9287, 310, 326, 1800, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 598, 9446, 1435, 1071, 866, 13937, 866, 5541, 1876, 5933, 288, 203, 202, 202, 3576, 18, 15330, 18, 13866, 12, 12296, 1769, 203, 202, 202, 12296, 273, 374, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x5c421066EbA9E1387f8BEa709c08C8425F0E1350/sources/contracts/PriceFeedFactory.sol
sliding window oracle that uses observations collected over a window to provide moving price averages in the past `windowSize` with a precision of `windowSize / granularity` note this is a singleton oracle and only needs to be deployed once per desired parameters, which differs from the simple oracle which must be deployed once per pair.
contract SlidingWindowOracle { using FixedPoint for *; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } address public immutable factory; address public immutable feedFactory; uint public immutable windowSize; uint8 public immutable granularity; uint public immutable periodSize; mapping(address => Observation[]) public pairObservations; constructor(address factory_, uint windowSize_, uint8 granularity_) public { require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY'); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, 'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE' ); factory = factory_; windowSize = windowSize_; granularity = granularity_; feedFactory = msg.sender; } function observationIndexOf(uint timestamp) public view returns (uint8 index) { uint epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } function update(address tokenA, address tokenB) external { require(msg.sender == feedFactory, 'Only feedFactory'); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } Observation storage observation = pairObservations[pair][observationIndex]; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; } } function update(address tokenA, address tokenB) external { require(msg.sender == feedFactory, 'Only feedFactory'); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } Observation storage observation = pairObservations[pair][observationIndex]; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; } } uint8 observationIndex = observationIndexOf(block.timestamp); uint timeElapsed = block.timestamp - observation.timestamp; function update(address tokenA, address tokenB) external { require(msg.sender == feedFactory, 'Only feedFactory'); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } Observation storage observation = pairObservations[pair][observationIndex]; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; } } function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = getFirstObservationInWindow(pair); uint timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION'); require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED'); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = getFirstObservationInWindow(pair); uint timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION'); require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED'); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } } else { }
16,323,744
[ 1, 2069, 10415, 2742, 20865, 716, 4692, 16477, 12230, 1879, 279, 2742, 358, 5615, 12499, 6205, 23713, 1023, 316, 326, 8854, 1375, 5668, 1225, 68, 598, 279, 6039, 434, 1375, 5668, 1225, 342, 25380, 68, 4721, 333, 353, 279, 6396, 20865, 471, 1338, 4260, 358, 506, 19357, 3647, 1534, 6049, 1472, 16, 1492, 21944, 628, 326, 4143, 20865, 1492, 1297, 506, 19357, 3647, 1534, 3082, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9708, 10415, 3829, 23601, 288, 203, 565, 1450, 15038, 2148, 364, 380, 31, 203, 203, 565, 1958, 27177, 367, 288, 203, 3639, 2254, 2858, 31, 203, 3639, 2254, 6205, 20, 39, 11276, 31, 203, 3639, 2254, 6205, 21, 39, 11276, 31, 203, 565, 289, 203, 203, 565, 1758, 1071, 11732, 3272, 31, 203, 565, 1758, 1071, 11732, 4746, 1733, 31, 203, 203, 203, 565, 2254, 1071, 11732, 27064, 31, 203, 565, 2254, 28, 1071, 11732, 25380, 31, 203, 565, 2254, 1071, 11732, 3879, 1225, 31, 203, 565, 2874, 12, 2867, 516, 27177, 367, 63, 5717, 1071, 3082, 26199, 1012, 31, 203, 565, 3885, 12, 2867, 3272, 67, 16, 2254, 27064, 67, 16, 2254, 28, 25380, 67, 13, 1071, 288, 203, 3639, 2583, 12, 75, 27234, 67, 405, 404, 16, 296, 3738, 10415, 3829, 23601, 30, 15228, 1258, 19545, 4107, 8284, 203, 3639, 2583, 12, 203, 5411, 261, 6908, 1225, 273, 27064, 67, 342, 25380, 67, 13, 380, 25380, 67, 422, 27064, 67, 16, 203, 5411, 296, 3738, 10415, 3829, 23601, 30, 24482, 7306, 67, 4400, 67, 24427, 1157, 7076, 67, 2565, 29588, 11, 203, 3639, 11272, 203, 3639, 3272, 273, 3272, 67, 31, 203, 3639, 27064, 273, 27064, 67, 31, 203, 3639, 25380, 273, 25380, 67, 31, 203, 3639, 4746, 1733, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 13853, 31985, 12, 11890, 2858, 13, 1071, 1476, 1135, 261, 11890, 28, 770, 13, 288, 203, 3639, 2254, 7632, 5027, 273, 2858, 342, 3879, 1225, 31, 203, 3639, 327, 2254, 2 ]
./full_match/100/0xcd2D99b1bf2cBa504CDff5A33e65Daa3e00E1e88/sources/compilationTests/gnosis/Tokens/OutcomeToken.sol
@title Outcome token contract - Issuing and revoking outcome tokens @author Stefan George - <[email protected]>
contract OutcomeToken is StandardToken { using Math for *; event Issuance(address indexed owner, uint amount); event Revocation(address indexed owner, uint amount); address public eventContract; modifier isEventContract () { require(msg.sender == eventContract); _; } constructor() { eventContract = msg.sender; } function issue(address _for, uint outcomeTokenCount) public isEventContract { balances[_for] = balances[_for].add(outcomeTokenCount); totalTokens = totalTokens.add(outcomeTokenCount); emit Issuance(_for, outcomeTokenCount); } function revoke(address _for, uint outcomeTokenCount) public isEventContract { balances[_for] = balances[_for].sub(outcomeTokenCount); totalTokens = totalTokens.sub(outcomeTokenCount); emit Revocation(_for, outcomeTokenCount); } }
14,288,520
[ 1, 19758, 1147, 6835, 300, 9310, 22370, 471, 5588, 601, 310, 12884, 2430, 225, 7780, 74, 304, 15391, 280, 908, 300, 411, 334, 10241, 304, 36, 1600, 538, 291, 18, 7755, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2976, 5624, 1345, 353, 8263, 1345, 288, 203, 565, 1450, 2361, 364, 380, 31, 203, 203, 565, 871, 9310, 89, 1359, 12, 2867, 8808, 3410, 16, 2254, 3844, 1769, 203, 565, 871, 14477, 4431, 12, 2867, 8808, 3410, 16, 2254, 3844, 1769, 203, 203, 565, 1758, 1071, 871, 8924, 31, 203, 203, 565, 9606, 15805, 8924, 1832, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 871, 8924, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 203, 565, 288, 203, 3639, 871, 8924, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 5672, 12, 2867, 389, 1884, 16, 2254, 12884, 1345, 1380, 13, 203, 3639, 1071, 203, 3639, 15805, 8924, 203, 565, 288, 203, 3639, 324, 26488, 63, 67, 1884, 65, 273, 324, 26488, 63, 67, 1884, 8009, 1289, 12, 21672, 1345, 1380, 1769, 203, 3639, 2078, 5157, 273, 2078, 5157, 18, 1289, 12, 21672, 1345, 1380, 1769, 203, 3639, 3626, 9310, 89, 1359, 24899, 1884, 16, 12884, 1345, 1380, 1769, 203, 565, 289, 203, 203, 565, 445, 18007, 12, 2867, 389, 1884, 16, 2254, 12884, 1345, 1380, 13, 203, 3639, 1071, 203, 3639, 15805, 8924, 203, 565, 288, 203, 3639, 324, 26488, 63, 67, 1884, 65, 273, 324, 26488, 63, 67, 1884, 8009, 1717, 12, 21672, 1345, 1380, 1769, 203, 3639, 2078, 5157, 273, 2078, 5157, 18, 1717, 12, 21672, 1345, 1380, 1769, 203, 3639, 3626, 14477, 4431, 24899, 1884, 16, 12884, 1345, 1380, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100 ]
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 { 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; } } // 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; 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; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/token/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; /** * @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.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/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]; } /** * 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; } } // File: zeppelin-solidity/contracts/token/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/crowdsale/Crowdsale.sol /** * @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; } } // File: libs/BonusCrowdsale.sol /** * @dev Parent crowdsale contract with support for time-based and amount based bonuses * Based on references from OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity * */ contract BonusCrowdsale is Crowdsale, Ownable { // Constants // The following will be populated by main crowdsale contract uint32[] public BONUS_TIMES; uint32[] public BONUS_TIMES_VALUES; uint32[] public BONUS_AMOUNTS; uint32[] public BONUS_AMOUNTS_VALUES; uint public constant BONUS_COEFF = 1000; // Values should be 10x percents, value 1000 = 100% // Members uint public tokenPriceInCents; /** * @dev Contructor * @param _tokenPriceInCents token price in USD cents. The price is fixed */ function BonusCrowdsale(uint256 _tokenPriceInCents) public { tokenPriceInCents = _tokenPriceInCents; } /** * @dev Retrieve length of bonuses by time array * @return Bonuses by time array length */ function bonusesForTimesCount() public constant returns(uint) { return BONUS_TIMES.length; } /** * @dev Sets bonuses for time */ function setBonusesForTimes(uint32[] times, uint32[] values) public onlyOwner { require(times.length == values.length); for (uint i = 0; i + 1 < times.length; i++) { require(times[i] < times[i+1]); } BONUS_TIMES = times; BONUS_TIMES_VALUES = values; } /** * @dev Retrieve length of bonuses by amounts array * @return Bonuses by amounts array length */ function bonusesForAmountsCount() public constant returns(uint) { return BONUS_AMOUNTS.length; } /** * @dev Sets bonuses for USD amounts */ function setBonusesForAmounts(uint32[] amounts, uint32[] values) public onlyOwner { require(amounts.length == values.length); for (uint i = 0; i + 1 < amounts.length; i++) { require(amounts[i] > amounts[i+1]); } BONUS_AMOUNTS = amounts; BONUS_AMOUNTS_VALUES = values; } /** * @dev Overrided buyTokens method of parent Crowdsale contract to provide bonus by changing and restoring rate variable * @param beneficiary walelt of investor to receive tokens */ function buyTokens(address beneficiary) public payable { // Compute usd amount = wei * catsInEth * usdcentsInCat / usdcentsPerUsd / weisPerEth uint256 usdValue = msg.value.mul(rate).mul(tokenPriceInCents).div(1000).div(1 ether); // Compute time and amount bonus uint256 bonus = computeBonus(usdValue); // Apply bonus by adjusting and restoring rate member uint256 oldRate = rate; rate = rate.mul(BONUS_COEFF.add(bonus)).div(BONUS_COEFF); super.buyTokens(beneficiary); rate = oldRate; } /** * @dev Computes overall bonus based on time of contribution and amount of contribution. * The total bonus is the sum of bonus by time and bonus by amount * @return bonus percentage scaled by 10 */ function computeBonus(uint256 usdValue) public constant returns(uint256) { return computeAmountBonus(usdValue).add(computeTimeBonus()); } /** * @dev Computes bonus based on time of contribution relative to the beginning of crowdsale * @return bonus percentage scaled by 10 */ function computeTimeBonus() public constant returns(uint256) { require(now >= startTime); for (uint i = 0; i < BONUS_TIMES.length; i++) { if (now.sub(startTime) <= BONUS_TIMES[i]) { return BONUS_TIMES_VALUES[i]; } } return 0; } /** * @dev Computes bonus based on amount of contribution * @return bonus percentage scaled by 10 */ function computeAmountBonus(uint256 usdValue) public constant returns(uint256) { for (uint i = 0; i < BONUS_AMOUNTS.length; i++) { if (usdValue >= BONUS_AMOUNTS[i]) { return BONUS_AMOUNTS_VALUES[i]; } } return 0; } } // File: libs/TokensCappedCrowdsale.sol /** * @dev Parent crowdsale contract is extended with support for cap in tokens * Based on references from OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity * */ contract TokensCappedCrowdsale is Crowdsale { uint256 public tokensCap; function TokensCappedCrowdsale(uint256 _tokensCap) public { tokensCap = _tokensCap; } // overriding Crowdsale#validPurchase to add extra tokens cap logic // @return true if investors can buy at the moment function validPurchase() internal constant returns(bool) { uint256 tokens = token.totalSupply().add(msg.value.mul(rate)); bool withinCap = tokens <= tokensCap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add tokens cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns(bool) { bool capReached = token.totalSupply() >= tokensCap; return super.hasEnded() || capReached; } } // 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/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/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/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 uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _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: zeppelin-solidity/contracts/token/TokenVesting.sol /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn&#39;t been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } // File: contracts/MDKToken.sol contract MDKToken is MintableToken, PausableToken { string public constant name = "MDKToken"; string public constant symbol = "MDK"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); TokenTimelock public reserveTokens; TokenVesting public teamTokens; address public PreICO = address(0); address public ICO = address(0); /** * @dev Constructor * Initializing token contract, locking team and reserve funds, sending renumeration fund to owner */ function MDKToken(address _teamFund) public { lockTeamTokens(_teamFund); lockReserveTokens(_teamFund); mint(_teamFund, 250000000 * (10 ** uint256(decimals))); pause(); } /** * @dev Lock team tokens for 3 years with vesting contract. Team can receive first portion of tokens 3 months after contract created, after that they can get portion of tokens proportional to time left until full unlock */ function lockTeamTokens(address _teamFund) private { teamTokens = new TokenVesting(_teamFund, now, 90 days, 1095 days, false); mint(teamTokens, 200000000 * (10 ** uint256(decimals))); } /** * @dev Lock reserve tokens for 1 year */ function lockReserveTokens(address _teamFund) private { reserveTokens = new TokenTimelock(this, _teamFund, uint64(now + 1 years)); mint(reserveTokens, 50000000 * (10 ** uint256(decimals))); } /** * @dev Starts ICO, making ICO contract owner, so it can mint */ function startICO(address _icoAddress) onlyOwner public { require(ICO == address(0)); require(PreICO != address(0)); require(_icoAddress != address(0)); ICO = _icoAddress; transferOwnership(_icoAddress); } /** * @dev Starts PreICO, making PreICO contract owner, so it can mint */ function startPreICO(address _icoAddress) onlyOwner public { require(PreICO == address(0)); require(_icoAddress != address(0)); PreICO = _icoAddress; transferOwnership(_icoAddress); } } // File: zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol /** * @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&#39;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 { } } // File: contracts/MDKICO.sol contract MDKICO is TokensCappedCrowdsale(MDKICO.TOKENS_CAP), FinalizableCrowdsale, BonusCrowdsale(MDKICO.TOKEN_USDCENT_PRICE) { uint8 public constant decimals = 18; uint256 constant TOKENS_CAP = 600000000 * (10 ** uint256(decimals)); uint256 public constant TOKEN_USDCENT_PRICE = 18; event RateChange(uint256 rate); /** * @dev Contructor * @param _startTime startTime of crowdsale * @param _endTime endTime of crowdsale * @param _rate MDK / ETH rate * @param _token Address of MDKToken contract */ function MDKICO( uint _startTime, uint _endTime, uint256 _rate, address _token, address _teamWallet ) public Crowdsale(_startTime, _endTime, _rate, _teamWallet) { require(_token != address(0)); token = MintableToken(_token); } /** * @dev Sets MDK to Ether rate. Will be called multiple times durign the crowdsale to adjsut the rate * since MDK cost is fixed in USD, but USD/ETH rate is changing * @param _rate defines MDK/ETH rate: 1 ETH = _rate MDKs */ function setRate(uint256 _rate) external onlyOwner { require(_rate != 0x0); rate = _rate; RateChange(_rate); } /** * @dev Gives user tokens for contribution in bitcoins * @param _beneficiary User who&#39;ll receive tokens * @param tokens Amount of tokens */ function buyForBitcoin(address _beneficiary, uint256 tokens) public onlyOwner { mintTokens(_beneficiary, tokens); } function mintTokens(address beneficiary, uint256 tokens) public onlyOwner { require(beneficiary != 0); require(tokens > 0); require(now <= endTime); // Crowdsale (without startTime check) require(!isFinalized); // FinalizableCrowdsale require(token.totalSupply().add(tokens) <= TOKENS_CAP); // TokensCappedCrowdsale token.mint(beneficiary, tokens); } /** * @dev Allows to adjust the crowdsale end time */ function setEndTime(uint256 _endTime) external onlyOwner { require(!isFinalized); require(_endTime >= startTime); require(_endTime >= now); endTime = _endTime; } /** * @dev Override super createTokenContract, so it&#39;ll not deploy MintableToke */ function createTokenContract() internal returns (MintableToken) { return MintableToken(0); } /** * @dev Give not bought tokens to owner, also give back ownership of MDKToken contract */ function finalization() internal { /* We don&#39;t call finishMinting in finalization, because after ICO we will held main round of ICO few months later */ token.transferOwnership(owner); } }
overriding Crowdsale#hasEnded to add tokens cap logic @return true if crowdsale event has ended
function hasEnded() public constant returns(bool) { bool capReached = token.totalSupply() >= tokensCap; return super.hasEnded() || capReached; }
6,555,974
[ 1, 83, 1107, 10415, 385, 492, 2377, 5349, 5332, 28362, 358, 527, 2430, 3523, 4058, 327, 638, 309, 276, 492, 2377, 5349, 871, 711, 16926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 711, 28362, 1435, 1071, 5381, 1135, 12, 6430, 13, 288, 203, 3639, 1426, 3523, 23646, 273, 1147, 18, 4963, 3088, 1283, 1435, 1545, 2430, 4664, 31, 203, 3639, 327, 2240, 18, 5332, 28362, 1435, 747, 3523, 23646, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* ___ ___ ___ ___ /\ \ /\ \ /\ \ ___ /\ \ \:\ \ /::\ \ /::\ \ /\ \ /::\ \ \:\ \ /:/\:\ \ /:/\:\ \ \:\ \ /:/\:\ \ _____\:\ \ /:/ \:\ \ /:/ /::\ \ \:\ \ /:/ /::\ \ /::::::::\__\ /:/__/ \:\__\ /:/_/:/\:\__\ ___ \:\__\ /:/_/:/\:\__\ \:\~~\~~\/__/ \:\ \ /:/ / \:\/:/ \/__/ /\ \ |:| | \:\/:/ \/__/ \:\ \ \:\ /:/ / \::/__/ \:\ \|:| | \::/__/ \:\ \ \:\/:/ / \:\ \ \:\__|:|__| \:\ \ \:\__\ \::/ / \:\__\ \::::/__/ \:\__\ \/__/ \/__/ \/__/ ~~~~ \/__/ * * MIT License * =========== * * Copyright (c) 2020 NoavaFinance * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol"; import "../../interfaces/IBank.sol"; import "../../interfaces/IPriceCalculator.sol"; import "../../library/WhitelistUpgradeable.sol"; import "../../library/SafeToken.sol"; import "../../library/PoolConstant.sol"; import "../../zap/ZapBSC.sol"; import "./VaultRelayInternal.sol"; contract VaultRelayer is WhitelistUpgradeable { using SafeMath for uint256; using SafeBEP20 for IBEP20; /* ========== CONSTANTS ============= */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,address verifyingContract)"); bytes32 public constant DEPOSIT_TYPEHASH = keccak256( "Deposit(address pool,uint256 bnbAmount,uint256 nonce,uint256 expiry)" ); bytes32 public constant WITHDRAW_TYPEHASH = keccak256("Withdraw(address pool,uint256 nonce,uint256 expiry)"); address private constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; address private constant CAKE = 0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82; address private constant BRIDGE = 0xE46Fbb655867CB122A3b14e03FC612Efb1AB6B7d; IBank private constant bank = IBank(0x926940FA307562Ac71Bb401525E1bBA6e32DBbb8); ZapBSC private constant zapBSC = ZapBSC(0xdC2bBB0D33E0e7Dea9F5b98F46EDBaC823586a0C); IPriceCalculator private constant priceCalculator = IPriceCalculator(0xF5BF8A9249e3cc4cB684E3f23db9669323d4FB7d); /* ========== STATE VARIABLES ========== */ mapping(address => uint256) public nonces; mapping(address => bool) private _testers; // pool -> account -> withdrawn history mapping(address => mapping(address => PoolConstant.RelayWithdrawn)) public withdrawnHistories; mapping(address => mapping(address => bool)) public withdrawing; /* ========== EVENTS ========== */ event Deposited( address indexed pool, address indexed account, uint256 amount ); event Withdrawn( address indexed pool, address indexed account, uint256 profitInETH, uint256 lossInETH ); event Recovered(address token, uint256 amount); /* ========== INITIALIZER ========== */ receive() external payable {} function initialize() external initializer { __WhitelistUpgradeable_init(); if (IBEP20(CAKE).allowance(address(this), address(zapBSC)) == 0) { IBEP20(CAKE).safeApprove(address(zapBSC), uint256(-1)); } } /* ========== VIEW FUNCTIONS ========== */ function totalSupply(address pool) external view returns (uint256) { return VaultRelayInternal(pool).totalSupply(); } function balanceOf(address pool, address account) external view returns (uint256) { return VaultRelayInternal(pool).balanceOf(account); } function earnedOf(address pool, address account) public view returns (uint256) { return VaultRelayInternal(pool).earned(account); } function balanceInUSD(address pool, address account) public view returns (uint256) { VaultRelayInternal vault = VaultRelayInternal(pool); uint256 flipBalance = vault.balanceOf(account); (, uint256 flipInUSD) = priceCalculator.valueOfAsset( vault.stakingToken(), flipBalance ); return flipInUSD; } function earnedInUSD(address pool, address account) public view returns (uint256) { VaultRelayInternal vault = VaultRelayInternal(pool); uint256 cakeBalance = vault.earned(account); (, uint256 cakeInUSD) = priceCalculator.valueOfAsset(CAKE, cakeBalance); return cakeInUSD; } function debtInUSD(address pool, address account) public view returns (uint256) { (, uint256 valueInUSD) = priceCalculator.valueOfAsset( WBNB, bank.pendingDebtOf(pool, account) ); return valueInUSD; } function isTester(address account) public view returns (bool) { return _testers[account]; } function withdrawnHistoryOf(address pool, address account) public view returns (PoolConstant.RelayWithdrawn memory) { return withdrawnHistories[pool][account]; } /** * @return nonce The nonce per account * @return debt The borrowed value of account in USD * @return value The borrowing value of account in USD * @return utilizable The Liquidity remain of BankBNB */ function validateDeposit( address pool, address account, uint256 bnbAmount ) public view returns ( uint256 nonce, uint256 debt, uint256 value, uint256 utilizable ) { (uint256 liquidity, uint256 utilized) = bank.getUtilizationInfo(); (, uint256 valueInUSD) = priceCalculator.valueOfAsset(WBNB, bnbAmount); return ( nonces[account], debtInUSD(pool, account), valueInUSD, liquidity.sub(utilized) ); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @param pool BSC Pool address * @param bnbAmount BNB amount to borrow * @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 depositBySig( address pool, uint256 bnbAmount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external onlyWhitelisted { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("VaultRelayer")), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DEPOSIT_TYPEHASH, pool, bnbAmount, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VaultRelayer: invalid signature"); require(isTester(signatory), "VaultRelayer: not tester"); require(nonce == nonces[signatory]++, "VaultRelayer: invalid nonce"); require(now <= expiry, "VaultRelayer: signature expired"); _deposit(pool, signatory, bnbAmount); } function withdrawBySig( address pool, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external onlyWhitelisted { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("VaultRelayer")), address(this) ) ); bytes32 structHash = keccak256( abi.encode(WITHDRAW_TYPEHASH, pool, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VaultRelayer: invalid signature"); require(nonce == nonces[signatory]++, "VaultRelayer: invalid nonce"); require(now <= expiry, "VaultRelayer: signature expired"); _withdraw(pool, signatory); } function completeWithdraw(address pool, address account) external onlyWhitelisted { delete withdrawing[pool][account]; delete withdrawnHistories[pool][account]; } function liquidate(address pool, address account) external onlyWhitelisted { _withdraw(pool, account); } function setTester(address account, bool on) external onlyOwner { _testers[account] = on; } /* ========== PRIVATE FUNCTIONS ========== */ function _deposit( address pool, address account, uint256 bnbAmount ) private { (uint256 liquidity, uint256 utilized) = bank.getUtilizationInfo(); bnbAmount = Math.min(bnbAmount, liquidity.sub(utilized)); require(bnbAmount > 0, "VaultRelayer: not enough amount"); require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); VaultRelayInternal vault = VaultRelayInternal(pool); address flip = vault.stakingToken(); uint256 _beforeBNB = address(this).balance; bank.borrow(pool, account, bnbAmount); bnbAmount = address(this).balance.sub(_beforeBNB); uint256 _beforeFlip = IBEP20(flip).balanceOf(address(this)); zapBSC.zapIn{value: bnbAmount}(flip); uint256 flipAmount = IBEP20(flip).balanceOf(address(this)).sub( _beforeFlip ); if (IBEP20(flip).allowance(address(this), pool) == 0) { IBEP20(flip).safeApprove(pool, uint256(-1)); } vault.deposit(flipAmount, account); delete withdrawnHistories[pool][account]; emit Deposited(pool, account, flipAmount); } function _withdraw(address pool, address account) private { require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); if (VaultRelayInternal(pool).balanceOf(account) == 0) return; withdrawing[pool][account] = true; (uint256 flipAmount, uint256 cakeAmount) = _withdrawInternal( pool, account ); uint256 bnbAmount = _zapOutToBNB(pool, flipAmount, cakeAmount); (uint256 profitInETH, uint256 lossInETH) = bank.repayAll{ value: bnbAmount }(pool, account); PoolConstant.RelayWithdrawn storage history = withdrawnHistories[pool][ account ]; history.pool = pool; history.account = account; history.profitInETH = history.profitInETH.add(profitInETH); history.lossInETH = history.lossInETH.add(lossInETH); if (profitInETH > lossInETH) { bank.bridgeETH(BRIDGE, profitInETH.sub(lossInETH)); } emit Withdrawn(pool, account, profitInETH, lossInETH); } function _withdrawInternal(address pool, address account) private returns (uint256 flipAmount, uint256 cakeAmount) { VaultRelayInternal vault = VaultRelayInternal(pool); address flip = vault.stakingToken(); uint256 _beforeFlip = IBEP20(flip).balanceOf(address(this)); uint256 _beforeCake = IBEP20(CAKE).balanceOf(address(this)); vault.withdrawAll(account); flipAmount = IBEP20(flip).balanceOf(address(this)).sub(_beforeFlip); cakeAmount = IBEP20(CAKE).balanceOf(address(this)).sub(_beforeCake); } function _zapOutToBNB( address pool, uint256 flipAmount, uint256 cakeAmount ) private returns (uint256) { uint256 _beforeBNB = address(this).balance; address flip = VaultRelayInternal(pool).stakingToken(); IPancakePair pair = IPancakePair(flip); address pairToken = pair.token0() == WBNB ? pair.token1() : pair.token0(); uint256 _beforePairTokenAmount = IBEP20(pairToken).balanceOf( address(this) ); _approveIfNeeded(flip); if (flipAmount > 0) zapBSC.zapOut(flip, flipAmount); if (cakeAmount > 0) zapBSC.zapOut(CAKE, cakeAmount); uint256 pairTokenAmount = IBEP20(pairToken) .balanceOf(address(this)) .sub(_beforePairTokenAmount); if (pairTokenAmount > 0) { _approveIfNeeded(pairToken); zapBSC.zapOut(pairToken, pairTokenAmount); } return address(this).balance.sub(_beforeBNB); } function _approveIfNeeded(address token) private { if (IBEP20(token).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token).safeApprove(address(zapBSC), uint256(-1)); } } /* ========== SALVAGE PURPOSE ONLY ========== */ function recoverToken(address tokenAddress, uint256 tokenAmount) external onlyOwner { require( tokenAddress != address(0) && tokenAddress != CAKE && keccak256( abi.encodePacked(IPancakePair(tokenAddress).symbol()) ) == keccak256("Cake-LP"), "VaultRelayer: cannot recover token" ); IBEP20(tokenAddress).safeTransfer(owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } }
pool -> account -> withdrawn history
contract VaultRelayer is WhitelistUpgradeable { using SafeMath for uint256; using SafeBEP20 for IBEP20; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,address verifyingContract)"); bytes32 public constant DEPOSIT_TYPEHASH = keccak256( "Deposit(address pool,uint256 bnbAmount,uint256 nonce,uint256 expiry)" ); bytes32 public constant WITHDRAW_TYPEHASH = keccak256("Withdraw(address pool,uint256 nonce,uint256 expiry)"); address private constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; address private constant CAKE = 0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82; address private constant BRIDGE = 0xE46Fbb655867CB122A3b14e03FC612Efb1AB6B7d; IBank private constant bank = IBank(0x926940FA307562Ac71Bb401525E1bBA6e32DBbb8); ZapBSC private constant zapBSC = ZapBSC(0xdC2bBB0D33E0e7Dea9F5b98F46EDBaC823586a0C); IPriceCalculator private constant priceCalculator = IPriceCalculator(0xF5BF8A9249e3cc4cB684E3f23db9669323d4FB7d); mapping(address => uint256) public nonces; mapping(address => bool) private _testers; mapping(address => mapping(address => PoolConstant.RelayWithdrawn)) public withdrawnHistories; mapping(address => mapping(address => bool)) public withdrawing; event Deposited( address indexed pool, address indexed account, uint256 amount ); event Withdrawn( address indexed pool, address indexed account, uint256 profitInETH, uint256 lossInETH ); event Recovered(address token, uint256 amount); pragma solidity ^0.6.12; ___ ___ ___ ___ receive() external payable {} function initialize() external initializer { __WhitelistUpgradeable_init(); if (IBEP20(CAKE).allowance(address(this), address(zapBSC)) == 0) { IBEP20(CAKE).safeApprove(address(zapBSC), uint256(-1)); } } function initialize() external initializer { __WhitelistUpgradeable_init(); if (IBEP20(CAKE).allowance(address(this), address(zapBSC)) == 0) { IBEP20(CAKE).safeApprove(address(zapBSC), uint256(-1)); } } function totalSupply(address pool) external view returns (uint256) { return VaultRelayInternal(pool).totalSupply(); } function balanceOf(address pool, address account) external view returns (uint256) { return VaultRelayInternal(pool).balanceOf(account); } function earnedOf(address pool, address account) public view returns (uint256) { return VaultRelayInternal(pool).earned(account); } function balanceInUSD(address pool, address account) public view returns (uint256) { VaultRelayInternal vault = VaultRelayInternal(pool); uint256 flipBalance = vault.balanceOf(account); (, uint256 flipInUSD) = priceCalculator.valueOfAsset( vault.stakingToken(), flipBalance ); return flipInUSD; } function earnedInUSD(address pool, address account) public view returns (uint256) { VaultRelayInternal vault = VaultRelayInternal(pool); uint256 cakeBalance = vault.earned(account); (, uint256 cakeInUSD) = priceCalculator.valueOfAsset(CAKE, cakeBalance); return cakeInUSD; } function debtInUSD(address pool, address account) public view returns (uint256) { (, uint256 valueInUSD) = priceCalculator.valueOfAsset( WBNB, bank.pendingDebtOf(pool, account) ); return valueInUSD; } function isTester(address account) public view returns (bool) { return _testers[account]; } function withdrawnHistoryOf(address pool, address account) public view returns (PoolConstant.RelayWithdrawn memory) { return withdrawnHistories[pool][account]; } function validateDeposit( address pool, address account, uint256 bnbAmount ) public view returns ( uint256 nonce, uint256 debt, uint256 value, uint256 utilizable ) { (uint256 liquidity, uint256 utilized) = bank.getUtilizationInfo(); (, uint256 valueInUSD) = priceCalculator.valueOfAsset(WBNB, bnbAmount); return ( nonces[account], debtInUSD(pool, account), valueInUSD, liquidity.sub(utilized) ); } function depositBySig( address pool, uint256 bnbAmount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external onlyWhitelisted { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("VaultRelayer")), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DEPOSIT_TYPEHASH, pool, bnbAmount, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VaultRelayer: invalid signature"); require(isTester(signatory), "VaultRelayer: not tester"); require(nonce == nonces[signatory]++, "VaultRelayer: invalid nonce"); require(now <= expiry, "VaultRelayer: signature expired"); _deposit(pool, signatory, bnbAmount); } function withdrawBySig( address pool, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external onlyWhitelisted { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("VaultRelayer")), address(this) ) ); bytes32 structHash = keccak256( abi.encode(WITHDRAW_TYPEHASH, pool, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VaultRelayer: invalid signature"); require(nonce == nonces[signatory]++, "VaultRelayer: invalid nonce"); require(now <= expiry, "VaultRelayer: signature expired"); _withdraw(pool, signatory); } function completeWithdraw(address pool, address account) external onlyWhitelisted { delete withdrawing[pool][account]; delete withdrawnHistories[pool][account]; } function liquidate(address pool, address account) external onlyWhitelisted { _withdraw(pool, account); } function setTester(address account, bool on) external onlyOwner { _testers[account] = on; } function _deposit( address pool, address account, uint256 bnbAmount ) private { (uint256 liquidity, uint256 utilized) = bank.getUtilizationInfo(); bnbAmount = Math.min(bnbAmount, liquidity.sub(utilized)); require(bnbAmount > 0, "VaultRelayer: not enough amount"); require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); VaultRelayInternal vault = VaultRelayInternal(pool); address flip = vault.stakingToken(); uint256 _beforeBNB = address(this).balance; bank.borrow(pool, account, bnbAmount); bnbAmount = address(this).balance.sub(_beforeBNB); uint256 _beforeFlip = IBEP20(flip).balanceOf(address(this)); uint256 flipAmount = IBEP20(flip).balanceOf(address(this)).sub( _beforeFlip ); if (IBEP20(flip).allowance(address(this), pool) == 0) { IBEP20(flip).safeApprove(pool, uint256(-1)); } vault.deposit(flipAmount, account); delete withdrawnHistories[pool][account]; emit Deposited(pool, account, flipAmount); } zapBSC.zapIn{value: bnbAmount}(flip); function _deposit( address pool, address account, uint256 bnbAmount ) private { (uint256 liquidity, uint256 utilized) = bank.getUtilizationInfo(); bnbAmount = Math.min(bnbAmount, liquidity.sub(utilized)); require(bnbAmount > 0, "VaultRelayer: not enough amount"); require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); VaultRelayInternal vault = VaultRelayInternal(pool); address flip = vault.stakingToken(); uint256 _beforeBNB = address(this).balance; bank.borrow(pool, account, bnbAmount); bnbAmount = address(this).balance.sub(_beforeBNB); uint256 _beforeFlip = IBEP20(flip).balanceOf(address(this)); uint256 flipAmount = IBEP20(flip).balanceOf(address(this)).sub( _beforeFlip ); if (IBEP20(flip).allowance(address(this), pool) == 0) { IBEP20(flip).safeApprove(pool, uint256(-1)); } vault.deposit(flipAmount, account); delete withdrawnHistories[pool][account]; emit Deposited(pool, account, flipAmount); } function _withdraw(address pool, address account) private { require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); if (VaultRelayInternal(pool).balanceOf(account) == 0) return; withdrawing[pool][account] = true; (uint256 flipAmount, uint256 cakeAmount) = _withdrawInternal( pool, account ); uint256 bnbAmount = _zapOutToBNB(pool, flipAmount, cakeAmount); (uint256 profitInETH, uint256 lossInETH) = bank.repayAll{ value: bnbAmount }(pool, account); PoolConstant.RelayWithdrawn storage history = withdrawnHistories[pool][ account ]; history.pool = pool; history.account = account; history.profitInETH = history.profitInETH.add(profitInETH); history.lossInETH = history.lossInETH.add(lossInETH); if (profitInETH > lossInETH) { bank.bridgeETH(BRIDGE, profitInETH.sub(lossInETH)); } emit Withdrawn(pool, account, profitInETH, lossInETH); } function _withdraw(address pool, address account) private { require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); if (VaultRelayInternal(pool).balanceOf(account) == 0) return; withdrawing[pool][account] = true; (uint256 flipAmount, uint256 cakeAmount) = _withdrawInternal( pool, account ); uint256 bnbAmount = _zapOutToBNB(pool, flipAmount, cakeAmount); (uint256 profitInETH, uint256 lossInETH) = bank.repayAll{ value: bnbAmount }(pool, account); PoolConstant.RelayWithdrawn storage history = withdrawnHistories[pool][ account ]; history.pool = pool; history.account = account; history.profitInETH = history.profitInETH.add(profitInETH); history.lossInETH = history.lossInETH.add(lossInETH); if (profitInETH > lossInETH) { bank.bridgeETH(BRIDGE, profitInETH.sub(lossInETH)); } emit Withdrawn(pool, account, profitInETH, lossInETH); } function _withdraw(address pool, address account) private { require( !withdrawing[pool][account], "VaultRelayer: withdrawing must be complete" ); if (VaultRelayInternal(pool).balanceOf(account) == 0) return; withdrawing[pool][account] = true; (uint256 flipAmount, uint256 cakeAmount) = _withdrawInternal( pool, account ); uint256 bnbAmount = _zapOutToBNB(pool, flipAmount, cakeAmount); (uint256 profitInETH, uint256 lossInETH) = bank.repayAll{ value: bnbAmount }(pool, account); PoolConstant.RelayWithdrawn storage history = withdrawnHistories[pool][ account ]; history.pool = pool; history.account = account; history.profitInETH = history.profitInETH.add(profitInETH); history.lossInETH = history.lossInETH.add(lossInETH); if (profitInETH > lossInETH) { bank.bridgeETH(BRIDGE, profitInETH.sub(lossInETH)); } emit Withdrawn(pool, account, profitInETH, lossInETH); } function _withdrawInternal(address pool, address account) private returns (uint256 flipAmount, uint256 cakeAmount) { VaultRelayInternal vault = VaultRelayInternal(pool); address flip = vault.stakingToken(); uint256 _beforeFlip = IBEP20(flip).balanceOf(address(this)); uint256 _beforeCake = IBEP20(CAKE).balanceOf(address(this)); vault.withdrawAll(account); flipAmount = IBEP20(flip).balanceOf(address(this)).sub(_beforeFlip); cakeAmount = IBEP20(CAKE).balanceOf(address(this)).sub(_beforeCake); } function _zapOutToBNB( address pool, uint256 flipAmount, uint256 cakeAmount ) private returns (uint256) { uint256 _beforeBNB = address(this).balance; address flip = VaultRelayInternal(pool).stakingToken(); IPancakePair pair = IPancakePair(flip); address pairToken = pair.token0() == WBNB ? pair.token1() : pair.token0(); uint256 _beforePairTokenAmount = IBEP20(pairToken).balanceOf( address(this) ); _approveIfNeeded(flip); if (flipAmount > 0) zapBSC.zapOut(flip, flipAmount); if (cakeAmount > 0) zapBSC.zapOut(CAKE, cakeAmount); uint256 pairTokenAmount = IBEP20(pairToken) .balanceOf(address(this)) .sub(_beforePairTokenAmount); if (pairTokenAmount > 0) { _approveIfNeeded(pairToken); zapBSC.zapOut(pairToken, pairTokenAmount); } return address(this).balance.sub(_beforeBNB); } function _zapOutToBNB( address pool, uint256 flipAmount, uint256 cakeAmount ) private returns (uint256) { uint256 _beforeBNB = address(this).balance; address flip = VaultRelayInternal(pool).stakingToken(); IPancakePair pair = IPancakePair(flip); address pairToken = pair.token0() == WBNB ? pair.token1() : pair.token0(); uint256 _beforePairTokenAmount = IBEP20(pairToken).balanceOf( address(this) ); _approveIfNeeded(flip); if (flipAmount > 0) zapBSC.zapOut(flip, flipAmount); if (cakeAmount > 0) zapBSC.zapOut(CAKE, cakeAmount); uint256 pairTokenAmount = IBEP20(pairToken) .balanceOf(address(this)) .sub(_beforePairTokenAmount); if (pairTokenAmount > 0) { _approveIfNeeded(pairToken); zapBSC.zapOut(pairToken, pairTokenAmount); } return address(this).balance.sub(_beforeBNB); } function _approveIfNeeded(address token) private { if (IBEP20(token).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token).safeApprove(address(zapBSC), uint256(-1)); } } function _approveIfNeeded(address token) private { if (IBEP20(token).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token).safeApprove(address(zapBSC), uint256(-1)); } } function recoverToken(address tokenAddress, uint256 tokenAmount) external onlyOwner { require( tokenAddress != address(0) && tokenAddress != CAKE && keccak256( abi.encodePacked(IPancakePair(tokenAddress).symbol()) ) == keccak256("Cake-LP"), "VaultRelayer: cannot recover token" ); IBEP20(tokenAddress).safeTransfer(owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } }
12,632,919
[ 1, 6011, 317, 2236, 317, 598, 9446, 82, 4927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17329, 1971, 1773, 353, 3497, 7523, 10784, 429, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 5948, 52, 3462, 364, 467, 5948, 52, 3462, 31, 203, 203, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 28284, 67, 2399, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 12, 203, 5411, 315, 758, 1724, 12, 2867, 2845, 16, 11890, 5034, 324, 6423, 6275, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 203, 3639, 11272, 203, 565, 1731, 1578, 1071, 5381, 13601, 40, 10821, 67, 2399, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 2932, 1190, 9446, 12, 2867, 2845, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 203, 565, 1758, 3238, 5381, 678, 15388, 38, 273, 374, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 31, 203, 565, 1758, 3238, 5381, 6425, 6859, 273, 374, 92, 20, 41, 5908, 29634, 9676, 9036, 38, 72, 23, 37, 323, 20, 69, 4033, 41, 6743, 1578, 21, 74, 40, 3437, 69, 3657, 73, 11861, 71, 41, 11149, 31, 203, 565, 1758, 3238, 5381, 22427, 734, 7113, 273, 203, 3639, 374, 17432, 8749, 42, 9897, 26, 2539, 5292, 27, 8876, 22266, 37, 23, 70, 3461, 73, 2 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/presets/ERC20PresetMinterPauser.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev {ERC20} 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 * * NOTE: Modified from OZ ERC20PresetMinterPauser to add Snapshot extension * * 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 FitcoinToken is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable, ERC20Snapshot { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(SNAPSHOT_ROLE, _msgSender()); } function snapshot() public returns (uint256) { require(hasRole(SNAPSHOT_ROLE, msg.sender), "Token: must have snapshot role to call snapshot"); return _snapshot(); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.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). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC20 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 ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Arrays.sol"; import "../../../utils/Counters.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. * * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient * alternative consider {ERC20Votes}. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping(address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _getCurrentSnapshotId(); emit Snapshot(currentId); return currentId; } /** * @dev Get the current snapshotId */ function _getCurrentSnapshotId() internal view virtual returns (uint256) { return _currentSnapshotId.current(); } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _getCurrentSnapshotId(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).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) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // 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 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // 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 (utils/Arrays.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) 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 // OpenZeppelin Contracts v4.4.1 (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 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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 // OpenZeppelin Contracts v4.4.1 (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 override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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 (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 EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @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 // 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/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev {ERC20} 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 NOTE: Modified from OZ ERC20PresetMinterPauser to add Snapshot extension 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 FitcoinToken is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable, ERC20Snapshot { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE"); constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(SNAPSHOT_ROLE, _msgSender()); } function snapshot() public returns (uint256) { require(hasRole(SNAPSHOT_ROLE, msg.sender), "Token: must have snapshot role to call snapshot"); return _snapshot(); } function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } }
6,149,090
[ 1, 95, 654, 39, 3462, 97, 1147, 16, 6508, 30, 225, 300, 7123, 364, 366, 4665, 358, 18305, 261, 11662, 13, 3675, 2430, 225, 300, 279, 1131, 387, 2478, 716, 5360, 364, 1147, 312, 474, 310, 261, 17169, 13, 225, 300, 279, 6790, 1355, 2478, 716, 5360, 358, 2132, 777, 1147, 29375, 225, 5219, 30, 21154, 628, 531, 62, 4232, 39, 3462, 18385, 49, 2761, 16507, 1355, 358, 527, 10030, 2710, 1220, 6835, 4692, 288, 16541, 97, 358, 2176, 4132, 329, 4186, 1450, 326, 3775, 4900, 300, 910, 358, 2097, 7323, 364, 3189, 18, 1021, 2236, 716, 5993, 383, 1900, 326, 6835, 903, 506, 17578, 326, 1131, 387, 471, 6790, 1355, 4900, 16, 487, 5492, 487, 326, 805, 3981, 2478, 16, 1492, 903, 2231, 518, 7936, 3937, 1131, 387, 471, 6790, 1355, 4900, 358, 1308, 9484, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 30504, 12645, 1345, 353, 1772, 16, 24349, 3572, 25121, 16, 4232, 39, 3462, 38, 321, 429, 16, 4232, 39, 3462, 16507, 16665, 16, 4232, 39, 3462, 4568, 288, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 14204, 31667, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 13653, 31667, 67, 16256, 8863, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 4232, 39, 3462, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 13653, 31667, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 4439, 1435, 203, 3639, 1071, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 13653, 31667, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 1345, 30, 1297, 1240, 4439, 2478, 358, 745, 4439, 8863, 203, 203, 3639, 327, 389, 11171, 5621, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 2 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/lib/contracts/libraries/SafeERC20Namer.sol'; import './libraries/ChainId.sol'; import './interfaces/INonfungiblePositionManager.sol'; import './interfaces/INonfungibleTokenPositionDescriptor.sol'; import './interfaces/IERC20Metadata.sol'; import './libraries/PoolAddress.sol'; import './libraries/NFTDescriptor.sol'; import './libraries/TokenRatioSortOrder.sol'; /// @title Describes NFT token positions /// @notice Produces a string containing the data URI for a JSON metadata string contract NonfungibleTokenPositionDescriptor is INonfungibleTokenPositionDescriptor { address private constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address private constant TBTC = 0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa; address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public immutable WETH9; constructor(address _WETH9) { WETH9 = _WETH9; } /// @inheritdoc INonfungibleTokenPositionDescriptor function tokenURI(INonfungiblePositionManager positionManager, uint256 tokenId) external view override returns (string memory) { (, , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, , , , , ) = positionManager.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool( PoolAddress.computeAddress( positionManager.factory(), PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) ) ); bool _flipRatio = flipRatio(token0, token1, ChainId.get()); address quoteTokenAddress = !_flipRatio ? token1 : token0; address baseTokenAddress = !_flipRatio ? token0 : token1; (, int24 tick, , , , , ) = pool.slot0(); return NFTDescriptor.constructTokenURI( NFTDescriptor.ConstructTokenURIParams({ tokenId: tokenId, quoteTokenAddress: quoteTokenAddress, baseTokenAddress: baseTokenAddress, quoteTokenSymbol: quoteTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(quoteTokenAddress), baseTokenSymbol: baseTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(baseTokenAddress), quoteTokenDecimals: IERC20Metadata(quoteTokenAddress).decimals(), baseTokenDecimals: IERC20Metadata(baseTokenAddress).decimals(), flipRatio: _flipRatio, tickLower: tickLower, tickUpper: tickUpper, tickCurrent: tick, tickSpacing: pool.tickSpacing(), fee: fee, poolAddress: address(pool) }) ); } function flipRatio( address token0, address token1, uint256 chainId ) public view returns (bool) { return tokenRatioPriority(token0, chainId) > tokenRatioPriority(token1, chainId); } function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) { if (token == WETH9) { return TokenRatioSortOrder.DENOMINATOR; } if (chainId == 1) { if (token == USDC) { return TokenRatioSortOrder.NUMERATOR_MOST; } else if (token == USDT) { return TokenRatioSortOrder.NUMERATOR_MORE; } else if (token == DAI) { return TokenRatioSortOrder.NUMERATOR; } else if (token == TBTC) { return TokenRatioSortOrder.DENOMINATOR_MORE; } else if (token == WBTC) { return TokenRatioSortOrder.DENOMINATOR_MOST; } else { return 0; } } return 0; } }
@title Describes NFT token positions @notice Produces a string containing the data URI for a JSON metadata string
contract NonfungibleTokenPositionDescriptor is INonfungibleTokenPositionDescriptor { address private constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address private constant TBTC = 0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa; address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public immutable WETH9; pragma solidity =0.7.6; constructor(address _WETH9) { WETH9 = _WETH9; } function tokenURI(INonfungiblePositionManager positionManager, uint256 tokenId) external view override returns (string memory) { (, , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, , , , , ) = positionManager.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool( PoolAddress.computeAddress( positionManager.factory(), ) ); bool _flipRatio = flipRatio(token0, token1, ChainId.get()); address quoteTokenAddress = !_flipRatio ? token1 : token0; address baseTokenAddress = !_flipRatio ? token0 : token1; (, int24 tick, , , , , ) = pool.slot0(); return NFTDescriptor.constructTokenURI( NFTDescriptor.ConstructTokenURIParams({ tokenId: tokenId, quoteTokenAddress: quoteTokenAddress, baseTokenAddress: baseTokenAddress, quoteTokenSymbol: quoteTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(quoteTokenAddress), baseTokenSymbol: baseTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(baseTokenAddress), quoteTokenDecimals: IERC20Metadata(quoteTokenAddress).decimals(), baseTokenDecimals: IERC20Metadata(baseTokenAddress).decimals(), flipRatio: _flipRatio, tickLower: tickLower, tickUpper: tickUpper, tickCurrent: tick, tickSpacing: pool.tickSpacing(), fee: fee, poolAddress: address(pool) }) ); } PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) function tokenURI(INonfungiblePositionManager positionManager, uint256 tokenId) external view override returns (string memory) { (, , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, , , , , ) = positionManager.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool( PoolAddress.computeAddress( positionManager.factory(), ) ); bool _flipRatio = flipRatio(token0, token1, ChainId.get()); address quoteTokenAddress = !_flipRatio ? token1 : token0; address baseTokenAddress = !_flipRatio ? token0 : token1; (, int24 tick, , , , , ) = pool.slot0(); return NFTDescriptor.constructTokenURI( NFTDescriptor.ConstructTokenURIParams({ tokenId: tokenId, quoteTokenAddress: quoteTokenAddress, baseTokenAddress: baseTokenAddress, quoteTokenSymbol: quoteTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(quoteTokenAddress), baseTokenSymbol: baseTokenAddress == WETH9 ? 'ETH' : SafeERC20Namer.tokenSymbol(baseTokenAddress), quoteTokenDecimals: IERC20Metadata(quoteTokenAddress).decimals(), baseTokenDecimals: IERC20Metadata(baseTokenAddress).decimals(), flipRatio: _flipRatio, tickLower: tickLower, tickUpper: tickUpper, tickCurrent: tick, tickSpacing: pool.tickSpacing(), fee: fee, poolAddress: address(pool) }) ); } function flipRatio( address token0, address token1, uint256 chainId ) public view returns (bool) { return tokenRatioPriority(token0, chainId) > tokenRatioPriority(token1, chainId); } function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) { if (token == WETH9) { return TokenRatioSortOrder.DENOMINATOR; } if (chainId == 1) { if (token == USDC) { return TokenRatioSortOrder.NUMERATOR_MOST; return TokenRatioSortOrder.NUMERATOR_MORE; return TokenRatioSortOrder.NUMERATOR; return TokenRatioSortOrder.DENOMINATOR_MORE; return TokenRatioSortOrder.DENOMINATOR_MOST; return 0; } } return 0; } function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) { if (token == WETH9) { return TokenRatioSortOrder.DENOMINATOR; } if (chainId == 1) { if (token == USDC) { return TokenRatioSortOrder.NUMERATOR_MOST; return TokenRatioSortOrder.NUMERATOR_MORE; return TokenRatioSortOrder.NUMERATOR; return TokenRatioSortOrder.DENOMINATOR_MORE; return TokenRatioSortOrder.DENOMINATOR_MOST; return 0; } } return 0; } function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) { if (token == WETH9) { return TokenRatioSortOrder.DENOMINATOR; } if (chainId == 1) { if (token == USDC) { return TokenRatioSortOrder.NUMERATOR_MOST; return TokenRatioSortOrder.NUMERATOR_MORE; return TokenRatioSortOrder.NUMERATOR; return TokenRatioSortOrder.DENOMINATOR_MORE; return TokenRatioSortOrder.DENOMINATOR_MOST; return 0; } } return 0; } function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) { if (token == WETH9) { return TokenRatioSortOrder.DENOMINATOR; } if (chainId == 1) { if (token == USDC) { return TokenRatioSortOrder.NUMERATOR_MOST; return TokenRatioSortOrder.NUMERATOR_MORE; return TokenRatioSortOrder.NUMERATOR; return TokenRatioSortOrder.DENOMINATOR_MORE; return TokenRatioSortOrder.DENOMINATOR_MOST; return 0; } } return 0; } } else if (token == USDT) { } else if (token == DAI) { } else if (token == TBTC) { } else if (token == WBTC) { } else { }
12,901,836
[ 1, 4217, 24322, 423, 4464, 1147, 6865, 225, 22934, 279, 533, 4191, 326, 501, 3699, 364, 279, 1796, 1982, 533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3858, 12125, 75, 1523, 1345, 2555, 3187, 353, 2120, 265, 12125, 75, 1523, 1345, 2555, 3187, 288, 203, 565, 1758, 3238, 5381, 463, 18194, 273, 374, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 31, 203, 565, 1758, 3238, 5381, 11836, 5528, 273, 374, 21703, 20, 70, 5292, 2733, 21, 71, 8898, 2643, 70, 5718, 71, 21, 72, 3657, 40, 24, 69, 22, 73, 29, 41, 70, 20, 71, 41, 29751, 26, 73, 38, 8875, 31, 203, 565, 1758, 3238, 5381, 11836, 9081, 273, 374, 7669, 2226, 4033, 42, 29, 8204, 40, 22, 1340, 25, 4366, 69, 27246, 26, 3462, 26, 2733, 24, 6162, 27, 39, 3437, 40, 28, 6938, 557, 27, 31, 203, 565, 1758, 3238, 5381, 399, 38, 15988, 273, 374, 92, 28, 72, 16985, 12536, 1639, 29, 3787, 72, 42, 27, 4763, 71, 7414, 39, 3672, 39, 27, 73, 18096, 27, 6840, 12664, 3361, 28, 3600, 29534, 69, 31, 203, 565, 1758, 3238, 5381, 678, 38, 15988, 273, 374, 92, 3787, 4848, 2046, 39, 25, 41, 2539, 9452, 69, 4700, 23, 37, 69, 6334, 74, 16283, 3030, 40, 74, 27, 39, 3657, 23, 13459, 22, 39, 25, 2733, 31, 203, 203, 565, 1758, 1071, 11732, 678, 1584, 44, 29, 31, 203, 203, 683, 9454, 18035, 560, 273, 20, 18, 27, 18, 26, 31, 203, 565, 3885, 12, 2867, 389, 59, 1584, 44, 29, 13, 288, 203, 3639, 678, 1584, 2 ]
./partial_match/137/0x6Cc13dB0B67a2A29c210D4A4638DA51E8cD8b139/sources/BlackErc20.sol
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
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } struct Counter { }
3,516,319
[ 1, 2503, 2190, 1410, 5903, 506, 5122, 15539, 635, 3677, 434, 326, 5313, 30, 23877, 1297, 506, 15693, 358, 326, 5313, 1807, 445, 18, 2970, 434, 348, 7953, 560, 331, 20, 18, 25, 18, 22, 16, 333, 2780, 506, 570, 19778, 16, 11376, 1915, 353, 279, 14708, 358, 527, 333, 2572, 30, 2621, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 30205, 560, 19, 9618, 19, 24, 4449, 27, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 1958, 9354, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x734cd09a8e204f946b588D5c470b2a940e2Dbbf2/sources/contracts/2_Owner.sol
* @title Owner @dev Set & change owner/ event for EVM logging modifier to check if caller is owner
contract ReCoinToken { address private owner; event OwnerSet(address indexed oldOwner, address indexed newOwner); modifier isOwner() { require(msg.sender == owner, "Caller is not owner"); _; } constructor() { emit OwnerSet(address(0), owner); } function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } function getOwner() external view returns (address) { return owner; } }
12,374,463
[ 1, 5541, 225, 1000, 473, 2549, 3410, 19, 871, 364, 512, 7397, 2907, 9606, 358, 866, 309, 4894, 353, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 27055, 1345, 288, 203, 203, 565, 1758, 3238, 3410, 31, 203, 377, 203, 565, 871, 16837, 694, 12, 2867, 8808, 1592, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 377, 203, 203, 565, 9606, 353, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 11095, 353, 486, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 3885, 1435, 288, 203, 3639, 3626, 16837, 694, 12, 2867, 12, 20, 3631, 3410, 1769, 203, 565, 289, 203, 203, 565, 445, 2549, 5541, 12, 2867, 394, 5541, 13, 1071, 353, 5541, 288, 203, 3639, 3626, 16837, 694, 12, 8443, 16, 394, 5541, 1769, 203, 3639, 3410, 273, 394, 5541, 31, 203, 565, 289, 203, 203, 565, 445, 13782, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x154DAc76755d2A372804a9C409683F2eeFa9e5e9/sources/lib/tl-sol-tools/src/upgradeable/royalties/EIP2981TLUpgradeable.sol
@inheritdoc ERC165Upgradeable
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable) returns (bool) { return interfaceId == type(IEIP2981).interfaceId || ERC165Upgradeable.supportsInterface(interfaceId); } External View Functions
4,979,380
[ 1, 36, 10093, 4232, 39, 28275, 10784, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 654, 39, 28275, 10784, 429, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 8732, 2579, 5540, 11861, 2934, 5831, 548, 747, 4232, 39, 28275, 10784, 429, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 18701, 11352, 4441, 15486, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xcf2f1d0ae77b7d6ec1e5961978dbfdcce6f007f7 //Contract name: CrowdsaleProxyFactory //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ interface IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() public view returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint); /** * Send `_value` token to `_to` from `msg.sender` * * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint _value) public returns (bool); /** * Send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint _value) public returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) public returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint); } /** * ICrowdsale * * Base crowdsale interface to manage the sale of * an ERC20 token * * #created 09/09/2017 * #author Frank Bonnet */ interface ICrowdsale { /** * Returns true if the contract is currently in the presale phase * * @return True if in presale phase */ function isInPresalePhase() public view returns (bool); /** * Returns true if the contract is currently in the ended stage * * @return True if ended */ function isEnded() public view returns (bool); /** * Returns true if `_beneficiary` has a balance allocated * * @param _beneficiary The account that the balance is allocated for * @param _releaseDate The date after which the balance can be withdrawn * @return True if there is a balance that belongs to `_beneficiary` */ function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool); /** * Get the allocated token balance of `_owner` * * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated token balance */ function balanceOf(address _owner) public view returns (uint); /** * Get the allocated eth balance of `_owner` * * @param _owner The address from which the allocated eth balance will be retrieved * @return The allocated eth balance */ function ethBalanceOf(address _owner) public view returns (uint); /** * Get invested and refundable balance of `_owner` (only contributions during the ICO phase are registered) * * @param _owner The address from which the refundable balance will be retrieved * @return The invested refundable balance */ function refundableEthBalanceOf(address _owner) public view returns (uint); /** * Returns the rate and bonus release date * * @param _phase The phase to use while determining the rate * @param _volume The amount wei used to determine what volume multiplier to use * @return The rate used in `_phase` multiplied by the corresponding volume multiplier */ function getRate(uint _phase, uint _volume) public view returns (uint); /** * Convert `_wei` to an amount in tokens using * the `_rate` * * @param _wei amount of wei to convert * @param _rate rate to use for the conversion * @return Amount in tokens */ function toTokens(uint _wei, uint _rate) public view returns (uint); /** * Receive ether and issue tokens to the sender * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable; /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint); /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint); /** * Withdraw allocated tokens */ function withdrawTokens() public; /** * Withdraw allocated tokens * * @param _beneficiary Address to send to */ function withdrawTokensTo(address _beneficiary) public; /** * Withdraw allocated ether */ function withdrawEther() public; /** * Withdraw allocated ether * * @param _beneficiary Address to send to */ function withdrawEtherTo(address _beneficiary) public; /** * Refund in the case of an unsuccessful crowdsale. The * crowdsale is considered unsuccessful if minAmount was * not raised before end of the crowdsale */ function refund() public; /** * Refund in the case of an unsuccessful crowdsale. The * crowdsale is considered unsuccessful if minAmount was * not raised before end of the crowdsale * * @param _beneficiary Address to send to */ function refundTo(address _beneficiary) public; } /** * Adds to the memory signature of the contract * that contains the code that is called by the * dispatcher */ contract Dispatchable { /** * Target contract that contains the code */ address private target; } /** * The dispatcher is a minimal 'shim' that dispatches calls to a targeted * contract without returning any data. * * Calls are made using 'delegatecall', meaning all storage and value * is kept on the dispatcher. */ contract SimpleDispatcher { /** * Target contract that contains the code */ address private target; /** * Initialize simple dispatcher * * @param _target Contract that holds the code */ function SimpleDispatcher(address _target) public { target = _target; } /** * Execute target code in the context of the dispatcher */ function () public payable { var dest = target; assembly { calldatacopy(0x0, 0x0, calldatasize) switch delegatecall(sub(gas, 10000), dest, 0x0, calldatasize, 0, 0) case 0 { revert(0, 0) } // Throw } } } /** * PersonalCrowdsaleProxy Dispatcher * * #created 31/12/2017 * #author Frank Bonnet */ contract PersonalCrowdsaleProxyDispatcher is SimpleDispatcher { // Target address public targetCrowdsale; address public targetToken; // Owner address public beneficiary; bytes32 private passphraseHash; /** * Deploy personal proxy * * @param _target Target contract to dispach calls to * @param _targetCrowdsale Target crowdsale to invest in * @param _targetToken Token that is bought * @param _passphraseHash Hash of the passphrase */ function PersonalCrowdsaleProxyDispatcher(address _target, address _targetCrowdsale, address _targetToken, bytes32 _passphraseHash) public SimpleDispatcher(_target) { targetCrowdsale = _targetCrowdsale; targetToken = _targetToken; passphraseHash = _passphraseHash; } } /** * ICrowdsaleProxy * * #created 23/11/2017 * #author Frank Bonnet */ interface ICrowdsaleProxy { /** * Receive ether and issue tokens to the sender * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable; /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint); /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint); } /** * CrowdsaleProxy * * #created 22/11/2017 * #author Frank Bonnet */ contract CrowdsaleProxy is ICrowdsaleProxy { address public owner; ICrowdsale public target; /** * Deploy proxy * * @param _owner Owner of the proxy * @param _target Target crowdsale */ function CrowdsaleProxy(address _owner, address _target) public { target = ICrowdsale(_target); owner = _owner; } /** * Receive contribution and forward to the crowdsale * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) */ function () public payable { target.contributeFor.value(msg.value)(msg.sender); } /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint) { target.contributeFor.value(msg.value)(msg.sender); } /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint) { target.contributeFor.value(msg.value)(_beneficiary); } } /** * IPersonalCrowdsaleProxy * * #created 22/11/2017 * #author Frank Bonnet */ interface IPersonalCrowdsaleProxy { /** * Receive ether to forward to the target crowdsale */ function () public payable; /** * Invest received ether in target crowdsale */ function invest() public; /** * Request a refund from the target crowdsale */ function refund() public; /** * Request outstanding token balance from the * target crowdsale */ function updateTokenBalance() public; /** * Transfer token balance to beneficiary */ function withdrawTokens() public; /** * Request outstanding ether balance from the * target crowdsale */ function updateEtherBalance() public; /** * Transfer ether balance to beneficiary */ function withdrawEther() public; } /** * PersonalCrowdsaleProxy * * #created 31/12/2017 * #author Frank Bonnet */ contract PersonalCrowdsaleProxy is IPersonalCrowdsaleProxy, Dispatchable { // Target ICrowdsale public targetCrowdsale; IToken public targetToken; // Owner address public beneficiary; bytes32 private passphraseHash; /** * Restrict call access to when the beneficiary * address is known */ modifier when_beneficiary_is_known() { require(beneficiary != address(0)); _; } /** * Restrict call access to when the beneficiary * address is unknown */ modifier when_beneficiary_is_unknown() { require(beneficiary == address(0)); _; } /** * Set the beneficiary account. Tokens and ether will be send * to this address * * @param _beneficiary The address to receive tokens and ether * @param _passphrase The raw passphrasse */ function setBeneficiary(address _beneficiary, bytes32 _passphrase) public when_beneficiary_is_unknown { require(keccak256(_passphrase) == passphraseHash); beneficiary = _beneficiary; } /** * Receive ether to forward to the target crowdsale */ function () public payable { // Just receive ether } /** * Invest received ether in target crowdsale */ function invest() public { targetCrowdsale.contribute.value(this.balance)(); } /** * Request a refund from the target crowdsale */ function refund() public { targetCrowdsale.refund(); } /** * Request outstanding token balance from the * target crowdsale */ function updateTokenBalance() public { targetCrowdsale.withdrawTokens(); } /** * Transfer token balance to beneficiary */ function withdrawTokens() public when_beneficiary_is_known { uint balance = targetToken.balanceOf(this); targetToken.transfer(beneficiary, balance); } /** * Request outstanding ether balance from the * target crowdsale */ function updateEtherBalance() public { targetCrowdsale.withdrawEther(); } /** * Transfer ether balance to beneficiary */ function withdrawEther() public when_beneficiary_is_known { beneficiary.transfer(this.balance); } } /** * CrowdsaleProxyFactory * * #created 21/12/2017 * #author Frank Bonnet */ contract CrowdsaleProxyFactory { // Target address public targetCrowdsale; address public targetToken; // Dispatch target address private personalCrowdsaleProxyTarget; // Events event ProxyCreated(address proxy, address beneficiary); /** * Deploy factory * * @param _targetCrowdsale Target crowdsale to invest in * @param _targetToken Token that is bought */ function CrowdsaleProxyFactory(address _targetCrowdsale, address _targetToken) public { targetCrowdsale = _targetCrowdsale; targetToken = _targetToken; personalCrowdsaleProxyTarget = new PersonalCrowdsaleProxy(); } /** * Deploy a contract that serves as a proxy to * the target crowdsale * * @return The address of the deposit address */ function createProxyAddress() public returns (address) { address proxy = new CrowdsaleProxy(msg.sender, targetCrowdsale); ProxyCreated(proxy, msg.sender); return proxy; } /** * Deploy a contract that serves as a proxy to * the target crowdsale * * @param _beneficiary The owner of the proxy * @return The address of the deposit address */ function createProxyAddressFor(address _beneficiary) public returns (address) { address proxy = new CrowdsaleProxy(_beneficiary, targetCrowdsale); ProxyCreated(proxy, _beneficiary); return proxy; } /** * Deploy a contract that serves as a proxy to * the target crowdsale * * Contributions through this address will be made * for the person that knows the passphrase * * @param _passphraseHash Hash of the passphrase * @return The address of the deposit address */ function createPersonalDepositAddress(bytes32 _passphraseHash) public returns (address) { address proxy = new PersonalCrowdsaleProxyDispatcher( personalCrowdsaleProxyTarget, targetCrowdsale, targetToken, _passphraseHash); ProxyCreated(proxy, msg.sender); return proxy; } /** * Deploy a contract that serves as a proxy to * the target crowdsale * * Contributions through this address will be made * for `_beneficiary` * * @param _beneficiary The owner of the proxy * @return The address of the deposit address */ function createPersonalDepositAddressFor(address _beneficiary) public returns (address) { PersonalCrowdsaleProxy proxy = PersonalCrowdsaleProxy(new PersonalCrowdsaleProxyDispatcher( personalCrowdsaleProxyTarget, targetCrowdsale, targetToken, keccak256(bytes32(_beneficiary)))); proxy.setBeneficiary(_beneficiary, bytes32(_beneficiary)); ProxyCreated(proxy, _beneficiary); return proxy; } }
* Invest received ether in target crowdsale/
function invest() public { targetCrowdsale.contribute.value(this.balance)(); }
909,111
[ 1, 3605, 395, 5079, 225, 2437, 316, 1018, 276, 492, 2377, 5349, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2198, 395, 1435, 1071, 288, 203, 3639, 1018, 39, 492, 2377, 5349, 18, 591, 887, 18, 1132, 12, 2211, 18, 12296, 13, 5621, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xdD09fD24f5a00E1047681DF5404a38504d4793a5/sources/contracts/buy.sol
address cryptoToken = 0x9695e0114e12C0d3A3636fAb5A18e6b737529023; dfyn address1 gwei = .000000001 ETH. So 0.1 ETH would be 10000000 gwei. Try this.so i'm trying to trade 0.1 ETH for at least 150 DAI, here. 400 = about 5 minutes msg.value, I THINK, is what we put into the VALUE box and is the number of eth to swap for tokens. no need to refund ETH
function buyTokenWithExactEth() public payable returns(uint256) { return 1000; }
16,233,053
[ 1, 2867, 8170, 1345, 273, 374, 92, 29, 8148, 25, 73, 1611, 3461, 73, 2138, 39, 20, 72, 23, 37, 23, 4449, 26, 74, 5895, 25, 37, 2643, 73, 26, 70, 9036, 5877, 5540, 3103, 23, 31, 3013, 878, 1758, 21, 314, 1814, 77, 273, 263, 12648, 21, 512, 2455, 18, 6155, 374, 18, 21, 512, 2455, 4102, 506, 2130, 11706, 314, 1814, 77, 18, 6161, 333, 18, 2048, 277, 17784, 8374, 358, 18542, 374, 18, 21, 512, 2455, 364, 622, 4520, 18478, 463, 18194, 16, 2674, 18, 7409, 273, 2973, 1381, 6824, 1234, 18, 1132, 16, 467, 7662, 8476, 16, 353, 4121, 732, 1378, 1368, 326, 5848, 3919, 471, 353, 326, 1300, 434, 13750, 358, 7720, 364, 2430, 18, 1158, 1608, 358, 16255, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1345, 1190, 14332, 41, 451, 1435, 1071, 8843, 429, 1135, 12, 11890, 5034, 13, 288, 203, 2398, 203, 377, 203, 377, 203, 5411, 327, 4336, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ReserveStabilizer.sol"; import "./ITribeReserveStabilizer.sol"; import "../dao/ITribeMinter.sol"; import "../utils/Timed.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @title implementation for a TRIBE Reserve Stabilizer /// @author Fei Protocol contract TribeReserveStabilizer is ITribeReserveStabilizer, ReserveStabilizer, Timed { using Decimal for Decimal.D256; /// @notice a collateralization oracle ICollateralizationOracle public override collateralizationOracle; /// @notice the TRIBE minter address ITribeMinter public immutable tribeMinter; Decimal.D256 private _collateralizationThreshold; /// @notice Tribe Reserve Stabilizer constructor /// @param _core Fei Core to reference /// @param _tribeOracle the TRIBE price oracle to reference /// @param _backupOracle the backup oracle to reference /// @param _usdPerFeiBasisPoints the USD price per FEI to sell TRIBE at /// @param _collateralizationOracle the collateralization oracle to reference /// @param _collateralizationThresholdBasisPoints the collateralization ratio below which the stabilizer becomes active. Reported in basis points (1/10000) /// @param _tribeMinter the tribe minter contract /// @param _osmDuration the amount of delay time before the TribeReserveStabilizer begins minting TRIBE constructor( address _core, address _tribeOracle, address _backupOracle, uint256 _usdPerFeiBasisPoints, ICollateralizationOracle _collateralizationOracle, uint256 _collateralizationThresholdBasisPoints, ITribeMinter _tribeMinter, uint256 _osmDuration ) ReserveStabilizer(_core, _tribeOracle, _backupOracle, IERC20(address(0)), _usdPerFeiBasisPoints) Timed(_osmDuration) { collateralizationOracle = _collateralizationOracle; emit CollateralizationOracleUpdate(address(0), address(_collateralizationOracle)); _collateralizationThreshold = Decimal.ratio(_collateralizationThresholdBasisPoints, Constants.BASIS_POINTS_GRANULARITY); emit CollateralizationThresholdUpdate(0, _collateralizationThresholdBasisPoints); // Setting token here because it isn't available until after CoreRef is constructed // This does skip the _setDecimalsNormalizerFromToken call in ReserveStabilizer constructor, but it isn't needed because TRIBE is 18 decimals token = tribe(); tribeMinter = _tribeMinter; } /// @notice exchange FEI for minted TRIBE /// @dev the timer counts down from first time below threshold and opens after window function exchangeFei(uint256 feiAmount) public override afterTime returns(uint256) { require(isCollateralizationBelowThreshold(), "TribeReserveStabilizer: Collateralization ratio above threshold"); return super.exchangeFei(feiAmount); } /// @dev reverts. Held TRIBE should only be released by exchangeFei or mint function withdraw(address, uint256) external pure override { revert("TribeReserveStabilizer: can't withdraw TRIBE"); } /// @notice check whether collateralization ratio is below the threshold set /// @dev returns false if the oracle is invalid function isCollateralizationBelowThreshold() public override view returns(bool) { (Decimal.D256 memory ratio, bool valid) = collateralizationOracle.read(); return valid && ratio.lessThanOrEqualTo(_collateralizationThreshold); } /// @notice delay the opening of the TribeReserveStabilizer until oracle delay duration is met function startOracleDelayCountdown() external override { require(isCollateralizationBelowThreshold(), "TribeReserveStabilizer: Collateralization ratio above threshold"); require(!isTimeStarted(), "TribeReserveStabilizer: timer started"); _initTimed(); } /// @notice reset the opening of the TribeReserveStabilizer oracle delay as soon as above CR target function resetOracleDelayCountdown() external override { require(!isCollateralizationBelowThreshold(), "TribeReserveStabilizer: Collateralization ratio under threshold"); require(isTimeStarted(), "TribeReserveStabilizer: timer started"); _pauseTimer(); } /// @notice set the Collateralization oracle function setCollateralizationOracle(ICollateralizationOracle newCollateralizationOracle) external override onlyGovernor { require(address(newCollateralizationOracle) != address(0), "TribeReserveStabilizer: zero address"); address oldCollateralizationOracle = address(collateralizationOracle); collateralizationOracle = newCollateralizationOracle; emit CollateralizationOracleUpdate(oldCollateralizationOracle, address(newCollateralizationOracle)); } /// @notice set the collateralization threshold below which exchanging becomes active function setCollateralizationThreshold(uint256 newCollateralizationThresholdBasisPoints) external override onlyGovernor { uint256 oldCollateralizationThresholdBasisPoints = _collateralizationThreshold.mul(Constants.BASIS_POINTS_GRANULARITY).asUint256(); _collateralizationThreshold = Decimal.ratio(newCollateralizationThresholdBasisPoints, Constants.BASIS_POINTS_GRANULARITY); emit CollateralizationThresholdUpdate(oldCollateralizationThresholdBasisPoints, newCollateralizationThresholdBasisPoints); } /// @notice the collateralization threshold below which exchanging becomes active function collateralizationThreshold() external view override returns(Decimal.D256 memory) { return _collateralizationThreshold; } // Call out to TRIBE minter for transferring function _transfer(address to, uint256 amount) internal override { tribeMinter.mint(to, amount); } function _pauseTimer() internal { // setting start time to 0 means isTimeStarted is false startTime = 0; emit TimerReset(0); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IReserveStabilizer.sol"; import "../pcv/PCVDeposit.sol"; import "../refs/OracleRef.sol"; import "../Constants.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title implementation for an ERC20 Reserve Stabilizer /// @author Fei Protocol contract ReserveStabilizer is OracleRef, IReserveStabilizer, PCVDeposit { using Decimal for Decimal.D256; /// @notice the USD per FEI exchange rate denominated in basis points (1/10000) uint256 public override usdPerFeiBasisPoints; /// @notice the ERC20 token exchanged on this stablizer IERC20 public token; /// @notice ERC20 Reserve Stabilizer constructor /// @param _core Fei Core to reference /// @param _oracle the price oracle to reference /// @param _backupOracle the backup oracle to reference /// @param _token the ERC20 token for this stabilizer, 0x0 if TRIBE or ETH /// @param _usdPerFeiBasisPoints the USD price per FEI to sell tokens at constructor( address _core, address _oracle, address _backupOracle, IERC20 _token, uint256 _usdPerFeiBasisPoints ) OracleRef( _core, _oracle, _backupOracle, 0, // default to zero for ETH and TRIBE which both have 18 decimals true // invert the price oracle, as the operation performed here needs to convert FEI into underlying ) { require(_usdPerFeiBasisPoints <= Constants.BASIS_POINTS_GRANULARITY, "ReserveStabilizer: Exceeds bp granularity"); usdPerFeiBasisPoints = _usdPerFeiBasisPoints; emit UsdPerFeiRateUpdate(0, _usdPerFeiBasisPoints); token = _token; if (address(_token) != address(0)) { _setDecimalsNormalizerFromToken(address(_token)); } } /// @notice exchange FEI for tokens from the reserves /// @param feiAmount of FEI to sell function exchangeFei(uint256 feiAmount) public virtual override whenNotPaused returns (uint256 amountOut) { updateOracle(); fei().transferFrom(msg.sender, address(this), feiAmount); _burnFeiHeld(); amountOut = getAmountOut(feiAmount); _transfer(msg.sender, amountOut); emit FeiExchange(msg.sender, feiAmount, amountOut); } /// @notice returns the amount out of tokens from the reserves for a given amount of FEI /// @param amountFeiIn the amount of FEI in function getAmountOut(uint256 amountFeiIn) public view override returns(uint256) { uint256 adjustedAmountIn = amountFeiIn * usdPerFeiBasisPoints / Constants.BASIS_POINTS_GRANULARITY; return readOracle().mul(adjustedAmountIn).asUint256(); } /// @notice withdraw tokens from the reserves /// @param to address to send tokens /// @param amountOut amount of tokens to send function withdraw(address to, uint256 amountOut) external virtual override onlyPCVController { _transfer(to, amountOut); emit Withdrawal(msg.sender, to, amountOut); } /// @notice new PCV deposited to the stabilizer /// @dev no-op because the token transfer already happened function deposit() external override virtual {} /// @notice returns the amount of the held ERC-20 function balance() public view override virtual returns(uint256) { return token.balanceOf(address(this)); } /// @notice display the related token of the balance reported function balanceReportedIn() public view override returns (address) { return address(token); } /// @notice sets the USD per FEI exchange rate rate /// @param newUsdPerFeiBasisPoints the USD per FEI exchange rate denominated in basis points (1/10000) function setUsdPerFeiRate(uint256 newUsdPerFeiBasisPoints) external override onlyGovernorOrAdmin { require(newUsdPerFeiBasisPoints <= Constants.BASIS_POINTS_GRANULARITY, "ReserveStabilizer: Exceeds bp granularity"); uint256 oldUsdPerFeiBasisPoints = usdPerFeiBasisPoints; usdPerFeiBasisPoints = newUsdPerFeiBasisPoints; emit UsdPerFeiRateUpdate(oldUsdPerFeiBasisPoints, newUsdPerFeiBasisPoints); } function _transfer(address to, uint256 amount) internal virtual { SafeERC20.safeTransfer(IERC20(token), to, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a Reserve Stabilizer interface /// @author Fei Protocol interface IReserveStabilizer { // ----------- Events ----------- event FeiExchange(address indexed to, uint256 feiAmountIn, uint256 amountOut); event UsdPerFeiRateUpdate(uint256 oldUsdPerFeiBasisPoints, uint256 newUsdPerFeiBasisPoints); // ----------- State changing api ----------- function exchangeFei(uint256 feiAmount) external returns (uint256); // ----------- Governor only state changing api ----------- function setUsdPerFeiRate(uint256 exchangeRateBasisPoints) external; // ----------- Getters ----------- function usdPerFeiBasisPoints() external view returns (uint256); function getAmountOut(uint256 amountIn) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "./IPCVDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller /// @author Fei Protocol abstract contract PCVDeposit is IPCVDeposit, CoreRef { using SafeERC20 for IERC20; /// @notice withdraw ERC20 from the contract /// @param token address of the ERC20 to send /// @param to address destination of the ERC20 /// @param amount quantity of ERC20 to send function withdrawERC20( address token, address to, uint256 amount ) public virtual override onlyPCVController { _withdrawERC20(token, to, amount); } function _withdrawERC20( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); emit WithdrawERC20(msg.sender, token, to, amount); } /// @notice withdraw ETH from the contract /// @param to address to send ETH /// @param amountOut amount of ETH to send function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController { Address.sendValue(to, amountOut); emit WithdrawETH(msg.sender, to, amountOut); } function balance() public view virtual override returns(uint256); function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) { return (balance(), 0); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; /// @notice boolean to check whether or not the contract has been initialized. /// cannot be initialized twice. bool private _initialized; constructor(address coreAddress) { _initialize(coreAddress); } /// @notice CoreRef constructor /// @param coreAddress Fei Core to reference function _initialize(address coreAddress) internal { require(!_initialized, "CoreRef: already initialized"); _initialized = true; _core = ICore(coreAddress); _setContractAdminRole(_core.GOVERN_ROLE()); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin"); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } /// @notice set new Core reference address /// @param newCore the new core address function setCore(address newCore) external override onlyGovernor { require(newCore != address(0), "CoreRef: zero address"); address oldCore = address(_core); _core = ICore(newCore); emit CoreUpdate(oldCore, newCore); } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { fei().mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setCore(address newCore) external; function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../token/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPCVDepositBalances.sol"; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit is IPCVDepositBalances { // ----------- Events ----------- event Deposit(address indexed _from, uint256 _amount); event Withdrawal( address indexed _caller, address indexed _to, uint256 _amount ); event WithdrawERC20( address indexed _caller, address indexed _token, address indexed _to, uint256 _amount ); event WithdrawETH( address indexed _caller, address indexed _to, uint256 _amount ); // ----------- State changing api ----------- function deposit() external; // ----------- PCV Controller only state changing api ----------- function withdraw(address to, uint256 amount) external; function withdrawERC20(address token, address to, uint256 amount) external; function withdrawETH(address payable to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a PCV Deposit interface for only balance getters /// @author Fei Protocol interface IPCVDepositBalances { // ----------- Getters ----------- /// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn function balance() external view returns (uint256); /// @notice gets the token address in which this deposit returns its balance function balanceReportedIn() external view returns (address); /// @notice gets the resistant token balance and protocol owned fei of this deposit function resistantBalanceAndFei() external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IOracleRef.sol"; import "./CoreRef.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /// @title Reference to an Oracle /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; using SafeCast for int256; /// @notice the oracle reference by the contract IOracle public override oracle; /// @notice the backup oracle reference by the contract IOracle public override backupOracle; /// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer) int256 public override decimalsNormalizer; bool public override doInvert; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference /// @param _backupOracle backup oracle to reference /// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary /// @param _doInvert invert the oracle price if this flag is on constructor(address _core, address _oracle, address _backupOracle, int256 _decimalsNormalizer, bool _doInvert) CoreRef(_core) { _setOracle(_oracle); if (_backupOracle != address(0) && _backupOracle != _oracle) { _setBackupOracle(_backupOracle); } _setDoInvert(_doInvert); _setDecimalsNormalizer(_decimalsNormalizer); } /// @notice sets the referenced oracle /// @param newOracle the new oracle to reference function setOracle(address newOracle) external override onlyGovernor { _setOracle(newOracle); } /// @notice sets the flag for whether to invert or not /// @param newDoInvert the new flag for whether to invert function setDoInvert(bool newDoInvert) external override onlyGovernor { _setDoInvert(newDoInvert); } /// @notice sets the new decimalsNormalizer /// @param newDecimalsNormalizer the new decimalsNormalizer function setDecimalsNormalizer(int256 newDecimalsNormalizer) external override onlyGovernor { _setDecimalsNormalizer(newDecimalsNormalizer); } /// @notice sets the referenced backup oracle /// @param newBackupOracle the new backup oracle to reference function setBackupOracle(address newBackupOracle) external override onlyGovernorOrAdmin { _setBackupOracle(newBackupOracle); } /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 memory price) public pure override returns (Decimal.D256 memory) { return Decimal.one().div(price); } /// @notice updates the referenced oracle function updateOracle() public override { oracle.update(); } /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function readOracle() public view override returns (Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); if (!valid && address(backupOracle) != address(0)) { (_peg, valid) = backupOracle.read(); } require(valid, "OracleRef: oracle invalid"); // Scale the oracle price by token decimals delta if necessary uint256 scalingFactor; if (decimalsNormalizer < 0) { scalingFactor = 10 ** (-1 * decimalsNormalizer).toUint256(); _peg = _peg.div(scalingFactor); } else { scalingFactor = 10 ** decimalsNormalizer.toUint256(); _peg = _peg.mul(scalingFactor); } // Invert the oracle price if necessary if (doInvert) { _peg = invert(_peg); } return _peg; } function _setOracle(address newOracle) internal { require(newOracle != address(0), "OracleRef: zero address"); address oldOracle = address(oracle); oracle = IOracle(newOracle); emit OracleUpdate(oldOracle, newOracle); } // Supports zero address if no backup function _setBackupOracle(address newBackupOracle) internal { address oldBackupOracle = address(backupOracle); backupOracle = IOracle(newBackupOracle); emit BackupOracleUpdate(oldBackupOracle, newBackupOracle); } function _setDoInvert(bool newDoInvert) internal { bool oldDoInvert = doInvert; doInvert = newDoInvert; if (oldDoInvert != newDoInvert) { _setDecimalsNormalizer( -1 * decimalsNormalizer); } emit InvertUpdate(oldDoInvert, newDoInvert); } function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal { int256 oldDecimalsNormalizer = decimalsNormalizer; decimalsNormalizer = newDecimalsNormalizer; emit DecimalsNormalizerUpdate(oldDecimalsNormalizer, newDecimalsNormalizer); } function _setDecimalsNormalizerFromToken(address token) internal { int256 feiDecimals = 18; int256 _decimalsNormalizer = feiDecimals - int256(uint256(IERC20Metadata(token).decimals())); if (doInvert) { _decimalsNormalizer = -1 * _decimalsNormalizer; } _setDecimalsNormalizer(_decimalsNormalizer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../oracle/IOracle.sol"; /// @title OracleRef interface /// @author Fei Protocol interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed oldOracle, address indexed newOracle); event InvertUpdate(bool oldDoInvert, bool newDoInvert); event DecimalsNormalizerUpdate(int256 oldDecimalsNormalizer, int256 newDecimalsNormalizer); event BackupOracleUpdate(address indexed oldBackupOracle, address indexed newBackupOracle); // ----------- State changing API ----------- function updateOracle() external; // ----------- Governor only state changing API ----------- function setOracle(address newOracle) external; function setBackupOracle(address newBackupOracle) external; function setDecimalsNormalizer(int256 newDecimalsNormalizer) external; function setDoInvert(bool newDoInvert) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function backupOracle() external view returns (IOracle); function doInvert() external view returns (bool); function decimalsNormalizer() external view returns (int256); function readOracle() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; library Constants { /// @notice the denominator for basis points granularity (10,000) uint256 public constant BASIS_POINTS_GRANULARITY = 10_000; uint256 public constant ONE_YEAR = 365.25 days; /// @notice WETH9 address IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice USD stand-in address address public constant USD = 0x1111111111111111111111111111111111111111; /// @notice Wei per ETH, i.e. 10**18 uint256 public constant ETH_GRANULARITY = 1e18; /// @notice number of decimals in ETH, 18 uint256 public constant ETH_DECIMALS = 18; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../oracle/collateralization/ICollateralizationOracle.sol"; /// @title a Tribe Reserve Stabilizer interface /// @author Fei Protocol interface ITribeReserveStabilizer { // ----------- Events ----------- event CollateralizationOracleUpdate(address indexed oldCollateralizationOracle, address indexed newCollateralizationOracle); event CollateralizationThresholdUpdate(uint256 oldCollateralizationThresholdBasisPoints, uint256 newCollateralizationThresholdBasisPoints); // ----------- Governor only state changing api ----------- function setCollateralizationOracle(ICollateralizationOracle newCollateralizationOracle) external; function setCollateralizationThreshold(uint256 newCollateralizationThresholdBasisPoints) external; function startOracleDelayCountdown() external; function resetOracleDelayCountdown() external; // ----------- Getters ----------- function isCollateralizationBelowThreshold() external view returns (bool); function collateralizationOracle() external view returns (ICollateralizationOracle); function collateralizationThreshold() external view returns (Decimal.D256 calldata); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../IOracle.sol"; /// @title Collateralization ratio oracle interface for Fei Protocol /// @author Fei Protocol interface ICollateralizationOracle is IOracle { // ----------- Getters ----------- // returns the PCV value, User-circulating FEI, and Protocol Equity, as well // as a validity status. function pcvStats() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); // true if Protocol Equity > 0 function isOvercollateralized() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ITribe is IERC20 { function mint(address to, uint256 amount) external; function setMinter(address newMinter) external; } /// @title TribeMinter interface /// @author Fei Protocol interface ITribeMinter { // ----------- Events ----------- event AnnualMaxInflationUpdate(uint256 oldAnnualMaxInflationBasisPoints, uint256 newAnnualMaxInflationBasisPoints); event TribeTreasuryUpdate(address indexed oldTribeTreasury, address indexed newTribeTreasury); event TribeRewardsDripperUpdate(address indexed oldTribeRewardsDripper, address indexed newTribeRewardsDripper); // ----------- Public state changing api ----------- function poke() external; // ----------- Owner only state changing api ----------- function setMinter(address newMinter) external; // ----------- Governor or Admin only state changing api ----------- function mint(address to, uint256 amount) external; function setTribeTreasury(address newTribeTreasury) external; function setTribeRewardsDripper(address newTribeRewardsDripper) external; function setAnnualMaxInflationBasisPoints(uint256 newAnnualMaxInflationBasisPoints) external; // ----------- Getters ----------- function annualMaxInflationBasisPoints() external view returns (uint256); function idealBufferCap() external view returns (uint256); function tribeCirculatingSupply() external view returns (uint256); function totalSupply() external view returns (uint256); function isPokeNeeded() external view returns (bool); function tribeTreasury() external view returns (address); function tribeRewardsDripper() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title an abstract contract for timed events /// @author Fei Protocol abstract contract Timed { /// @notice the start timestamp of the timed period uint256 public startTime; /// @notice the duration of the timed period uint256 public duration; event DurationUpdate(uint256 oldDuration, uint256 newDuration); event TimerReset(uint256 startTime); constructor(uint256 _duration) { _setDuration(_duration); } modifier duringTime() { require(isTimeStarted(), "Timed: time not started"); require(!isTimeEnded(), "Timed: time ended"); _; } modifier afterTime() { require(isTimeEnded(), "Timed: time not ended"); _; } /// @notice return true if time period has ended function isTimeEnded() public view returns (bool) { return remainingTime() == 0; } /// @notice number of seconds remaining until time is up /// @return remaining function remainingTime() public view returns (uint256) { return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d] } /// @notice number of seconds since contract was initialized /// @return timestamp /// @dev will be less than or equal to duration function timeSinceStart() public view returns (uint256) { if (!isTimeStarted()) { return 0; // uninitialized } uint256 _duration = duration; uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime return timePassed > _duration ? _duration : timePassed; } function isTimeStarted() public view returns (bool) { return startTime != 0; } function _initTimed() internal { startTime = block.timestamp; emit TimerReset(block.timestamp); } function _setDuration(uint256 newDuration) internal { require(newDuration != 0, "Timed: zero duration"); uint256 oldDuration = duration; duration = newDuration; emit DurationUpdate(oldDuration, newDuration); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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 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.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 override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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.0 (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.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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 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.0 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; }
@notice exchange FEI for tokens from the reserves @param feiAmount of FEI to sell
function exchangeFei(uint256 feiAmount) public virtual override whenNotPaused returns (uint256 amountOut) { updateOracle(); fei().transferFrom(msg.sender, address(this), feiAmount); _burnFeiHeld(); amountOut = getAmountOut(feiAmount); _transfer(msg.sender, amountOut); emit FeiExchange(msg.sender, feiAmount, amountOut); }
10,003,102
[ 1, 16641, 16439, 45, 364, 2430, 628, 326, 400, 264, 3324, 225, 1656, 77, 6275, 434, 16439, 45, 358, 357, 80, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7829, 2954, 77, 12, 11890, 5034, 1656, 77, 6275, 13, 1071, 5024, 3849, 1347, 1248, 28590, 1135, 261, 11890, 5034, 3844, 1182, 13, 288, 203, 3639, 1089, 23601, 5621, 203, 203, 3639, 1656, 77, 7675, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 1656, 77, 6275, 1769, 203, 3639, 389, 70, 321, 2954, 77, 44, 488, 5621, 203, 203, 3639, 3844, 1182, 273, 24418, 1182, 12, 3030, 77, 6275, 1769, 203, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 3844, 1182, 1769, 203, 3639, 3626, 5782, 77, 11688, 12, 3576, 18, 15330, 16, 1656, 77, 6275, 16, 3844, 1182, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xD567f218D0a4151Ae2Bc08B969AA90B0D9401fD7/sources/StrategyGg1LPV2.sol
* @dev Implementation of a strategy to get yields from farming LP Pools in PancakeSwap. PancakeSwap is an automated market maker (“AMM”) that allows two tokens to be exchanged on the Binance Smart Chain. It is fast, cheap, and allows anyone to participate. PancakeSwap is aiming to be the #1 liquidity provider on BSC. This strategy simply deposits whatever funds it receives from the vault into the selected ShareRewardPool pool. gg1 rewards from providing liquidity are farmed every few minutes, sold and split 50/50. The corresponding pair of assets are bought and more liquidity is added to the ShareRewardPool pool. This strat is currently compatible with all LP pools./
contract StrategyGg1LPV2 is Ownable, Pausable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; mapping(address => bool) public odioList; IERC20 flp = IERC20(address(0x87ff96aba480f1813aF5c780387d8De7cf7D8261)); address public constant gg1 = address(0xa41497122BB9B9EB2EB1c5c872551e145bC3166B); address public constant wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant busd = address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56); address public lpPair; address public lpToken0; address public lpToken1; address public constant unirouter = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); address public constant shareRewardPool = address(0x22cC57c9ec341152834F216289A1824d61b47855); uint8 public poolId; address public constant treasury = address(0xD54307a8edfa93b1794861F091C714d752400D13); address public vault; uint256 public constant WITHDRAWAL_FEE = 10; uint256 public constant WITHDRAWAL_MAX = 10000; uint256 public _callFee; uint256 public _treasurySup; uint256 public flpToHarvest; address[] public gg1ToWbnbRoute = [gg1, wbnb]; address[] public gg1ToLp0Route; address[] public gg1ToLp1Route; address[] public Lp0ToLp1Route; address[] public Lp1ToLp0Route; event StratHarvest(address indexed harvester); constructor( address _lpPair, uint8 _poolId, address _vault ) public { lpPair = _lpPair; lpToken0 = IPancakePair(lpPair).token0(); lpToken1 = IPancakePair(lpPair).token1(); poolId = _poolId; vault = _vault; _callFee = 25; _treasurySup = 75; flpToHarvest = 0; gasPermitido = 10000000000; if (lpToken0 == wbnb) { gg1ToLp0Route = [gg1, wbnb]; gg1ToLp0Route = [gg1, wbnb, lpToken0]; } if (lpToken1 == wbnb) { gg1ToLp1Route = [gg1, wbnb]; gg1ToLp1Route = [gg1, wbnb, lpToken1]; } Lp0ToLp1Route = [lpToken0, lpToken1]; Lp1ToLp0Route = [lpToken1, lpToken0]; IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1)); IERC20(gg1).safeApprove(unirouter, uint256(-1)); IERC20(wbnb).safeApprove(unirouter, uint256(-1)); IERC20(busd).safeApprove(unirouter, uint256(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint256(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint256(-1)); } ) public { lpPair = _lpPair; lpToken0 = IPancakePair(lpPair).token0(); lpToken1 = IPancakePair(lpPair).token1(); poolId = _poolId; vault = _vault; _callFee = 25; _treasurySup = 75; flpToHarvest = 0; gasPermitido = 10000000000; if (lpToken0 == wbnb) { gg1ToLp0Route = [gg1, wbnb]; gg1ToLp0Route = [gg1, wbnb, lpToken0]; } if (lpToken1 == wbnb) { gg1ToLp1Route = [gg1, wbnb]; gg1ToLp1Route = [gg1, wbnb, lpToken1]; } Lp0ToLp1Route = [lpToken0, lpToken1]; Lp1ToLp0Route = [lpToken1, lpToken0]; IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1)); IERC20(gg1).safeApprove(unirouter, uint256(-1)); IERC20(wbnb).safeApprove(unirouter, uint256(-1)); IERC20(busd).safeApprove(unirouter, uint256(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint256(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint256(-1)); } } else if (lpToken0 != gg1) { ) public { lpPair = _lpPair; lpToken0 = IPancakePair(lpPair).token0(); lpToken1 = IPancakePair(lpPair).token1(); poolId = _poolId; vault = _vault; _callFee = 25; _treasurySup = 75; flpToHarvest = 0; gasPermitido = 10000000000; if (lpToken0 == wbnb) { gg1ToLp0Route = [gg1, wbnb]; gg1ToLp0Route = [gg1, wbnb, lpToken0]; } if (lpToken1 == wbnb) { gg1ToLp1Route = [gg1, wbnb]; gg1ToLp1Route = [gg1, wbnb, lpToken1]; } Lp0ToLp1Route = [lpToken0, lpToken1]; Lp1ToLp0Route = [lpToken1, lpToken0]; IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1)); IERC20(gg1).safeApprove(unirouter, uint256(-1)); IERC20(wbnb).safeApprove(unirouter, uint256(-1)); IERC20(busd).safeApprove(unirouter, uint256(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint256(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint256(-1)); } } else if (lpToken1 != gg1) { modifier noEsOdiado() { require(odioList[msg.sender] == false, "Juira!"); _; } function teOdio(address _address, bool _odio) public onlyOwner { odioList[_address] = _odio; } function setGasPermitido(uint256 _priceGas) public onlyOwner { gasPermitido = _priceGas; } function setflpToHarvest(uint256 _flpToHarvest) public onlyOwner { flpToHarvest = _flpToHarvest; } function deposit() public whenNotPaused { uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); if (pairBal > 0) { IShareRewardPool(shareRewardPool).deposit( poolId, pairBal ); } } function deposit() public whenNotPaused { uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); if (pairBal > 0) { IShareRewardPool(shareRewardPool).deposit( poolId, pairBal ); } } function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); if (pairBal < _amount) { IShareRewardPool(shareRewardPool).withdraw( poolId, _amount.sub(pairBal) ); pairBal = IERC20(lpPair).balanceOf(address(this)); pairBal = _amount; } uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX); IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee)); } function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); if (pairBal < _amount) { IShareRewardPool(shareRewardPool).withdraw( poolId, _amount.sub(pairBal) ); pairBal = IERC20(lpPair).balanceOf(address(this)); pairBal = _amount; } uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX); IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee)); } } else { function harvest() external whenNotPaused noEsOdiado { require( flp.balanceOf(msg.sender) >= flpToHarvest, "You need more falopa in your life" ); require(tx.gasprice <= gasPermitido, "Respeta el orden de la fila!"); require(!Address.isContract(msg.sender), "!contract"); IShareRewardPool(shareRewardPool).deposit(poolId, 0); chargeFees(); addLiquidity(); deposit(); emit StratHarvest(msg.sender); } function setperfomFee(uint256 _newCallFee, uint256 _newTreasurySup) public onlyOwner { require(_newCallFee.add(_newTreasurySup) == 100, "!100%"); require(_newCallFee > 0 && _newTreasurySup > 0, "must be > 0"); _callFee = _newCallFee; _treasurySup = _newTreasurySup; } function chargeFees() internal { uint256 toWbnb = IERC20(gg1).balanceOf(address(this)).mul(40).div(1000); IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( toWbnb, 0, gg1ToWbnbRoute, address(this), now.add(600) ); uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this)); uint256 callFee = wbnbBal.mul(_callFee).div(100); IERC20(wbnb).safeTransfer(msg.sender, callFee); uint256 treasurySup = wbnbBal.mul(_treasurySup).div(100); IERC20(wbnb).safeTransfer(treasury, treasurySup); } function addLiquidity() internal { uint256 gg1Half = IERC20(gg1).balanceOf(address(this)).div(2); if (lpToken0 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp0Route, address(this), now.add(600) ); } if (lpToken1 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp1Route, address(this), now.add(600) ); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IPancakeRouter(unirouter).addLiquidity( lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600) ); } function addLiquidity() internal { uint256 gg1Half = IERC20(gg1).balanceOf(address(this)).div(2); if (lpToken0 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp0Route, address(this), now.add(600) ); } if (lpToken1 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp1Route, address(this), now.add(600) ); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IPancakeRouter(unirouter).addLiquidity( lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600) ); } function addLiquidity() internal { uint256 gg1Half = IERC20(gg1).balanceOf(address(this)).div(2); if (lpToken0 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp0Route, address(this), now.add(600) ); } if (lpToken1 != gg1) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( gg1Half, 0, gg1ToLp1Route, address(this), now.add(600) ); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IPancakeRouter(unirouter).addLiquidity( lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600) ); } function rebalance(address _token) public onlyOwner { uint256 tokenHalf = IERC20(_token).balanceOf(address(this)).div(2); if (_token == lpToken0) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenHalf, 0, Lp0ToLp1Route, address(this), now.add(600) ); IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenHalf, 0, Lp1ToLp0Route, address(this), now.add(600) ); } } function rebalance(address _token) public onlyOwner { uint256 tokenHalf = IERC20(_token).balanceOf(address(this)).div(2); if (_token == lpToken0) { IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenHalf, 0, Lp0ToLp1Route, address(this), now.add(600) ); IPancakeRouter(unirouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenHalf, 0, Lp1ToLp0Route, address(this), now.add(600) ); } } } else { function balanceOf() public view returns (uint256) { return balanceOfLpPair().add(balanceOfPool()); } function balanceOfLpPair() public view returns (uint256) { return IERC20(lpPair).balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { (uint256 _amount, ) = IShareRewardPool(shareRewardPool).userInfo(poolId, address(this)); return _amount; } function retireStrat() external onlyOwner { panic(); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); IERC20(lpPair).transfer(vault, pairBal); } function panic() public onlyOwner { pause(); IShareRewardPool(shareRewardPool).emergencyWithdraw(poolId); } function pause() public onlyOwner { _pause(); IERC20(lpPair).safeApprove(shareRewardPool, 0); IERC20(gg1).safeApprove(unirouter, 0); IERC20(wbnb).safeApprove(unirouter, 0); IERC20(busd).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, 0); } function unpause() external onlyOwner { _unpause(); IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1)); IERC20(gg1).safeApprove(unirouter, uint256(-1)); IERC20(wbnb).safeApprove(unirouter, uint256(-1)); IERC20(busd).safeApprove(unirouter, uint256(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint256(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint256(-1)); } }
11,335,175
[ 1, 13621, 434, 279, 6252, 358, 336, 16932, 628, 284, 4610, 310, 511, 52, 453, 8192, 316, 12913, 23780, 12521, 18, 12913, 23780, 12521, 353, 392, 18472, 690, 13667, 312, 6388, 261, 163, 227, 255, 2192, 49, 163, 227, 256, 13, 716, 5360, 2795, 2430, 358, 506, 431, 6703, 603, 326, 16827, 1359, 19656, 7824, 18, 2597, 353, 4797, 16, 19315, 438, 16, 471, 5360, 1281, 476, 358, 30891, 340, 18, 12913, 23780, 12521, 353, 279, 381, 310, 358, 506, 326, 404, 4501, 372, 24237, 2893, 603, 605, 2312, 18, 1220, 6252, 8616, 443, 917, 1282, 15098, 284, 19156, 518, 17024, 628, 326, 9229, 1368, 326, 3170, 25805, 17631, 1060, 2864, 2845, 18, 29758, 21, 283, 6397, 628, 17721, 4501, 372, 24237, 854, 10247, 2937, 3614, 11315, 6824, 16, 272, 1673, 471, 1416, 6437, 19, 3361, 18, 1021, 4656, 3082, 434, 7176, 854, 800, 9540, 471, 1898, 4501, 372, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 19736, 43, 75, 21, 14461, 58, 22, 353, 14223, 6914, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 28541, 1594, 682, 31, 203, 203, 565, 467, 654, 39, 3462, 1183, 84, 273, 467, 654, 39, 3462, 12, 2867, 12, 20, 92, 11035, 1403, 10525, 378, 69, 24, 3672, 74, 2643, 3437, 69, 42, 25, 71, 27, 3672, 7414, 27, 72, 28, 758, 27, 8522, 27, 40, 28, 5558, 21, 10019, 203, 203, 565, 1758, 1071, 5381, 29758, 21, 273, 203, 3639, 1758, 12, 20, 6995, 24, 3461, 10580, 22266, 9676, 29, 38, 29, 29258, 22, 29258, 21, 71, 25, 71, 28, 9060, 2539, 21, 73, 30379, 70, 39, 23, 23553, 38, 1769, 203, 565, 1758, 1071, 5381, 17298, 6423, 273, 203, 3639, 1758, 12, 20, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 1769, 203, 565, 1758, 1071, 5381, 5766, 72, 273, 203, 3639, 1758, 12, 20, 6554, 29, 73, 27, 1441, 37, 23, 20563, 71, 37, 6162, 5193, 27, 3672, 38, 1727, 71, 25, 2733, 70, 40, 8148, 1880, 72, 6840, 27, 40, 4313, 1769, 203, 203, 203, 565, 1758, 1071, 12423, 4154, 31, 203, 565, 1758, 1071, 12423, 1345, 20, 31, 203, 565, 1758, 1071, 2 ]
pragma solidity 0.5.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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 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) && _to != address(this)); // 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; /** * @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) && _to != address(this)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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 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; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, bytes calldata _extraData) external; } /** * @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(address burner, uint256 _value) internal { require(_value > 0); require(_value <= balances[burner]); // 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 balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Transfer(burner, address(0), _value); emit Burn(burner, _value); } } contract DKING is BurnableToken, Ownable { address public stakingAddress; string public constant name = "Deflationary King"; string public constant symbol = "DKING"; uint public constant decimals = 18; // there is no problem in using * here instead of .mul() uint256 public constant initialSupply = 1000000 * (10 ** uint256(decimals)); function setStakingAddress(address _addr) public onlyOwner { stakingAddress = _addr; } function transfer(address to, uint amount) public returns (bool) { uint _amountToBurn = amount.mul(400).div(10000); uint _amountToDisburse = amount.mul(400).div(10000); uint _amountAfterFee = amount.sub(_amountToBurn).sub(_amountToDisburse); burn(msg.sender, _amountToBurn); require(super.transfer(stakingAddress, _amountToDisburse), "Cannot disburse rewards."); if (stakingAddress != address(0)) { tokenRecipient(stakingAddress).receiveApproval(msg.sender, _amountToDisburse, ""); } require(super.transfer(to, _amountAfterFee), "Cannot transfer tokens."); return true; } function transferFrom(address from, address to, uint amount) public returns (bool) { require(to != address(0) && to != address(this)); uint _amountToBurn = amount.mul(400).div(10000); uint _amountToDisburse = amount.mul(400).div(10000); uint _amountAfterFee = amount.sub(_amountToBurn).sub(_amountToDisburse); uint256 _allowance = allowed[from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[from] = balances[from].sub(_amountAfterFee); balances[to] = balances[to].add(_amountAfterFee); balances[from] = balances[from].sub(_amountToDisburse); balances[stakingAddress] = balances[stakingAddress].add(_amountToDisburse); allowed[from][msg.sender] = _allowance.sub(amount); burn(from, _amountToBurn); emit Transfer(from, stakingAddress, _amountToDisburse); emit Transfer(from, to, _amountAfterFee); if (stakingAddress != address(0)) { tokenRecipient(stakingAddress).receiveApproval(msg.sender, _amountToDisburse, ""); } return true; } // Constructors constructor () public { totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner emit Transfer(address(0), msg.sender, initialSupply); } function transferAnyERC20Token(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).transfer(_to, _amount); } }
* @dev Burns a specific amount of tokens. @param _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(address burner, uint256 _value) internal { require(_value > 0); require(_value <= balances[burner]); balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Transfer(burner, address(0), _value); emit Burn(burner, _value); }
2,279,691
[ 1, 38, 321, 87, 279, 2923, 3844, 434, 2430, 18, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 506, 18305, 329, 18, 19, 1158, 1608, 358, 2583, 460, 1648, 2078, 3088, 1283, 16, 3241, 716, 4102, 709, 1283, 326, 5793, 1807, 11013, 353, 6802, 2353, 326, 2078, 3088, 1283, 16, 1492, 1410, 506, 392, 11240, 5166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 2867, 18305, 264, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 1132, 405, 374, 1769, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 70, 321, 264, 19226, 203, 203, 3639, 324, 26488, 63, 70, 321, 264, 65, 273, 324, 26488, 63, 70, 321, 264, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 3639, 3626, 12279, 12, 70, 321, 264, 16, 1758, 12, 20, 3631, 389, 1132, 1769, 203, 3639, 3626, 605, 321, 12, 70, 321, 264, 16, 389, 1132, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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 { __Context_init_unchained(); __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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library 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 Message, created from `s`. 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(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // 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: GPL-3.0-only pragma solidity ^0.8.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./libraries/ProofParser.sol"; import "./interfaces/ICrossChainBridge.sol"; import "./SimpleTokenProxy.sol"; import "./InternetBondProxy.sol"; contract BridgeRouter { function peggedTokenAddress(address bridge, address fromToken) public pure returns (address) { return SimpleTokenProxyUtils.simpleTokenProxyAddress(bridge, bytes32(bytes20(fromToken))); } function peggedBondAddress(address bridge, address fromToken) public pure returns (address) { return InternetBondProxyUtils.internetBondProxyAddress(bridge, bytes32(bytes20(fromToken))); } function factoryPeggedToken(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge) public returns (IERC20Mintable) { /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ address targetToken = SimpleTokenProxyUtils.deploySimpleTokenProxy(bridge, bytes32(bytes20(fromToken)), metaData); require(targetToken == toToken, "bad chain"); /* to token is our new pegged token */ return IERC20Mintable(toToken); } function factoryPeggedBond(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge, address feed) public returns (IERC20Mintable) { /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ address targetToken = InternetBondProxyUtils.deployInternetBondProxy(bridge, bytes32(bytes20(fromToken)), metaData, feed); require(targetToken == toToken, "bad chain"); /* to token is our new pegged token */ return IERC20Mintable(toToken); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/IERC20.sol"; import "./interfaces/IInternetBondRatioFeed.sol"; import "./SimpleToken.sol"; import "./libraries/Utils.sol"; contract InternetBond is SimpleToken, IERC20InternetBond { IInternetBondRatioFeed public ratioFeed; bool internal _rebasing; function ratio() public view override returns (uint256) { return ratioFeed.getRatioFor(_originAddress); } function isRebasing() public view override returns (bool) { return _rebasing; } function totalSupply() public view override returns (uint256) { return _sharesToBonds(super.totalSupply()); } function balanceOf(address account) public view override returns (uint256) { return _sharesToBonds(super.balanceOf(account)); } function transfer(address recipient, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _transfer(_msgSender(), recipient, shares, false); emit Transfer(_msgSender(), recipient, _sharesToBonds(shares)); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _sharesToBonds(super.allowance(owner, spender)); } function approve(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _approve(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function increaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _increaseAllowance(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _decreaseAllowance(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _transfer(sender, recipient, shares, false); emit Transfer(sender, recipient, _sharesToBonds(shares)); _decreaseAllowance(sender, _msgSender(), shares, false); emit Approval(sender, _msgSender(), allowance(sender, _msgSender())); return true; } // NB: mint accepts amount in shares function mint(address account, uint256 shares) public onlyOwner override { require(account != address(0)); _totalSupply += shares; _balances[account] += shares; emit Transfer(address(0), account, _sharesToBonds(shares)); } // NB: burn accepts amount in shares function burn(address account, uint256 shares) public onlyOwner override { require(account != address(0)); _balances[account] -= shares; _totalSupply -= shares; emit Transfer(account, address(0), _sharesToBonds(shares)); } function _sharesToBonds(uint256 amount) internal view returns (uint256) { if (_rebasing) { uint256 currentRatio = ratio(); require(currentRatio > 0, "ratio not available"); return Utils.multiplyAndDivideCeil(amount, 10 ** decimals(), currentRatio); } else { return amount; } } function _bondsToShares(uint256 amount) internal view returns (uint256) { if (_rebasing) { uint256 currentRatio = ratio(); require(currentRatio > 0, "ratio not available"); return Utils.multiplyAndDivideFloor(amount, currentRatio, 10 ** decimals()); } else { return amount; } } function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress, address ratioFeedAddress, bool rebasing) external emptyOwner { super.initAndObtainOwnership(symbol, name, originChain, originAddress); require(ratioFeedAddress != address(0x0), "no ratio feed"); ratioFeed = IInternetBondRatioFeed(ratioFeedAddress); _rebasing = rebasing; } } contract InternetBondFactory { address private _template; constructor() { _template = InternetBondFactoryUtils.deployInternetBondTemplate(this); } function getImplementation() public view returns (address) { return _template; } } library InternetBondFactoryUtils { bytes32 constant internal INTERNET_BOND_TEMPLATE_SALT = keccak256("InternetBondTemplateV1"); bytes constant internal INTERNET_BOND_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b506110c0806100206000396000f3fe608060405234801561001057600080fd5b506004361061012c5760003560e01c806371ca337d116100ad5780639dc29fac116100715780639dc29fac1461026b578063a457c2d71461027e578063a9059cbb14610291578063dd62ed3e146102a4578063df1f29ee146102b757600080fd5b806371ca337d1461020a5780638da5cb5b146102125780638e29ebb51461023d57806394bfed881461025057806395d89b411461026357600080fd5b8063313ce567116100f4578063313ce567146101b057806339509351146101bf57806340c10f19146101d25780635dfba115146101e557806370a08231146101f757600080fd5b806306fdde0314610131578063095ea7b31461014f57806318160ddd1461017257806323b872dd14610188578063265535671461019b575b600080fd5b6101396102da565b6040516101469190610e14565b60405180910390f35b61016261015d366004610d2a565b6102ec565b6040519015158152602001610146565b61017a610348565b604051908152602001610146565b610162610196366004610cee565b61035b565b6101ae6101a9366004610d93565b610400565b005b60405160128152602001610146565b6101626101cd366004610d2a565b61049e565b6101ae6101e0366004610d2a565b6104b9565b600854600160a01b900460ff16610162565b61017a610205366004610ca0565b610560565b61017a610582565b600254610225906001600160a01b031681565b6040516001600160a01b039091168152602001610146565b600854610225906001600160a01b031681565b6101ae61025e366004610d54565b610606565b610139610657565b6101ae610279366004610d2a565b610664565b61016261028c366004610d2a565b6106f9565b61016261029f366004610d2a565b610714565b61017a6102b2366004610cbb565b610752565b600654600754604080519283526001600160a01b03909116602083015201610146565b60606102e760015461078a565b905090565b6000806102f883610860565b905061030733858360006108e6565b6001600160a01b0384163360008051602061106b83398151915261032b8288610752565b60405190815260200160405180910390a360019150505b92915050565b60006102e761035660055490565b61097c565b60008061036783610860565b905061037685858360006109f9565b836001600160a01b0316856001600160a01b031660008051602061104b8339815191526103a28461097c565b60405190815260200160405180910390a36103c08533836000610ab2565b336001600160a01b03861660008051602061106b8339815191526103e48884610752565b60405190815260200160405180910390a3506001949350505050565b6002546001600160a01b03161561041657600080fd5b61042286868686610606565b6001600160a01b03821661046d5760405162461bcd60e51b815260206004820152600d60248201526c1b9bc81c985d1a5bc819995959609a1b60448201526064015b60405180910390fd5b60088054911515600160a01b026001600160a81b03199092166001600160a01b039093169290921717905550505050565b6000806104aa83610860565b90506103073385836000610b5f565b6002546001600160a01b031633146104d057600080fd5b6001600160a01b0382166104e357600080fd5b80600560008282546104f59190610e69565b90915550506001600160a01b03821660009081526003602052604081208054839290610522908490610e69565b90915550506001600160a01b038216600060008051602061104b83398151915261054b8461097c565b60405190815260200160405180910390a35050565b6001600160a01b0381166000908152600360205260408120546103429061097c565b60085460075460405163a1f1d48d60e01b81526001600160a01b039182166004820152600092919091169063a1f1d48d9060240160206040518083038186803b1580156105ce57600080fd5b505afa1580156105e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102e79190610dfb565b6002546001600160a01b03161561061c57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102e760005461078a565b6002546001600160a01b0316331461067b57600080fd5b6001600160a01b03821661068e57600080fd5b6001600160a01b038216600090815260036020526040812080548392906106b6908490610fc7565b9250508190555080600560008282546106cf9190610fc7565b90915550600090506001600160a01b03831660008051602061104b83398151915261054b8461097c565b60008061070583610860565b90506103073385836000610ab2565b60008061072083610860565b905061072f33858360006109f9565b6001600160a01b0384163360008051602061104b83398151915261032b8461097c565b6001600160a01b0380831660009081526004602090815260408083209385168352929052908120546107839061097c565b9392505050565b6060816107a557505060408051600081526020810190915290565b600060105b60ff8116156107fc57836107be8284610e81565b60ff16602081106107d1576107d161101e565b1a60f81b6001600160f81b031916156107f1576107ee8183610e81565b91505b60011c607f166107aa565b50600061080a826001610e81565b60ff1667ffffffffffffffff81111561082557610825611034565b6040519080825280601f01601f19166020018201604052801561084f576020820181803683370190505b506020810194909452509192915050565b600854600090600160a01b900460ff16156108dd57600061087f610582565b9050600081116108c75760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b61078383826108d86012600a610efd565b610bbc565b5090565b919050565b6001600160a01b0384166108f957600080fd5b6001600160a01b03831661090c57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561097657826001600160a01b0316846001600160a01b031660008051602061106b8339815191528460405161096d91815260200190565b60405180910390a35b50505050565b600854600090600160a01b900460ff16156108dd57600061099b610582565b9050600081116109e35760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b610783836109f36012600a610efd565b83610c01565b6001600160a01b038416610a0c57600080fd5b6001600160a01b038316610a1f57600080fd5b6001600160a01b03841660009081526003602052604081208054849290610a47908490610fc7565b90915550506001600160a01b03831660009081526003602052604081208054849290610a74908490610e69565b9091555050801561097657826001600160a01b0316846001600160a01b031660008051602061104b8339815191528460405161096d91815260200190565b6001600160a01b038416610ac557600080fd5b6001600160a01b038316610ad857600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610fc7565b90915550508015610976576001600160a01b0384811660008181526004602090815260408083209488168084529482529182902054915191825260008051602061106b833981519152910161096d565b6001600160a01b038416610b7257600080fd5b6001600160a01b038316610b8557600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610e69565b6000610bf9610bd4610bce8487610ea6565b85610c3e565b8385610be08289610fde565b610bea9190610fa8565b610bf49190610ea6565b610c71565b949350505050565b6000610bf9610c13610bce8487610ea6565b83610c1f600182610fc7565b86610c2a878a610fde565b610c349190610fa8565b610bea9190610e69565b600082610c4d57506000610342565b82820282848281610c6057610c60611008565b041461078357600019915050610342565b60008282018381101561078357600019915050610342565b80356001600160a01b03811681146108e157600080fd5b600060208284031215610cb257600080fd5b61078382610c89565b60008060408385031215610cce57600080fd5b610cd783610c89565b9150610ce560208401610c89565b90509250929050565b600080600060608486031215610d0357600080fd5b610d0c84610c89565b9250610d1a60208501610c89565b9150604084013590509250925092565b60008060408385031215610d3d57600080fd5b610d4683610c89565b946020939093013593505050565b60008060008060808587031215610d6a57600080fd5b843593506020850135925060408501359150610d8860608601610c89565b905092959194509250565b60008060008060008060c08789031215610dac57600080fd5b863595506020870135945060408701359350610dca60608801610c89565b9250610dd860808801610c89565b915060a08701358015158114610ded57600080fd5b809150509295509295509295565b600060208284031215610e0d57600080fd5b5051919050565b600060208083528351808285015260005b81811015610e4157858101830151858201604001528201610e25565b81811115610e53576000604083870101525b50601f01601f1916929092016040019392505050565b60008219821115610e7c57610e7c610ff2565b500190565b600060ff821660ff84168060ff03821115610e9e57610e9e610ff2565b019392505050565b600082610eb557610eb5611008565b500490565b600181815b80851115610ef5578160001904821115610edb57610edb610ff2565b80851615610ee857918102915b93841c9390800290610ebf565b509250929050565b600061078360ff841683600082610f1657506001610342565b81610f2357506000610342565b8160018114610f395760028114610f4357610f5f565b6001915050610342565b60ff841115610f5457610f54610ff2565b50506001821b610342565b5060208310610133831016604e8410600b8410161715610f82575081810a610342565b610f8c8383610eba565b8060001904821115610fa057610fa0610ff2565b029392505050565b6000816000190483118215151615610fc257610fc2610ff2565b500290565b600082821015610fd957610fd9610ff2565b500390565b600082610fed57610fed611008565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfeddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a26469706673582212202704c0c85a7ffefb8570f6c29df5c6522044694561363ba9c4f84b992471d3fb64736f6c63430008060033"; bytes32 constant internal INTERNET_BOND_TEMPLATE_HASH = keccak256(INTERNET_BOND_TEMPLATE_BYTECODE); function deployInternetBondTemplate(InternetBondFactory templateFactory) internal returns (address) { /* we can use any deterministic salt here, since we don't care about it */ bytes32 salt = INTERNET_BOND_TEMPLATE_SALT; /* concat bytecode with constructor */ bytes memory bytecode = INTERNET_BOND_TEMPLATE_BYTECODE; /* deploy contract and store result in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* check that generated contract address is correct */ require(result == internetBondTemplateAddress(templateFactory), "address mismatched"); return result; } function internetBondTemplateAddress(InternetBondFactory templateFactory) internal pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), INTERNET_BOND_TEMPLATE_SALT, INTERNET_BOND_TEMPLATE_HASH)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/ICrossChainBridge.sol"; contract InternetBondProxy { bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1); fallback() external { address bridge; bytes32 slot = BEACON_SLOT; assembly { bridge := sload(slot) } address impl = ICrossChainBridge(bridge).getBondImplementation(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } function setBeacon(address newBeacon) external { address beacon; bytes32 slot = BEACON_SLOT; assembly { beacon := sload(slot) } require(beacon == address(0x00)); assembly { sstore(slot, newBeacon) } } } library InternetBondProxyUtils { bytes constant internal INTERNET_BOND_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b0316631626425c6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220d283edebb1e56b63c1cf809c7a7219bbf056c367c289dabb51fdba5f71cdf44c64736f6c63430008060033"; bytes32 constant internal INTERNET_BOND_PROXY_HASH = keccak256(INTERNET_BOND_PROXY_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address,address,bool)")); bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)")); function deployInternetBondProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData, address ratioFeed) internal returns (address) { /* lets concat bytecode with constructor parameters */ bytes memory bytecode = INTERNET_BOND_PROXY_BYTECODE; /* deploy new contract and store contract address in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* setup impl */ (bool success, bytes memory returnValue) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge))); require(success, string(abi.encodePacked("setBeacon failed: ", returnValue))); /* setup meta data */ bytes memory inputData = new bytes(0xc4); bool isRebasing = metaData.bondMetadata[1] == bytes1(0x01); bytes4 selector = SET_META_DATA_SIG; assembly { mstore(add(inputData, 0x20), selector) mstore(add(inputData, 0x24), mload(metaData)) mstore(add(inputData, 0x44), mload(add(metaData, 0x20))) mstore(add(inputData, 0x64), mload(add(metaData, 0x40))) mstore(add(inputData, 0x84), mload(add(metaData, 0x60))) mstore(add(inputData, 0xa4), ratioFeed) mstore(add(inputData, 0xc4), isRebasing) } (success, returnValue) = result.call(inputData); require(success, string(abi.encodePacked("set metadata failed: ", returnValue))); /* return generated contract address */ return result; } function internetBondProxyAddress(address deployer, bytes32 salt) internal pure returns (address) { bytes32 bytecodeHash = keccak256(INTERNET_BOND_PROXY_BYTECODE); bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IInternetBondRatioFeed.sol"; contract InternetBondRatioFeed is OwnableUpgradeable, IInternetBondRatioFeed { event OperatorAdded(address operator); event OperatorRemoved(address operator); mapping(address => bool) _isOperator; mapping(address => uint256) private _ratios; function initialize(address operator) public initializer { __Ownable_init(); _isOperator[operator] = true; } function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) public override onlyOperator { require(addresses.length == ratios.length, "corrupted ratio data"); for (uint256 i = 0; i < addresses.length; i++) { _ratios[addresses[i]] = ratios[i]; } } function getRatioFor(address token) public view override returns (uint256) { return _ratios[token]; } function addOperator(address operator) public onlyOwner { require(operator != address(0x0), "operator must be non-zero"); require(!_isOperator[operator], "already operator"); _isOperator[operator] = true; emit OperatorAdded(operator); } function removeOperator(address operator) public onlyOwner { require(_isOperator[operator], "not an operator"); delete _isOperator[operator]; emit OperatorRemoved(operator); } modifier onlyOperator() { require(msg.sender == owner() || _isOperator[msg.sender], "Operator: not allowed"); _; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IERC20.sol"; contract SimpleToken is Context, IERC20, IERC20Mintable, IERC20Pegged { // pre-defined state bytes32 internal _symbol; // 0 bytes32 internal _name; // 1 address public owner; // 2 // internal state mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; uint256 internal _originChain; address internal _originAddress; function name() public view returns (string memory) { return bytes32ToString(_name); } function symbol() public view returns (string memory) { return bytes32ToString(_symbol); } function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { if (_bytes32 == 0) { return new string(0); } uint8 cntNonZero = 0; for (uint8 i = 16; i > 0; i >>= 1) { if (_bytes32[cntNonZero + i] != 0) cntNonZero += i; } string memory result = new string(cntNonZero + 1); assembly { mstore(add(result, 0x20), _bytes32) } return result; } function decimals() public pure returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount, true); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount, true); return true; } function increaseAllowance(address spender, uint256 amount) public virtual returns (bool) { _increaseAllowance(_msgSender(), spender, amount, true); return true; } function decreaseAllowance(address spender, uint256 amount) public virtual returns (bool) { _decreaseAllowance(_msgSender(), spender, amount, true); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount, true); _decreaseAllowance(sender, _msgSender(), amount, true); return true; } function _increaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] += amount; if (emitEvent) { emit Approval(owner, spender, _allowances[owner][spender]); } } function _decreaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] -= amount; if (emitEvent) { emit Approval(owner, spender, _allowances[owner][spender]); } } function _approve(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; if (emitEvent) { emit Approval(owner, spender, amount); } } function _transfer(address sender, address recipient, uint256 amount, bool emitEvent) internal { require(sender != address(0)); require(recipient != address(0)); _balances[sender] -= amount; _balances[recipient] += amount; if (emitEvent) { emit Transfer(sender, recipient, amount); } } function mint(address account, uint256 amount) public onlyOwner virtual override { require(account != address(0)); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function burn(address account, uint256 amount) public onlyOwner virtual override { require(account != address(0)); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } modifier emptyOwner() { require(owner == address(0x00)); _; } function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress) public emptyOwner { owner = msg.sender; _symbol = symbol; _name = name; _originChain = originChain; _originAddress = originAddress; } modifier onlyOwner() { require(msg.sender == owner); _; } function getOrigin() public view override returns (uint256, address) { return (_originChain, _originAddress); } } contract SimpleTokenFactory { address private _template; constructor() { _template = SimpleTokenFactoryUtils.deploySimpleTokenTemplate(this); } function getImplementation() public view returns (address) { return _template; } } library SimpleTokenFactoryUtils { bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_SALT = keccak256("SimpleTokenTemplateV1"); bytes constant internal SIMPLE_TOKEN_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b50610a7f806100206000396000f3fe608060405234801561001057600080fd5b50600436106101005760003560e01c80638da5cb5b11610097578063a457c2d711610066578063a457c2d714610224578063a9059cbb14610237578063dd62ed3e1461024a578063df1f29ee1461028357600080fd5b80638da5cb5b146101cb57806394bfed88146101f657806395d89b41146102095780639dc29fac1461021157600080fd5b8063313ce567116100d3578063313ce5671461016b578063395093511461017a57806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610105578063095ea7b31461012357806318160ddd1461014657806323b872dd14610158575b600080fd5b61010d6102a6565b60405161011a919061095e565b60405180910390f35b6101366101313660046108f5565b6102b8565b604051901515815260200161011a565b6005545b60405190815260200161011a565b6101366101663660046108b9565b6102d0565b6040516012815260200161011a565b6101366101883660046108f5565b6102f6565b6101a061019b3660046108f5565b610305565b005b61014a6101b0366004610864565b6001600160a01b031660009081526003602052604090205490565b6002546101de906001600160a01b031681565b6040516001600160a01b03909116815260200161011a565b6101a061020436600461091f565b6103b9565b61010d61040a565b6101a061021f3660046108f5565b610417565b6101366102323660046108f5565b6104c5565b6101366102453660046108f5565b6104d4565b61014a610258366004610886565b6001600160a01b03918216600090815260046020908152604080832093909416825291909152205490565b600654600754604080519283526001600160a01b0390911660208301520161011a565b60606102b36001546104e3565b905090565b60006102c733848460016105b9565b50600192915050565b60006102df8484846001610661565b6102ec843384600161072c565b5060019392505050565b60006102c733848460016107eb565b6002546001600160a01b0316331461031c57600080fd5b6001600160a01b03821661032f57600080fd5b806005600082825461034191906109b3565b90915550506001600160a01b0382166000908152600360205260408120805483929061036e9084906109b3565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a35050565b6002546001600160a01b0316156103cf57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102b36000546104e3565b6002546001600160a01b0316331461042e57600080fd5b6001600160a01b03821661044157600080fd5b6001600160a01b038216600090815260036020526040812080548392906104699084906109f0565b92505081905550806005600082825461048291906109f0565b90915550506040518181526000906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020016103ad565b60006102c7338484600161072c565b60006102c73384846001610661565b6060816104fe57505060408051600081526020810190915290565b600060105b60ff811615610555578361051782846109cb565b60ff166020811061052a5761052a610a1d565b1a60f81b6001600160f81b0319161561054a5761054781836109cb565b91505b60011c607f16610503565b5060006105638260016109cb565b60ff1667ffffffffffffffff81111561057e5761057e610a33565b6040519080825280601f01601f1916602001820160405280156105a8576020820181803683370190505b506020810194909452509192915050565b6001600160a01b0384166105cc57600080fd5b6001600160a01b0383166105df57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561065b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161065291815260200190565b60405180910390a35b50505050565b6001600160a01b03841661067457600080fd5b6001600160a01b03831661068757600080fd5b6001600160a01b038416600090815260036020526040812080548492906106af9084906109f0565b90915550506001600160a01b038316600090815260036020526040812080548492906106dc9084906109b3565b9091555050801561065b57826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161065291815260200190565b6001600160a01b03841661073f57600080fd5b6001600160a01b03831661075257600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109f0565b9091555050801561065b576001600160a01b038481166000818152600460209081526040808320948816808452948252918290205491519182527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259101610652565b6001600160a01b0384166107fe57600080fd5b6001600160a01b03831661081157600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109b3565b80356001600160a01b038116811461085f57600080fd5b919050565b60006020828403121561087657600080fd5b61087f82610848565b9392505050565b6000806040838503121561089957600080fd5b6108a283610848565b91506108b060208401610848565b90509250929050565b6000806000606084860312156108ce57600080fd5b6108d784610848565b92506108e560208501610848565b9150604084013590509250925092565b6000806040838503121561090857600080fd5b61091183610848565b946020939093013593505050565b6000806000806080858703121561093557600080fd5b84359350602085013592506040850135915061095360608601610848565b905092959194509250565b600060208083528351808285015260005b8181101561098b5785810183015185820160400152820161096f565b8181111561099d576000604083870101525b50601f01601f1916929092016040019392505050565b600082198211156109c6576109c6610a07565b500190565b600060ff821660ff84168060ff038211156109e8576109e8610a07565b019392505050565b600082821015610a0257610a02610a07565b500390565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfea2646970667358221220fe9609dd4d099f8ee61d515b2ebf66a53d24e78cf669be48b69b627acefde71564736f6c63430008060033"; bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_HASH = keccak256(SIMPLE_TOKEN_TEMPLATE_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("obtainOwnership(bytes32,bytes32)")); function deploySimpleTokenTemplate(SimpleTokenFactory templateFactory) internal returns (address) { /* we can use any deterministic salt here, since we don't care about it */ bytes32 salt = SIMPLE_TOKEN_TEMPLATE_SALT; /* concat bytecode with constructor */ bytes memory bytecode = SIMPLE_TOKEN_TEMPLATE_BYTECODE; /* deploy contract and store result in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* check that generated contract address is correct */ require(result == simpleTokenTemplateAddress(templateFactory), "address mismatched"); return result; } function simpleTokenTemplateAddress(SimpleTokenFactory templateFactory) internal pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), SIMPLE_TOKEN_TEMPLATE_SALT, SIMPLE_TOKEN_TEMPLATE_HASH)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/ICrossChainBridge.sol"; contract SimpleTokenProxy { bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1); fallback() external { address bridge; bytes32 slot = BEACON_SLOT; assembly { bridge := sload(slot) } address impl = ICrossChainBridge(bridge).getTokenImplementation(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } function setBeacon(address newBeacon) external { address beacon; bytes32 slot = BEACON_SLOT; assembly { beacon := sload(slot) } require(beacon == address(0x00)); assembly { sstore(slot, newBeacon) } } } library SimpleTokenProxyUtils { bytes constant internal SIMPLE_TOKEN_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b031663709bc7f36040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220e6ae4b3dc2474e43ff609e19eb520ce54b6f38170a43a6f96541360be5efc2b464736f6c63430008060033"; bytes32 constant internal SIMPLE_TOKEN_PROXY_HASH = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address)")); bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)")); function deploySimpleTokenProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData) internal returns (address) { /* lets concat bytecode with constructor parameters */ bytes memory bytecode = SIMPLE_TOKEN_PROXY_BYTECODE; /* deploy new contract and store contract address in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* setup impl */ (bool success,) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge))); require(success, "setBeacon failed"); /* setup meta data */ (success,) = result.call(abi.encodePacked(SET_META_DATA_SIG, abi.encode(metaData))); require(success, "set metadata failed"); /* return generated contract address */ return result; } function simpleTokenProxyAddress(address deployer, bytes32 salt) internal pure returns (address) { bytes32 bytecodeHash = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE); bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "../interfaces/IERC20.sol"; interface ICrossChainBridge { event ContractAllowed(address contractAddress, uint256 toChain); event ContractDisallowed(address contractAddress, uint256 toChain); event ConsensusChanged(address consensusAddress); event TokenImplementationChanged(address consensusAddress); event BondImplementationChanged(address consensusAddress); struct Metadata { bytes32 symbol; bytes32 name; uint256 originChain; address originAddress; bytes32 bondMetadata; // encoded metadata version, bond type } event DepositLocked( uint256 chainId, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount, Metadata metadata ); event DepositBurned( uint256 chainId, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount, Metadata metadata, address originToken ); event WithdrawMinted( bytes32 receiptHash, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount ); event WithdrawUnlocked( bytes32 receiptHash, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount ); enum InternetBondType { NOT_BOND, REBASING_BOND, NONREBASING_BOND } function isPeggedToken(address toToken) external returns (bool); function deposit(uint256 toChain, address toAddress) payable external; function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) external; function withdraw(bytes calldata encodedProof, bytes calldata rawReceipt, bytes calldata receiptRootSignature) external; function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external; function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external; function getTokenImplementation() external returns (address); function getBondImplementation() external returns (address); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Mintable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } interface IERC20Pegged { function getOrigin() external view returns (uint256, address); } interface IERC20Extra { function name() external returns (string memory); function decimals() external returns (uint8); function symbol() external returns (string memory); } interface IERC20InternetBond { function ratio() external view returns (uint256); function isRebasing() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; interface IInternetBondRatioFeed { function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) external; function getRatioFor(address) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.6; library CallDataRLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; function beginIteration(uint256 listOffset) internal pure returns (uint256 iter) { return listOffset + _payloadOffset(listOffset); } function next(uint256 iter) internal pure returns (uint256 nextIter) { return iter + itemLength(iter); } function payloadLen(uint256 ptr, uint256 len) internal pure returns (uint256) { return len - _payloadOffset(ptr); } function toAddress(uint256 ptr) internal pure returns (address) { return address(uint160(toUint(ptr, 21))); } function toUint(uint256 ptr, uint256 len) internal pure returns (uint256) { require(len > 0 && len <= 33); uint256 offset = _payloadOffset(ptr); uint256 numLen = len - offset; uint256 result; assembly { result := calldataload(add(ptr, offset)) // cut off redundant bytes result := shr(mul(8, sub(32, numLen)), result) } return result; } function toUintStrict(uint256 ptr) internal pure returns (uint256) { // one byte prefix uint256 result; assembly { result := calldataload(add(ptr, 1)) } return result; } function rawDataPtr(uint256 ptr) internal pure returns (uint256) { return ptr + _payloadOffset(ptr); } // @return entire rlp item byte length function itemLength(uint callDataPtr) internal pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, calldataload(callDataPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is callDataPtr := add(callDataPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr)) itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) callDataPtr := add(callDataPtr, 1) let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr)) itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 callDataPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, calldataload(callDataPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./CallDataRLPReader.sol"; import "./Utils.sol"; import "../interfaces/ICrossChainBridge.sol"; library EthereumVerifier { bytes32 constant TOPIC_PEG_IN_LOCKED = keccak256("DepositLocked(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32))"); bytes32 constant TOPIC_PEG_IN_BURNED = keccak256("DepositBurned(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32),address)"); enum PegInType { None, Lock, Burn } struct State { bytes32 receiptHash; address contractAddress; uint256 chainId; address fromAddress; address payable toAddress; address fromToken; address toToken; uint256 totalAmount; // metadata fields (we can't use Metadata struct here because of Solidity struct memory layout) bytes32 symbol; bytes32 name; uint256 originChain; address originAddress; bytes32 bondMetadata; address originToken; } function getMetadata(State memory state) internal pure returns (ICrossChainBridge.Metadata memory) { ICrossChainBridge.Metadata memory metadata; assembly { metadata := add(state, 0x100) } return metadata; } function parseTransactionReceipt(uint256 receiptOffset) internal view returns (State memory, PegInType pegInType) { State memory state; /* parse peg-in data from logs */ uint256 iter = CallDataRLPReader.beginIteration(receiptOffset + 0x20); { /* postStateOrStatus - we must ensure that tx is not reverted */ uint256 statusOffset = iter; iter = CallDataRLPReader.next(iter); require(CallDataRLPReader.payloadLen(statusOffset, iter - statusOffset) == 1, "tx is reverted"); } /* skip cumulativeGasUsed */ iter = CallDataRLPReader.next(iter); /* logs - we need to find our logs */ uint256 logs = iter; iter = CallDataRLPReader.next(iter); uint256 logsIter = CallDataRLPReader.beginIteration(logs); for (; logsIter < iter;) { uint256 log = logsIter; logsIter = CallDataRLPReader.next(logsIter); /* make sure there is only one peg-in event in logs */ PegInType logType = _decodeReceiptLogs(state, log); if (logType != PegInType.None) { require(pegInType == PegInType.None, "multiple logs"); pegInType = logType; } } /* don't allow to process if peg-in type is unknown */ require(pegInType != PegInType.None, "missing logs"); return (state, pegInType); } function _decodeReceiptLogs( State memory state, uint256 log ) internal view returns (PegInType pegInType) { uint256 logIter = CallDataRLPReader.beginIteration(log); address contractAddress; { /* parse smart contract address */ uint256 addressOffset = logIter; logIter = CallDataRLPReader.next(logIter); contractAddress = CallDataRLPReader.toAddress(addressOffset); } /* topics */ bytes32 mainTopic; address fromAddress; address toAddress; { uint256 topicsIter = logIter; logIter = CallDataRLPReader.next(logIter); // Must be 3 topics RLP encoded: event signature, fromAddress, toAddress // Each topic RLP encoded is 33 bytes (0xa0[32 bytes data]) // Total payload: 99 bytes. Since it's list with total size bigger than 55 bytes we need 2 bytes prefix (0xf863) // So total size of RLP encoded topics array must be 101 if (CallDataRLPReader.itemLength(topicsIter) != 101) { return PegInType.None; } topicsIter = CallDataRLPReader.beginIteration(topicsIter); mainTopic = bytes32(CallDataRLPReader.toUintStrict(topicsIter)); topicsIter = CallDataRLPReader.next(topicsIter); fromAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))); topicsIter = CallDataRLPReader.next(topicsIter); toAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))); topicsIter = CallDataRLPReader.next(topicsIter); require(topicsIter == logIter); // safety check that iteration is finished } uint256 ptr = CallDataRLPReader.rawDataPtr(logIter); logIter = CallDataRLPReader.next(logIter); uint256 len = logIter - ptr; { // parse logs based on topic type and check that event data has correct length uint256 expectedLen; if (mainTopic == TOPIC_PEG_IN_LOCKED) { expectedLen = 0x120; pegInType = PegInType.Lock; } else if (mainTopic == TOPIC_PEG_IN_BURNED) { expectedLen = 0x140; pegInType = PegInType.Burn; } else { return PegInType.None; } if (len != expectedLen) { return PegInType.None; } } { // read chain id separately and verify that contract that emitted event is relevant uint256 chainId; assembly { chainId := calldataload(ptr) } if (chainId != Utils.currentChain()) return PegInType.None; // All checks are passed after this point, no errors allowed and we can modify state state.chainId = chainId; ptr += 0x20; len -= 0x20; } { uint256 structOffset; assembly { // skip 5 fields: receiptHash, contractAddress, chainId, fromAddress, toAddress structOffset := add(state, 0xa0) calldatacopy(structOffset, ptr, len) } } state.contractAddress = contractAddress; state.fromAddress = fromAddress; state.toAddress = payable(toAddress); return pegInType; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./CallDataRLPReader.sol"; import "./Utils.sol"; library ProofParser { // Proof is message format signed by the protocol. It contains somewhat redundant information, so only part // of the proof could be passed into the contract and other part can be inferred from transaction receipt struct Proof { uint256 chainId; uint256 status; bytes32 transactionHash; uint256 blockNumber; bytes32 blockHash; uint256 transactionIndex; bytes32 receiptHash; uint256 transferAmount; } function parseProof(uint256 proofOffset) internal pure returns (Proof memory) { Proof memory proof; uint256 dataOffset = proofOffset + 0x20; assembly { calldatacopy(proof, dataOffset, 0x20) // 1 field (chainId) dataOffset := add(dataOffset, 0x20) calldatacopy(add(proof, 0x40), dataOffset, 0x80) // 4 fields * 0x20 = 0x80 dataOffset := add(dataOffset, 0x80) calldatacopy(add(proof, 0xe0), dataOffset, 0x20) // transferAmount } return proof; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "../SimpleToken.sol"; library Utils { function currentChain() internal view returns (uint256) { uint256 chain; assembly { chain := chainid() } return chain; } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function saturatingMultiply(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { if (a == 0) return 0; uint256 c = a * b; if (c / a != b) return type(uint256).max; return c; } } function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { uint256 c = a + b; if (c < a) return type(uint256).max; return c; } } // Preconditions: // 1. a may be arbitrary (up to 2 ** 256 - 1) // 2. b * c < 2 ** 256 // Returned value: min(floor((a * b) / c), 2 ** 256 - 1) function multiplyAndDivideFloor(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) { return saturatingAdd( saturatingMultiply(a / c, b), ((a % c) * b) / c // can't fail because of assumption 2. ); } // Preconditions: // 1. a may be arbitrary (up to 2 ** 256 - 1) // 2. b * c < 2 ** 256 // Returned value: min(ceil((a * b) / c), 2 ** 256 - 1) function multiplyAndDivideCeil(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) { return saturatingAdd( saturatingMultiply(a / c, b), ((a % c) * b + (c - 1)) / c // can't fail because of assumption 2. ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "../interfaces/ICrossChainBridge.sol"; import "../interfaces/IERC20.sol"; import "../libraries/EthereumVerifier.sol"; import "../libraries/ProofParser.sol"; import "../libraries/Utils.sol"; import "../SimpleToken.sol"; import "../InternetBond.sol"; import "../InternetBondRatioFeed.sol"; import "../BridgeRouter.sol"; contract CrossChainBridge_R1 is PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable, ICrossChainBridge { mapping(uint256 => address) private _bridgeAddressByChainId; address private _consensusAddress; mapping(bytes32 => bool) private _usedProofs; address private _tokenImplementation; mapping(address => address) private _peggedTokenOrigin; Metadata _nativeTokenMetadata; address private _bondImplementation; IInternetBondRatioFeed private _internetBondRatioFeed; BridgeRouter private _bridgeRouter; function initialize( address consensusAddress, SimpleTokenFactory tokenFactory, InternetBondFactory bondFactory, string memory nativeTokenSymbol, string memory nativeTokenName, InternetBondRatioFeed bondFeed, BridgeRouter router ) public initializer { __Pausable_init(); __ReentrancyGuard_init(); __Ownable_init(); __CrossChainBridge_init(consensusAddress, tokenFactory, bondFactory, nativeTokenSymbol, nativeTokenName, bondFeed, router); } function getTokenImplementation() public view override returns (address) { return _tokenImplementation; } function setTokenFactory(SimpleTokenFactory factory) public onlyOwner { _tokenImplementation = factory.getImplementation(); require(_tokenImplementation != address(0x0)); emit TokenImplementationChanged(_tokenImplementation); } function getBondImplementation() public view override returns (address) { return _bondImplementation; } function setBondFactory(InternetBondFactory factory) public onlyOwner { _bondImplementation = factory.getImplementation(); require(_bondImplementation != address(0x0)); emit BondImplementationChanged(_tokenImplementation); } function getNativeAddress() public view returns (address) { return _nativeTokenMetadata.originAddress; } function getOrigin(address token) internal view returns (uint256, address) { if (token == _nativeTokenMetadata.originAddress) { return (0, address(0x0)); } try IERC20Pegged(token).getOrigin() returns (uint256 chain, address origin) { return (chain, origin); } catch {} return (0, address(0x0)); } function __CrossChainBridge_init( address consensusAddress, SimpleTokenFactory tokenFactory, InternetBondFactory bondFactory, string memory nativeTokenSymbol, string memory nativeTokenName, InternetBondRatioFeed bondFeed, BridgeRouter router ) internal { _consensusAddress = consensusAddress; _tokenImplementation = tokenFactory.getImplementation(); _bondImplementation = bondFactory.getImplementation(); _nativeTokenMetadata = Metadata( Utils.stringToBytes32(nativeTokenSymbol), Utils.stringToBytes32(nativeTokenName), Utils.currentChain(), // generate unique address that will not collide with any contract address address(bytes20(keccak256(abi.encodePacked("CrossChainBridge:", nativeTokenSymbol)))), 0x0 ); _internetBondRatioFeed = bondFeed; _bridgeRouter = router; } // HELPER FUNCTIONS function isPeggedToken(address toToken) public view override returns (bool) { return _peggedTokenOrigin[toToken] != address(0x00); } function getRatio(address token) public view returns (uint256) { return _internetBondRatioFeed.getRatioFor(token); } function getBondType(address token) public view returns (InternetBondType) { try IERC20InternetBond(token).isRebasing() returns (bool isRebasing) { if (isRebasing) return InternetBondType.REBASING_BOND; else return InternetBondType.NONREBASING_BOND; } catch { } return InternetBondType.NOT_BOND; } function getNativeRatio(address token) public view returns (uint256) { try IERC20InternetBond(token).ratio() returns (uint256 ratio) { return ratio; } catch { } return 0; } function createBondMetadata(uint8 version, InternetBondType bondType) internal pure returns (bytes32) { bytes32 result = 0x0; result |= bytes32(bytes1(version)); result |= bytes32(bytes1(uint8(bondType))) >> 8; return result; } // DEPOSIT FUNCTIONS function deposit(uint256 toChain, address toAddress) public payable nonReentrant whenNotPaused override { _depositNative(toChain, toAddress, msg.value); } function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) public nonReentrant whenNotPaused override { (uint256 chain, address origin) = getOrigin(fromToken); if (chain != 0) { /* if we have pegged contract then its pegged token */ _depositPegged(fromToken, toChain, toAddress, amount, chain, origin); } else { /* otherwise its erc20 token, since we can't detect is it erc20 token it can only return insufficient balance in case of any errors */ _depositErc20(fromToken, toChain, toAddress, amount); } } function _depositNative(uint256 toChain, address toAddress, uint256 totalAmount) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); /* we need to calculate peg token contract address with meta data */ address toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), _nativeTokenMetadata.originAddress); /* emit event with all these params */ emit DepositLocked( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network _nativeTokenMetadata.originAddress, // this is our current native token (e.g. ETH, MATIC, BNB, etc) toToken, // this is an address of our target pegged token totalAmount, // how much funds was locked in this contract _nativeTokenMetadata // meta information about ); } function _depositPegged(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount, uint256 chain, address origin) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); /* check allowance and transfer tokens */ require(IERC20Upgradeable(fromToken).balanceOf(fromAddress) >= totalAmount, "insufficient balance"); InternetBondType bondType = getBondType(fromToken); uint256 amt; if (bondType == InternetBondType.REBASING_BOND) { amt = _peggedAmountToShares(totalAmount, getRatio(origin)); } else { amt = totalAmount; } address toToken; if (bondType == InternetBondType.NOT_BOND) { toToken = _peggedDestinationErc20Token(fromToken, origin, toChain, chain); } else { toToken = _peggedDestinationErc20Bond(fromToken, origin, toChain, chain); } IERC20Mintable(fromToken).burn(fromAddress, amt); Metadata memory metaData = Metadata( Utils.stringToBytes32(IERC20Extra(fromToken).symbol()), Utils.stringToBytes32(IERC20Extra(fromToken).name()), chain, origin, createBondMetadata(0, bondType) ); /* emit event with all these params */ emit DepositBurned( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else) toToken, // this is an address of our target pegged token amt, // how much funds was locked in this contract metaData, origin ); } function _peggedAmountToShares(uint256 amount, uint256 ratio) internal pure returns (uint256) { require(ratio > 0, "zero ratio"); return Utils.multiplyAndDivideFloor(amount, ratio, 1e18); } function _nativeAmountToShares(uint256 amount, uint256 ratio, uint8 decimals) internal pure returns (uint256) { require(ratio > 0, "zero ratio"); return Utils.multiplyAndDivideFloor(amount, ratio, 10 ** decimals); } function _depositErc20(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); InternetBondType bondType = getBondType(fromToken); /* check allowance and transfer tokens */ { uint256 balanceBefore = IERC20(fromToken).balanceOf(address(this)); uint256 allowance = IERC20(fromToken).allowance(fromAddress, address(this)); require(totalAmount <= allowance, "insufficient allowance"); require(IERC20(fromToken).transferFrom(fromAddress, address(this), totalAmount), "can't transfer"); uint256 balanceAfter = IERC20(fromToken).balanceOf(address(this)); if (bondType != InternetBondType.REBASING_BOND) { // Assert that enough coins were transferred to bridge require(balanceAfter >= balanceBefore + totalAmount, "incorrect behaviour"); } else { // For rebasing internet bonds we can't assert that exactly totalAmount will be transferred require(balanceAfter >= balanceBefore, "incorrect behaviour"); } } /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); /* lets pack ERC20 token meta data and scale amount to 18 decimals */ uint256 chain = Utils.currentChain(); uint256 amt; if (bondType != InternetBondType.REBASING_BOND) { amt = _amountErc20Token(fromToken, totalAmount); } else { amt = _amountErc20Bond(fromToken, totalAmount, getNativeRatio(fromToken)); } address toToken; if (bondType == InternetBondType.NOT_BOND) { toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), fromToken); } else { toToken = _bridgeRouter.peggedBondAddress(address(toBridge), fromToken); } Metadata memory metaData = Metadata( Utils.stringToBytes32(IERC20Extra(fromToken).symbol()), Utils.stringToBytes32(IERC20Extra(fromToken).name()), chain, fromToken, createBondMetadata(0, bondType) ); /* emit event with all these params */ emit DepositLocked( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else) toToken, // this is an address of our target pegged token amt, // how much funds was locked in this contract metaData // meta information about ); } function _peggedDestinationErc20Token(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) { /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported"); if (toChain == originChain) { return _peggedTokenOrigin[fromToken]; } else { return _bridgeRouter.peggedTokenAddress(address(toBridge), origin); } } function _peggedDestinationErc20Bond(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) { /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported"); if (toChain == originChain) { return _peggedTokenOrigin[fromToken]; } else { return _bridgeRouter.peggedBondAddress(address(toBridge), origin); } } function _amountErc20Token(address fromToken, uint256 totalAmount) internal returns (uint256) { /* lets pack ERC20 token meta data and scale amount to 18 decimals */ require(IERC20Extra(fromToken).decimals() <= 18, "decimals overflow"); totalAmount *= (10 ** (18 - IERC20Extra(fromToken).decimals())); return totalAmount; } function _amountErc20Bond(address fromToken, uint256 totalAmount, uint256 nativeRatio) internal returns (uint256) { /* lets pack ERC20 token meta data and scale amount to 18 decimals */ uint8 decimals = IERC20Extra(fromToken).decimals(); require(decimals <= 18, "decimals overflow"); uint256 totalShares = _nativeAmountToShares(totalAmount, nativeRatio, decimals); totalShares *= (10 ** (18 - decimals)); return totalShares; } function _currentChainNativeMetaData() internal view returns (Metadata memory) { return _nativeTokenMetadata; } // WITHDRAWAL FUNCTIONS function withdraw( bytes calldata /* encodedProof */, bytes calldata rawReceipt, bytes memory proofSignature ) external nonReentrant whenNotPaused override { uint256 proofOffset; uint256 receiptOffset; assembly { proofOffset := add(0x4, calldataload(4)) receiptOffset := add(0x4, calldataload(36)) } /* we must parse and verify that tx and receipt matches */ (EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType) = EthereumVerifier.parseTransactionReceipt(receiptOffset); require(state.chainId == Utils.currentChain(), "receipt points to another chain"); ProofParser.Proof memory proof = ProofParser.parseProof(proofOffset); require(_bridgeAddressByChainId[proof.chainId] == state.contractAddress, "crosschain event from not allowed contract"); state.receiptHash = keccak256(rawReceipt); proof.status = 0x01; // execution must be successful proof.receiptHash = state.receiptHash; // ensure that rawReceipt is preimage of receiptHash bytes32 hash; assembly { hash := keccak256(proof, 0x100) } // we can trust receipt only if proof is signed by consensus require(ECDSAUpgradeable.recover(hash, proofSignature) == _consensusAddress, "bad signature"); // withdraw funds to recipient _withdraw(state, pegInType, hash); } function _withdraw(EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType, bytes32 proofHash) internal { /* make sure these proofs wasn't used before */ require(!_usedProofs[proofHash], "proof already used"); _usedProofs[proofHash] = true; if (state.toToken == _nativeTokenMetadata.originAddress) { _withdrawNative(state); } else if (pegInType == EthereumVerifier.PegInType.Lock) { _withdrawPegged(state, state.fromToken); } else if (state.toToken != state.originToken) { // origin token is not deployed by our bridge so collision is not possible _withdrawPegged(state, state.originToken); } else { _withdrawErc20(state); } } function _withdrawNative(EthereumVerifier.State memory state) internal { state.toAddress.transfer(state.totalAmount); emit WithdrawUnlocked( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } function _withdrawPegged(EthereumVerifier.State memory state, address origin) internal { /* create pegged token if it doesn't exist */ Metadata memory metadata = EthereumVerifier.getMetadata(state); InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1])); if (bondType == InternetBondType.NOT_BOND) { _factoryPeggedToken(state.toToken, metadata); } else { _factoryPeggedBond(state.toToken, metadata); } /* mint tokens (NB: mint for bonds accepts amount in shares) */ IERC20Mintable(state.toToken).mint(state.toAddress, state.totalAmount); /* emit peg-out event (its just informative event) */ emit WithdrawMinted( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } function _withdrawErc20(EthereumVerifier.State memory state) internal { Metadata memory metadata = EthereumVerifier.getMetadata(state); InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1])); /* we need to rescale this amount */ uint8 decimals = IERC20Extra(state.toToken).decimals(); require(decimals <= 18, "decimals overflow"); uint256 scaledAmount = state.totalAmount / (10 ** (18 - decimals)); if (bondType == InternetBondType.REBASING_BOND) { scaledAmount = Utils.multiplyAndDivideCeil(scaledAmount, 10 ** decimals, getNativeRatio(state.toToken)); } /* transfer tokens and make sure behaviour is correct (just in case) */ uint256 balanceBefore = IERC20(state.toToken).balanceOf(state.toAddress); require(IERC20Upgradeable(state.toToken).transfer(state.toAddress, scaledAmount), "can't transfer"); uint256 balanceAfter = IERC20(state.toToken).balanceOf(state.toAddress); require(balanceBefore <= balanceAfter, "incorrect behaviour"); /* emit peg-out event (its just informative event) */ emit WithdrawUnlocked( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } // OWNER MAINTENANCE FUNCTIONS (owner functions will be reduced in future releases) function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external onlyOwner override { // make sure this chain is supported require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract"); // calc target token address toToken = _bridgeRouter.peggedTokenAddress(address(this), metaData.originAddress); require(_peggedTokenOrigin[toToken] == address(0x00), "already exists"); // deploy new token (its just a warmup operation) _factoryPeggedToken(toToken, metaData); } function _factoryPeggedToken(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) { address fromToken = metaData.originAddress; /* if pegged token exist we can just return its address */ if (_peggedTokenOrigin[toToken] != address(0x00)) { return IERC20Mintable(toToken); } /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ (bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall( abi.encodeWithSignature("factoryPeggedToken(address,address,(bytes32,bytes32,uint256,address,bytes32),address)", fromToken, toToken, metaData, address(this)) ); if (!success) { // preserving error message uint256 returnLength = returnValue.length; assembly { revert(add(returnValue, 0x20), returnLength) } } /* now we can mark this token as pegged */ _peggedTokenOrigin[toToken] = fromToken; /* to token is our new pegged token */ return IERC20Mintable(toToken); } function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external onlyOwner override { // make sure this chain is supported require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract"); // calc target token address toToken = _bridgeRouter.peggedBondAddress(address(this), metaData.originAddress); require(_peggedTokenOrigin[toToken] == address(0x00), "already exists"); // deploy new token (its just a warmup operation) _factoryPeggedBond(toToken, metaData); } function _factoryPeggedBond(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) { address fromToken = metaData.originAddress; if (_peggedTokenOrigin[toToken] != address(0x00)) { return IERC20Mintable(toToken); } /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ (bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall( abi.encodeWithSignature("factoryPeggedBond(address,address,(bytes32,bytes32,uint256,address,bytes32),address,address)", fromToken, toToken, metaData, address(this), address(_internetBondRatioFeed)) ); if (!success) { // preserving error message uint256 returnLength = returnValue.length; assembly { revert(add(returnValue, 0x20), returnLength) } } /* now we can mark this token as pegged */ _peggedTokenOrigin[toToken] = fromToken; /* to token is our new pegged token */ return IERC20Mintable(toToken); } function addAllowedContract(address allowedContract, uint256 toChain) public onlyOwner { require(_bridgeAddressByChainId[toChain] == address(0x00), "already allowed"); require(toChain > 0, "chain id must be positive"); _bridgeAddressByChainId[toChain] = allowedContract; emit ContractAllowed(allowedContract, toChain); } function removeAllowedContract(uint256 toChain) public onlyOwner { require(_bridgeAddressByChainId[toChain] != address(0x00), "already disallowed"); require(toChain > 0, "chain id must be positive"); address wasContract = _bridgeAddressByChainId[toChain]; delete _bridgeAddressByChainId[toChain]; emit ContractDisallowed(wasContract, toChain); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function changeConsensus(address consensus) public onlyOwner { require(consensus != address(0x0), "zero address disallowed"); _consensusAddress = consensus; emit ConsensusChanged(_consensusAddress); } function changeRouter(address router) public onlyOwner { require(router != address(0x0), "zero address disallowed"); _bridgeRouter = BridgeRouter(router); // We don't have special event for router change since it's very special technical contract // In future changing router will be disallowed } }
safety check that iteration is finished
require(topicsIter == logIter);
7,027,139
[ 1, 87, 1727, 14369, 866, 716, 6532, 353, 6708, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 17905, 2360, 422, 613, 2360, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x7Bd6062a2056Ba6b9775EfF89fdAa507Ba4B9E14/sources/baal.sol
@notice Baal-only function to set flash fee numerator.
function setFlashFeeNumerator(uint32 _flashFeeNumerator) external baalOnly { flashFeeNumerator = _flashFeeNumerator; }
12,297,305
[ 1, 38, 69, 287, 17, 3700, 445, 358, 444, 9563, 14036, 16730, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27059, 14667, 2578, 7385, 12, 11890, 1578, 389, 13440, 14667, 2578, 7385, 13, 3903, 9846, 287, 3386, 288, 203, 3639, 9563, 14667, 2578, 7385, 273, 389, 13440, 14667, 2578, 7385, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0 <0.9.0; contract Query { address public serviceContractAddress; // Initializing service contract address in constructor constructor() { serviceContractAddress = 0xA6Abc17819738299B3B2c1CE46d55c74f04E290C; } // Queries peers details function getPeers() public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getPeers()"); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } // Queries a block details function getBlock(string memory height) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getBlock(string)", height); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } // Queries roles details function getRoles() public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getRoles()"); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } // Queries permissions of a role function getRolePermissions(string memory role) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getRolePermissions(string)", role); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } }
Queries permissions of a role
function getRolePermissions(string memory role) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getRolePermissions(string)", role); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; }
1,830,129
[ 1, 9592, 4371, 434, 279, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15673, 6521, 12, 1080, 3778, 2478, 13, 1071, 1135, 261, 3890, 3778, 563, 13, 288, 203, 3639, 1731, 3778, 2385, 273, 24126, 18, 3015, 1190, 5374, 12, 203, 5411, 315, 588, 2996, 6521, 12, 1080, 2225, 16, 203, 5411, 2478, 1769, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 325, 13, 273, 1758, 12, 3278, 8924, 1887, 2934, 22216, 1991, 12, 7648, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 668, 4440, 1156, 6835, 445, 8863, 203, 3639, 563, 273, 325, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg interface DharmaUpgradeBeaconControllerManagerInterface { // Fire an event whenever the Adharma Contingency is activated or exited. event AdharmaContingencyActivated(); event AdharmaContingencyExited(); // Store timestamp and last implementation in case of Adharma Contingency. struct AdharmaContingency { bool armed; bool activated; uint256 activationTime; } // Store all prior implementations and allow for blocking rollbacks to them. struct PriorImplementation { address implementation; bool rollbackBlocked; } function initiateUpgrade( address controller, address beacon, address implementation, uint256 extraTime ) external; function upgrade( address controller, address beacon, address implementation ) external; function agreeToAcceptControllerOwnership( address controller, bool willAcceptOwnership ) external; function initiateTransferControllerOwnership( address controller, address newOwner, uint256 extraTime ) external; function transferControllerOwnership( address controller, address newOwner ) external; function heartbeat() external; function newHeartbeater(address heartbeater) external; function armAdharmaContingency(bool armed) external; function activateAdharmaContingency() external; function rollback(address controller, address beacon, uint256 index) external; function blockRollback( address controller, address beacon, uint256 index ) external; function exitAdharmaContingency( address smartWalletImplementation, address keyRingImpmementation ) external; function getTotalPriorImplementations( address controller, address beacon ) external view returns (uint256 totalPriorImplementations); function getPriorImplementation( address controller, address beacon, uint256 index ) external view returns (address priorImplementation, bool rollbackAllowed); function heartbeatStatus() external view returns ( bool expired, uint256 expirationTime ); } interface UpgradeBeaconControllerInterface { function upgrade(address beacon, address implementation) external; } interface TimelockerModifiersInterface { function initiateModifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval, uint256 extraTime ) external; function modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) external; function initiateModifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration, uint256 extraTime ) external; function modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) external; } 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { address private _owner; address private _newPotentialOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() public onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() public { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } } /** * @title Timelocker * @author 0age * @notice This contract allows contracts that inherit it to implement timelocks * on functions, where the `_setTimelock` internal function must first be called * and passed the target function selector and arguments. Then, a given time * interval must first fully transpire before the timelock functions can be * successfully called. Furthermore, once a timelock is complete, it will expire * after a period of time. In order to change timelock intervals or expirations, * the inheriting contract needs to implement `modifyTimelockInterval` and * `modifyTimelockExpiration` functions, respectively, as well as functions that * call `_setTimelock` in order to initiate the timelocks for those functions. * To make a function timelocked, use the `_enforceTimelock` internal function. * To set initial defult minimum timelock intervals and expirations, use the * `_setInitialTimelockInterval` and `_setInitialTimelockExpiration` internal * functions - they can only be used during contract creation. Finally, there * are three public getters: `getTimelock`, `getDefaultTimelockInterval`, and * `getDefaultTimelockExpiration`. */ contract Timelocker { using SafeMath for uint256; // Fire an event any time a timelock is initiated. event TimelockInitiated( bytes4 functionSelector, // selector of the function uint256 timeComplete, // timestamp at which the function can be called bytes arguments, // abi-encoded function arguments to call with uint256 timeExpired // timestamp where function can no longer be called ); // Fire an event any time a minimum timelock interval is modified. event TimelockIntervalModified( bytes4 functionSelector, // selector of the function uint256 oldInterval, // old minimum timelock interval for the function uint256 newInterval // new minimum timelock interval for the function ); // Fire an event any time a default timelock expiration is modified. event TimelockExpirationModified( bytes4 functionSelector, // selector of the function uint256 oldExpiration, // old default timelock expiration for the function uint256 newExpiration // new default timelock expiration for the function ); // Each timelock has timestamps for when it is complete and when it expires. struct Timelock { uint128 complete; uint128 expires; } // Functions have a timelock interval and time from completion to expiration. struct TimelockDefaults { uint128 interval; uint128 expiration; } // Implement a timelock for each function and set of arguments. mapping(bytes4 => mapping(bytes32 => Timelock)) private _timelocks; // Implement default timelock intervals and expirations for each function. mapping(bytes4 => TimelockDefaults) private _timelockDefaults; // Only allow one new interval or expiration change at a time per function. mapping(bytes4 => mapping(bytes4 => bytes32)) private _protectedTimelockIDs; // Store modifyTimelockInterval function selector as a constant. bytes4 private constant _MODIFY_TIMELOCK_INTERVAL_SELECTOR = bytes4( 0xe950c085 ); // Store modifyTimelockExpiration function selector as a constant. bytes4 private constant _MODIFY_TIMELOCK_EXPIRATION_SELECTOR = bytes4( 0xd7ce3c6f ); // Set a ridiculously high duration in order to protect against overflows. uint256 private constant _A_TRILLION_YEARS = 365000000000000 days; /** * @notice In the constructor, confirm that selectors specified as constants * are correct. */ constructor() internal { TimelockerModifiersInterface modifiers; bytes4 targetModifyInterval = modifiers.modifyTimelockInterval.selector; require( _MODIFY_TIMELOCK_INTERVAL_SELECTOR == targetModifyInterval, "Incorrect modify timelock interval selector supplied." ); bytes4 targetModifyExpiration = modifiers.modifyTimelockExpiration.selector; require( _MODIFY_TIMELOCK_EXPIRATION_SELECTOR == targetModifyExpiration, "Incorrect modify timelock expiration selector supplied." ); } /** * @notice View function to check if a timelock for the specified function and * arguments has completed. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. * @return A boolean indicating if the timelock exists or not and the time at * which the timelock completes if it does exist. */ function getTimelock( bytes4 functionSelector, bytes memory arguments ) public view returns ( bool exists, bool completed, bool expired, uint256 completionTime, uint256 expirationTime ) { // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // Get information on the current timelock, if one exists. completionTime = uint256(_timelocks[functionSelector][timelockID].complete); exists = completionTime != 0; expirationTime = uint256(_timelocks[functionSelector][timelockID].expires); completed = exists && now > completionTime; expired = exists && now > expirationTime; } /** * @notice View function to check the current minimum timelock interval on a * given function. * @param functionSelector function to retrieve the timelock interval for. * @return The current minimum timelock interval for the given function. */ function getDefaultTimelockInterval( bytes4 functionSelector ) public view returns (uint256 defaultTimelockInterval) { defaultTimelockInterval = uint256( _timelockDefaults[functionSelector].interval ); } /** * @notice View function to check the current default timelock expiration on a * given function. * @param functionSelector function to retrieve the timelock expiration for. * @return The current default timelock expiration for the given function. */ function getDefaultTimelockExpiration( bytes4 functionSelector ) public view returns (uint256 defaultTimelockExpiration) { defaultTimelockExpiration = uint256( _timelockDefaults[functionSelector].expiration ); } /** * @notice Internal function that sets a timelock so that the specified * function can be called with the specified arguments. Note that existing * timelocks may be extended, but not shortened - this can also be used as a * method for "cancelling" a function call by extending the timelock to an * arbitrarily long duration. Keep in mind that new timelocks may be created * with a shorter duration on functions that already have other timelocks on * them, but only if they have different arguments. * @param functionSelector selector of the function to be called. * @param arguments The abi-encoded arguments of the function to be called. * @param extraTime Additional time in seconds to add to the minimum timelock * interval for the given function. */ function _setTimelock( bytes4 functionSelector, bytes memory arguments, uint256 extraTime ) internal { // Ensure that the specified extra time will not cause an overflow error. require(extraTime < _A_TRILLION_YEARS, "Supplied extra time is too large."); // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // For timelock interval or expiration changes, first drop any existing // timelock for the function being modified if the argument has changed. if ( functionSelector == _MODIFY_TIMELOCK_INTERVAL_SELECTOR || functionSelector == _MODIFY_TIMELOCK_EXPIRATION_SELECTOR ) { // Determine the function that will be modified by the timelock. (bytes4 modifiedFunction, uint256 duration) = abi.decode( arguments, (bytes4, uint256) ); // Ensure that the new timelock duration will not cause an overflow error. require( duration < _A_TRILLION_YEARS, "Supplied default timelock duration to modify is too large." ); // Determine the current timelockID, if any, for the modified function. bytes32 currentTimelockID = ( _protectedTimelockIDs[functionSelector][modifiedFunction] ); // Determine if current timelockID differs from what is currently set. if (currentTimelockID != timelockID) { // Drop existing timelock if one exists and has a different timelockID. if (currentTimelockID != bytes32(0)) { delete _timelocks[functionSelector][currentTimelockID]; } // Register the new timelockID as the current protected timelockID. _protectedTimelockIDs[functionSelector][modifiedFunction] = timelockID; } } // Get timelock using current time, inverval for timelock ID, & extra time. uint256 timelock = uint256( _timelockDefaults[functionSelector].interval ).add(now).add(extraTime); // Get expiration time using timelock duration plus default expiration time. uint256 expiration = timelock.add( uint256(_timelockDefaults[functionSelector].expiration) ); // Get the current timelock, if one exists. Timelock storage timelockStorage = _timelocks[functionSelector][timelockID]; // Determine the duration of the current timelock. uint256 currentTimelock = uint256(timelockStorage.complete); // Ensure that the timelock duration does not decrease. Note that a new, // shorter timelock may still be set up on the same function in the event // that it is provided with different arguments. Also note that this can be // circumvented when modifying intervals or expirations by setting a new // timelock (removing the old one), then resetting the original timelock but // with a shorter duration. require( currentTimelock == 0 || timelock > currentTimelock, "Existing timelocks may only be extended." ); // Set timelock completion and expiration using timelock ID and extra time. timelockStorage.complete = uint128(timelock); timelockStorage.expires = uint128(expiration); // Emit an event with all of the relevant information. emit TimelockInitiated(functionSelector, timelock, arguments, expiration); } /** * @notice Internal function for setting a new timelock interval for a given * function selector. The default for this function may also be modified, but * excessive values will cause the `modifyTimelockInterval` function to become * unusable. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function _modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) internal { // Ensure that the timelock has been set and is completed. _enforceTimelockPrivate( _MODIFY_TIMELOCK_INTERVAL_SELECTOR, abi.encode(functionSelector, newTimelockInterval) ); // Clear out the existing timelockID protection for the given function. delete _protectedTimelockIDs[ _MODIFY_TIMELOCK_INTERVAL_SELECTOR ][functionSelector]; // Set new timelock interval and emit a `TimelockIntervalModified` event. _setTimelockIntervalPrivate(functionSelector, newTimelockInterval); } /** * @notice Internal function for setting a new timelock expiration for a given * function selector. Once the minimum interval has elapsed, the timelock will * expire once the specified expiration time has elapsed. Setting this value * too low will result in timelocks that are very difficult to execute * correctly. Be sure to override the public version of this function with * appropriate access controls. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration the new minimum timelock expiration to set for * the given function. */ function _modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) internal { // Ensure that the timelock has been set and is completed. _enforceTimelockPrivate( _MODIFY_TIMELOCK_EXPIRATION_SELECTOR, abi.encode(functionSelector, newTimelockExpiration) ); // Clear out the existing timelockID protection for the given function. delete _protectedTimelockIDs[ _MODIFY_TIMELOCK_EXPIRATION_SELECTOR ][functionSelector]; // Set new default expiration and emit a `TimelockExpirationModified` event. _setTimelockExpirationPrivate(functionSelector, newTimelockExpiration); } /** * @notice Internal function to set an initial timelock interval for a given * function selector. Only callable during contract creation. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function _setInitialTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) internal { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set the timelock interval and emit a `TimelockIntervalModified` event. _setTimelockIntervalPrivate(functionSelector, newTimelockInterval); } /** * @notice Internal function to set an initial timelock expiration for a given * function selector. Only callable during contract creation. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration the new minimum timelock expiration to set for * the given function. */ function _setInitialTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) internal { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set the timelock interval and emit a `TimelockExpirationModified` event. _setTimelockExpirationPrivate(functionSelector, newTimelockExpiration); } /** * @notice Internal function to ensure that a timelock is complete or expired * and to clear the existing timelock if it is complete so it cannot later be * reused. The function to enforce the timelock on is inferred from `msg.sig`. * @param arguments The abi-encoded arguments of the function to be called. */ function _enforceTimelock(bytes memory arguments) internal { // Enforce the relevant timelock. _enforceTimelockPrivate(msg.sig, arguments); } /** * @notice Private function to ensure that a timelock is complete or expired * and to clear the existing timelock if it is complete so it cannot later be * reused. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. */ function _enforceTimelockPrivate( bytes4 functionSelector, bytes memory arguments ) private { // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // Get the current timelock, if one exists. Timelock memory timelock = _timelocks[functionSelector][timelockID]; uint256 currentTimelock = uint256(timelock.complete); uint256 expiration = uint256(timelock.expires); // Ensure that the timelock is set and has completed. require( currentTimelock != 0 && currentTimelock <= now, "Timelock is incomplete." ); // Ensure that the timelock has not expired. require(expiration > now, "Timelock has expired."); // Clear out the existing timelock so that it cannot be reused. delete _timelocks[functionSelector][timelockID]; } /** * @notice Private function for setting a new timelock interval for a given * function selector. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function _setTimelockIntervalPrivate( bytes4 functionSelector, uint256 newTimelockInterval ) private { // Ensure that the new timelock interval will not cause an overflow error. require( newTimelockInterval < _A_TRILLION_YEARS, "Supplied minimum timelock interval is too large." ); // Get the existing timelock interval, if any. uint256 oldTimelockInterval = uint256( _timelockDefaults[functionSelector].interval ); // Update the timelock interval on the provided function. _timelockDefaults[functionSelector].interval = uint128(newTimelockInterval); // Emit a `TimelockIntervalModified` event with the appropriate arguments. emit TimelockIntervalModified( functionSelector, oldTimelockInterval, newTimelockInterval ); } /** * @notice Private function for setting a new timelock expiration for a given * function selector. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockExpiration the new default timelock expiration to set for * the given function. */ function _setTimelockExpirationPrivate( bytes4 functionSelector, uint256 newTimelockExpiration ) private { // Ensure that the new timelock expiration will not cause an overflow error. require( newTimelockExpiration < _A_TRILLION_YEARS, "Supplied default timelock expiration is too large." ); // Ensure that the new timelock expiration is not too short. require( newTimelockExpiration > 1 minutes, "New timelock expiration is too short." ); // Get the existing timelock expiration, if any. uint256 oldTimelockExpiration = uint256( _timelockDefaults[functionSelector].expiration ); // Update the timelock expiration on the provided function. _timelockDefaults[functionSelector].expiration = uint128( newTimelockExpiration ); // Emit a `TimelockExpirationModified` event with the appropriate arguments. emit TimelockExpirationModified( functionSelector, oldTimelockExpiration, newTimelockExpiration ); } } /** * @title DharmaUpgradeBeaconControllerManager * @author 0age * @notice This contract will be owned by DharmaUpgradeMultisig and will manage * upgrades to the global smart wallet and key ring implementation contracts via * dedicated control over the "upgrade beacon" controller contracts (and can * additionally be used to manage other upgrade beacon controllers). It contains * a set of timelocked functions, where the `setTimelock` function must first be * called, with the same arguments that the function will be supplied with. * Then, a given time interval must first fully transpire before the timelock * functions can be successfully called. * * The timelocked functions currently implemented include: * upgrade(address controller, address implementation) * transferControllerOwnership(address controller, address newOwner) * modifyTimelockInterval(bytes4 functionSelector, uint256 newTimelockInterval) * modifyTimelockExpiration( * bytes4 functionSelector, uint256 newTimelockExpiration * ) * * This contract also allows for immediately triggering a "rollback" to a prior * implementation in the event that a new vulnerability is introduced. It can * roll back to any implementation for a given controller + upgrade beacon pair * unless that implementation has been explicitly "blocked" by the owner. * * It also specifies dedicated implementations for the Dharma Smart Wallet and * Dharma Key Ring upgrade beacons that can be triggered in an emergency or in * the event of an extended period of inactivity from Dharma. These contingency * implementations give the user the ability to withdraw any funds on their * smart wallet by submitting a transaction directly from the account of any of * their signing keys, but are otherwise kept as simple as possible. After 48 * hours in the contingency state, the owner may bypass the standard upgrade * timelock and trigger upgrades to the smart wallet and key ring implementation * contracts. (Note that triggering a rollback) * * This contract can transfer ownership of any upgrade beacon controller it owns * (subject to the timelock on `transferControllerOwnership`), in order to * introduce new upgrade conditions or to otherwise alter the way that upgrades * are carried out. */ contract DharmaUpgradeBeaconControllerManager is DharmaUpgradeBeaconControllerManagerInterface, TimelockerModifiersInterface, TwoStepOwnable, Timelocker { using SafeMath for uint256; // Store prior implementation addresses for each controller + beacon pair. mapping(address => mapping (address => PriorImplementation[])) private _implementations; // New controller owners must accept ownership before a transfer can occur. mapping(address => mapping(address => bool)) private _willAcceptOwnership; // Store information on the current Adharma Contingency status. AdharmaContingency private _adharma; // Track the last heartbeat timestamp as well as the current heartbeat address uint256 private _lastHeartbeat; address private _heartbeater; // Store address of Smart Wallet Upgrade Beacon Controller as a constant. address private constant _SMART_WALLET_UPGRADE_BEACON_CONTROLLER = address( 0x00000000002226C940b74d674B85E4bE05539663 ); // Store the address of the Dharma Smart Wallet Upgrade Beacon as a constant. address private constant _DHARMA_SMART_WALLET_UPGRADE_BEACON = address( 0x000000000026750c571ce882B17016557279ADaa ); // Store the Adharma Smart Wallet Contingency implementation. address private constant _ADHARMA_SMART_WALLET_IMPLEMENTATION = address( 0x00000000009f22dA6fEB6735614563B9Af0339fB ); // Store address of Key Ring Upgrade Beacon Controller as a constant. address private constant _KEY_RING_UPGRADE_BEACON_CONTROLLER = address( 0x00000000011dF015e8aD00D7B2486a88C2Eb8210 ); // Store the address of the Dharma Key Ring Upgrade Beacon as a constant. address private constant _DHARMA_KEY_RING_UPGRADE_BEACON = address( 0x0000000000BDA2152794ac8c76B2dc86cbA57cad ); // Store the Adharma Key Ring Contingency implementation. address private constant _ADHARMA_KEY_RING_IMPLEMENTATION = address( 0x0000000055551209ABF26d0061000b3CCd81eC98 ); /** * @notice In the constructor, set tx.origin as initial owner, the initial * minimum timelock interval and expiration values, and some initial variable * values. */ constructor() public { // Ensure Smart Wallet Upgrade Beacon Controller has correct runtime code. bytes32 smartWalletControllerHash; bytes32 expectedSmartWalletControllerHash = bytes32( 0x6586626c057b68d99775ec4cae9aa5ce96907fb5f8d8c8046123f49f8ad93f1e ); address smartWalletController = _SMART_WALLET_UPGRADE_BEACON_CONTROLLER; assembly { smartWalletControllerHash := extcodehash(smartWalletController) } require( smartWalletControllerHash == expectedSmartWalletControllerHash, "Smart Wallet Upgrade Beacon Controller runtime code hash is incorrect." ); // Ensure Smart Wallet Upgrade Beacon has correct runtime code. bytes32 smartWalletUpgradeBeaconHash; bytes32 expectedSmartWalletUpgradeBeaconHash = bytes32( 0xca51e36cf6ab9af9a6f019a923588cd6df58aa1e58f5ac1639da46931167e436 ); address smartWalletBeacon = _DHARMA_SMART_WALLET_UPGRADE_BEACON; assembly { smartWalletUpgradeBeaconHash := extcodehash(smartWalletBeacon) } require( smartWalletUpgradeBeaconHash == expectedSmartWalletUpgradeBeaconHash, "Smart Wallet Upgrade Beacon runtime code hash is incorrect." ); // Ensure Adharma Smart Wallet implementation has the correct runtime code. bytes32 adharmaSmartWalletHash; bytes32 expectedAdharmaSmartWalletHash = bytes32( 0xa8d641085d608420781e0b49768aa57d6e19dfeef227f839c33e2e00e2b8d82e ); address adharmaSmartWallet = _ADHARMA_SMART_WALLET_IMPLEMENTATION; assembly { adharmaSmartWalletHash := extcodehash(adharmaSmartWallet) } require( adharmaSmartWalletHash == expectedAdharmaSmartWalletHash, "Adharma Smart Wallet implementation runtime code hash is incorrect." ); // Ensure Key Ring Upgrade Beacon Controller has correct runtime code. bytes32 keyRingControllerHash; bytes32 expectedKeyRingControllerHash = bytes32( 0xb98d105738145a629aeea247cee5f12bb25eabc1040eb01664bbc95f0e7e8d39 ); address keyRingController = _KEY_RING_UPGRADE_BEACON_CONTROLLER; assembly { keyRingControllerHash := extcodehash(keyRingController) } require( keyRingControllerHash == expectedKeyRingControllerHash, "Key Ring Upgrade Beacon Controller runtime code hash is incorrect." ); // Ensure Key Ring Upgrade Beacon has correct runtime code. bytes32 keyRingUpgradeBeaconHash; bytes32 expectedKeyRingUpgradeBeaconHash = bytes32( 0xb65d03cdc199085ae86b460e897b6d53c08a6c6d436063ea29822ea80d90adc3 ); address keyRingBeacon = _DHARMA_KEY_RING_UPGRADE_BEACON; assembly { keyRingUpgradeBeaconHash := extcodehash(keyRingBeacon) } require( keyRingUpgradeBeaconHash == expectedKeyRingUpgradeBeaconHash, "Key Ring Upgrade Beacon runtime code hash is incorrect." ); // Ensure Adharma Key Ring implementation has the correct runtime code. bytes32 adharmaKeyRingHash; bytes32 expectedAdharmaKeyRingHash = bytes32( 0xb23aba0d8cc5eadd7cbac3b303d8e915ec35aff2a910adebe7ef05ddbaa67501 ); address adharmaKeyRing = _ADHARMA_KEY_RING_IMPLEMENTATION; assembly { adharmaKeyRingHash := extcodehash(adharmaKeyRing) } require( adharmaKeyRingHash == expectedAdharmaKeyRingHash, "Adharma Key Ring implementation runtime code hash is incorrect." ); // Set initial minimum timelock interval values. _setInitialTimelockInterval( this.transferControllerOwnership.selector, 4 weeks ); _setInitialTimelockInterval(this.modifyTimelockInterval.selector, 4 weeks); _setInitialTimelockInterval( this.modifyTimelockExpiration.selector, 4 weeks ); _setInitialTimelockInterval(this.upgrade.selector, 7 days); // Set initial default timelock expiration values. _setInitialTimelockExpiration( this.transferControllerOwnership.selector, 7 days ); _setInitialTimelockExpiration(this.modifyTimelockInterval.selector, 7 days); _setInitialTimelockExpiration( this.modifyTimelockExpiration.selector, 7 days ); _setInitialTimelockExpiration(this.upgrade.selector, 7 days); // Set the initial owner as the initial heartbeater and trigger a heartbeat. _heartbeater = tx.origin; _lastHeartbeat = now; } /** * @notice Initiates a timelocked upgrade process via a given controller and * upgrade beacon to a given implementation address. Only the owner may call * this function. Once the timelock period is complete (and before it has * expired) the owner may call `upgrade` to complete the process and trigger * the upgrade. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateUpgrade( address controller, address beacon, address implementation, uint256 extraTime ) external onlyOwner { require(controller != address(0), "Must specify a controller address."); require(beacon != address(0), "Must specify a beacon address."); // Ensure that the implementaton contract is not the null address. require( implementation != address(0), "Implementation cannot be the null address." ); // Ensure that the implementation contract has code via extcodesize. uint256 size; assembly { size := extcodesize(implementation) } require(size > 0, "Implementation must have contract code."); // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.upgrade.selector, abi.encode(controller, beacon, implementation), extraTime ); } /** * @notice Timelocked function to set a new implementation address on an * upgrade beacon contract. Note that calling this function will cause the * contincency state to be exited if it is currently active. Only the owner * may call this function. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. */ function upgrade( address controller, address beacon, address implementation ) external onlyOwner { // Ensure that the timelock has been set and is completed. _enforceTimelock(abi.encode(controller, beacon, implementation)); // Exit contingency state if it is currently active and trigger a heartbeat. _exitAdharmaContingencyIfActiveAndTriggerHeartbeat(); // Call controller with beacon to upgrade and implementation to upgrade to. _upgrade(controller, beacon, implementation); } /** * @notice Allow a new potential owner of an upgrade beacon controller to * accept ownership of the controller. Anyone may call this function, though * ownership transfer of the controller in question will only proceed once the * owner calls `transferControllerOwnership`. * @param controller address of controller to allow ownership transfer for. * @param willAcceptOwnership a boolean signifying if an ownership transfer to * the caller is acceptable. */ function agreeToAcceptControllerOwnership( address controller, bool willAcceptOwnership ) external { require(controller != address(0), "Must specify a controller address."); // Register whether or not the new owner is willing to accept ownership. _willAcceptOwnership[controller][msg.sender] = willAcceptOwnership; } /** * @notice Initiates a timelock to set a new owner on an upgrade beacon * controller that is owned by this contract. Only the owner may call this * function. * @param controller address of controller to transfer ownership of. * @param newOwner address to assign ownership of the controller to. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateTransferControllerOwnership( address controller, address newOwner, uint256 extraTime ) external onlyOwner { require(controller != address(0), "No controller address provided."); require(newOwner != address(0), "No new owner address provided."); // Ensure that the new owner has confirmed that it can accept ownership. require( _willAcceptOwnership[controller][newOwner], "New owner must agree to accept ownership of the given controller." ); // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.transferControllerOwnership.selector, abi.encode(controller, newOwner), extraTime ); } /** * @notice Timelocked function to set a new owner on an upgrade beacon * controller that is owned by this contract. * @param controller address of controller to transfer ownership of. * @param newOwner address to assign ownership of the controller to. */ function transferControllerOwnership( address controller, address newOwner ) external onlyOwner { // Ensure that the new owner has confirmed that it can accept ownership. require( _willAcceptOwnership[controller][newOwner], "New owner must agree to accept ownership of the given controller." ); // Ensure that the timelock has been set and is completed. _enforceTimelock(abi.encode(controller, newOwner)); // Transfer ownership of the controller to the new owner. TwoStepOwnable(controller).transferOwnership(newOwner); } /** * @notice Send a new heartbeat. If 90 days pass without a heartbeat, anyone * may trigger the Adharma Contingency and force an upgrade to any controlled * upgrade beacon. */ function heartbeat() external { require(msg.sender == _heartbeater, "Must be called from the heartbeater."); _lastHeartbeat = now; } /** * @notice Set a new heartbeater. * @param heartbeater address to designate as the heartbeating address. */ function newHeartbeater(address heartbeater) external onlyOwner { require(heartbeater != address(0), "Must specify a heartbeater address."); _heartbeater = heartbeater; } /** * @notice Arm the Adharma Contingency upgrade. This is required as an extra * safeguard against accidentally triggering the Adharma Contingency. * @param armed Boolean that signifies the desired armed status. */ function armAdharmaContingency(bool armed) external { // Non-owners can only call if 90 days have passed since the last heartbeat. _ensureCallerIsOwnerOrDeadmansSwitchActivated(); // Arm (or disarm) the Adharma Contingency. _adharma.armed = armed; } /** * @notice Trigger the Adharma Contingency upgrade. This requires that the * owner first call `armAdharmaContingency` and set `armed` to `true`. This is * only to be invoked in cases of a time-sensitive emergency, or if the owner * has become inactive for over 90 days. It also requires that the Upgrade * Beacon Controller Manager contract still owns the specified upgrade beacon * controllers. It will simultaneously upgrade the Smart Wallet and the Key * Ring implementations to their designated contingency implementations. */ function activateAdharmaContingency() external { // Non-owners can only call if 90 days have passed since the last heartbeat. _ensureCallerIsOwnerOrDeadmansSwitchActivated(); // Ensure that the Adharma Contingency has been armed. require( _adharma.armed, "Adharma Contingency is not armed - are SURE you meant to call this?" ); // Ensure that the Adharma Contingency is not already active. require(!_adharma.activated, "Adharma Contingency is already activated."); // Ensure this contract still owns the required upgrade beacon controllers. _ensureOwnershipOfSmartWalletAndKeyRingControllers(); // Mark the Adharma Contingency as having been activated. _adharma = AdharmaContingency({ armed: false, activated: true, activationTime: now }); // Trigger upgrades on both beacons to the Adharma implementation contracts. _upgrade( _SMART_WALLET_UPGRADE_BEACON_CONTROLLER, _DHARMA_SMART_WALLET_UPGRADE_BEACON, _ADHARMA_SMART_WALLET_IMPLEMENTATION ); _upgrade( _KEY_RING_UPGRADE_BEACON_CONTROLLER, _DHARMA_KEY_RING_UPGRADE_BEACON, _ADHARMA_KEY_RING_IMPLEMENTATION ); // Emit an event to signal that the Adharma Contingency has been activated. emit AdharmaContingencyActivated(); } /** * @notice Roll back an upgrade to a prior implementation and exit from * contingency status if one currently exists. Note that you can also "roll * forward" a rollback to restore it to a more recent implementation that has * been rolled back from. If the Adharma Contingency state is activated, * triggering a rollback will cause it to be immediately exited - in that * event it is recommended to simultaneously roll back both the smart wallet * implementation and the key ring implementation. * @param controller address of controller to call into that will trigger the * rollback on the specified upgrade beacon. * @param beacon address of upgrade beacon to roll back to the last * implementation. * @param index uint256 the index of the implementation to roll back to. */ function rollback( address controller, address beacon, uint256 index ) external onlyOwner { // Ensure that there is an implementation address to roll back to. require( _implementations[controller][beacon].length > index, "No implementation with the given index available to roll back to." ); // Get the specified prior implementation. PriorImplementation memory priorImplementation = ( _implementations[controller][beacon][index] ); // Ensure rollbacks to the implementation have not already been blocked. require( !priorImplementation.rollbackBlocked, "Rollbacks to this implementation have been permanently blocked." ); // Exit contingency state if it is currently active and trigger a heartbeat. _exitAdharmaContingencyIfActiveAndTriggerHeartbeat(); // Upgrade to the specified implementation contract. _upgrade(controller, beacon, priorImplementation.implementation); } /** * @notice Permanently prevent a prior implementation from being rolled back * to. This can be used to prevent accidentally rolling back to an * implementation with a known vulnerability, or to remove the possibility of * a rollback once the security of more recent implementations has been firmly * established. Note that a blocked implementation can still be upgraded to in * the usual fashion, and after an additional upgrade it will become possible * to roll back to it unless it is blocked again. Only the owner may call this * function. * @param controller address of controller that was used to set the * implementation. * @param beacon address of upgrade beacon that the implementation was set on. * @param index uint256 the index of the implementation to block rollbacks to. */ function blockRollback( address controller, address beacon, uint256 index ) external onlyOwner { // Ensure that there is an implementation address to roll back to. require( _implementations[controller][beacon].length > index, "No implementation with the given index available to block." ); // Ensure rollbacks to the implementation have not already been blocked. require( !_implementations[controller][beacon][index].rollbackBlocked, "Rollbacks to this implementation are aleady blocked." ); // Permanently lock rollbacks to the implementation in question. _implementations[controller][beacon][index].rollbackBlocked = true; } /** * @notice Exit the Adharma Contingency by upgrading to new smart wallet and * key ring implementation contracts. This requires that the contingency is * currently activated and that at least 48 hours has elapsed since it was * activated. Only the owner may call this function. * @param smartWalletImplementation Address of the new smart wallet * implementation. * @param keyRingImpmementation Address of the new key ring implementation. */ function exitAdharmaContingency( address smartWalletImplementation, address keyRingImpmementation ) external onlyOwner { // Ensure that the Adharma Contingency is currently active. require( _adharma.activated, "Adharma Contingency is not currently activated." ); // Ensure that at least 48 hours has elapsed since the contingency commenced. require( now > _adharma.activationTime + 48 hours, "Cannot exit contingency with a new upgrade until 48 hours have elapsed." ); // Ensure this contract still owns the required upgrade beacon controllers. _ensureOwnershipOfSmartWalletAndKeyRingControllers(); // Exit the contingency state and trigger a heartbeat. _exitAdharmaContingencyIfActiveAndTriggerHeartbeat(); // Trigger upgrades on both beacons to the Adharma implementation contracts. _upgrade( _SMART_WALLET_UPGRADE_BEACON_CONTROLLER, _DHARMA_SMART_WALLET_UPGRADE_BEACON, smartWalletImplementation ); _upgrade( _KEY_RING_UPGRADE_BEACON_CONTROLLER, _DHARMA_KEY_RING_UPGRADE_BEACON, keyRingImpmementation ); } /** * @notice Sets the timelock for a new timelock interval for a given function * selector. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateModifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval, uint256 extraTime ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure a timelock interval over eight weeks is not set on this function. if (functionSelector == this.modifyTimelockInterval.selector) { require( newTimelockInterval <= 8 weeks, "Timelock interval of modifyTimelockInterval cannot exceed eight weeks." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockInterval.selector, abi.encode(functionSelector, newTimelockInterval), extraTime ); } /** * @notice Sets a new timelock interval for a given function selector. The * default for this function may also be modified, but has a maximum allowable * value of eight weeks. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. */ function modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `_modifyTimelockInterval` function. _modifyTimelockInterval(functionSelector, newTimelockInterval); } /** * @notice Sets a new timelock expiration for a given function selector. The * default Only the owner may call this function. New expiration durations may * not exceed one month. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateModifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration, uint256 extraTime ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure that the supplied default expiration does not exceed 1 month. require( newTimelockExpiration <= 30 days, "New timelock expiration cannot exceed one month." ); // Ensure a timelock expiration under one hour is not set on this function. if (functionSelector == this.modifyTimelockExpiration.selector) { require( newTimelockExpiration >= 60 minutes, "Expiration of modifyTimelockExpiration must be at least an hour long." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockExpiration.selector, abi.encode(functionSelector, newTimelockExpiration), extraTime ); } /** * @notice Sets a new timelock expiration for a given function selector. The * default for this function may also be modified, but has a minimum allowable * value of one hour. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. */ function modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `_modifyTimelockExpiration` function. _modifyTimelockExpiration( functionSelector, newTimelockExpiration ); } /** * @notice Get a count of total prior implementations for a given controller * and upgrade beacon. * @param controller address of controller that was used to set the * implementations. * @param beacon address of upgrade beacon that the implementations were set * on. * @return The total number of prior implementations. */ function getTotalPriorImplementations( address controller, address beacon ) external view returns (uint256 totalPriorImplementations) { // Get the total number of prior implementation contracts. totalPriorImplementations = _implementations[controller][beacon].length; } /** * @notice Get an implementation contract that has been used in the past for a * specific controller and beacon by index, and determine whether or not the * implementation can be rolled back to or not. * @param controller address of controller that was used to set the * implementation. * @param beacon address of upgrade beacon that the implementation was set on. * @param index uint256 the index of the implementation. * @return The address of the prior implementation if one exists and a boolean * representing whether or not the prior implementation can be rolled back to. */ function getPriorImplementation( address controller, address beacon, uint256 index ) external view returns (address priorImplementation, bool rollbackAllowed) { // Ensure that there is an implementation address with the given index. require( _implementations[controller][beacon].length > index, "No implementation contract found with the given index." ); // Get information on the specified prior implementation contract. PriorImplementation memory implementation = ( _implementations[controller][beacon][index] ); priorImplementation = implementation.implementation; rollbackAllowed = ( priorImplementation != address(0) && !implementation.rollbackBlocked ); } /** * @notice Determine if the Adharma Contingency state is currently armed or * activated, and if so, what time it was activated. An upgrade to arbitrary * smart wallet and key ring implementations can be performed by the owner * after 48 hours has elapsed in the contingency state. */ function contingencyStatus() external view returns ( bool armed, bool activated, uint256 activationTime ) { AdharmaContingency memory adharma = _adharma; armed = adharma.armed; activated = adharma.activated; activationTime = adharma.activationTime; } /** * @notice Determine if the deadman's switch has expired and get the time at * which it is set to expire (i.e. 90 days from the last heartbeat). * @return A boolean signifying whether the upgrade beacon controller is in an * expired state, as well as the expiration time. */ function heartbeatStatus() external view returns ( bool expired, uint256 expirationTime ) { (expired, expirationTime) = _heartbeatStatus(); } /** * @notice Internal view function to determine if the deadman's switch has * expired and to get the time at which it is set to expire (i.e. 90 days from * the last heartbeat). * @return A boolean signifying whether the upgrade beacon controller is in an * expired state, as well as the expiration time. */ function _heartbeatStatus() internal view returns ( bool expired, uint256 expirationTime ) { expirationTime = _lastHeartbeat + 90 days; expired = now > expirationTime; } /** * @notice Private function that sets a new implementation address on an * upgrade beacon contract. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. */ function _upgrade( address controller, address beacon, address implementation ) private { // Ensure that the implementaton contract is not the null address. require( implementation != address(0), "Implementation cannot be the null address." ); // Ensure that the implementation contract has code via extcodesize. uint256 size; assembly { size := extcodesize(implementation) } require(size > 0, "Implementation must have contract code."); // Try to get current implementation and store it as a prior implementation. (bool ok, bytes memory returnData) = beacon.call(""); if (ok && returnData.length == 32) { address currentImplementation = abi.decode(returnData, (address)); _implementations[controller][beacon].push(PriorImplementation({ implementation: currentImplementation, rollbackBlocked: false })); } // Trigger the upgrade to the new implementation contract. UpgradeBeaconControllerInterface(controller).upgrade( beacon, implementation ); } /** * @notice Private function that exits the Adharma Contingency if currently * active and triggers a heartbeat. */ function _exitAdharmaContingencyIfActiveAndTriggerHeartbeat() private { // Exit the contingency state if there is currently one active. if (_adharma.activated) { delete _adharma; emit AdharmaContingencyExited(); } // Reset the heartbeat to the current time. _lastHeartbeat = now; } /** * @notice Private view function to enforce that either the owner is the * caller, or that the deadman's switch has been activated as a result of 90 * days passing without a heartbeat. */ function _ensureCallerIsOwnerOrDeadmansSwitchActivated() private view { // Do not check if heartbeat has expired if the owner is the caller. if (!isOwner()) { // Determine if 90 days have passed since the last heartbeat. (bool expired, ) = _heartbeatStatus(); // Ensure that the deadman's switch is active. require( expired, "Only callable by the owner or after 90 days without a heartbeat." ); } } /** * @notice Private view function to enforce that this contract is still the * owner of the Dharma Smart Wallet Upgrade Beacon Controller and the Dharma * Key Ring Upgrade Beacon Controller prior to triggering the Adharma * Contingency, or prior to upgrading those contracts on exiting the Adharma * Contingency. */ function _ensureOwnershipOfSmartWalletAndKeyRingControllers() private view { // Ensure this contract still owns the required upgrade beacon controllers. require( TwoStepOwnable(_SMART_WALLET_UPGRADE_BEACON_CONTROLLER).isOwner(), "This contract no longer owns the Smart Wallet Upgrade Beacon Controller." ); require( TwoStepOwnable(_KEY_RING_UPGRADE_BEACON_CONTROLLER).isOwner(), "This contract no longer owns the Key Ring Upgrade Beacon Controller." ); } }
* @dev Initialize contract by setting transaction submitter as initial owner./
constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); }
1,759,356
[ 1, 7520, 6835, 635, 3637, 2492, 4879, 387, 487, 2172, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1435, 2713, 288, 203, 565, 389, 8443, 273, 2229, 18, 10012, 31, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.3; import {SafeMath} from "./SafeMath.sol"; import {Wallet} from "./Wallet.sol"; import {Identity} from "./Identity.sol"; import {Disbursement} from "./Disbursement.sol"; contract Campaigns { Wallet internal token; Identity internal id; Disbursement internal disb; using SafeMath for uint; /* Explaintation of campaign status * During: end date < now * Failed: end date >= now AND token collected < goal * Succeed: end date >= now AND token collected >= goal */ enum Status {during, failed, succeed} /* Explaintation of campaign FINACIAL status * Pending: new campaign just added. NOT allow donor fund to campaign * Accepted: a campaign was verified => Allow donors fund to campaign * Paid: a campaign that owner withdraw token completed => end campaign */ enum FinStatus {pending, accepted, rejected, paid} struct CampaignInfo { address owner; uint startDate; uint endDate; uint goal; uint collected; uint stage; FinStatus finstt; string ref; // store reference to other info as name, description on db string hashIntegrity; // hash of data store in server address[] donors; mapping(address => uint) donation; mapping(address => bool) isDonate; } CampaignInfo[] internal campaigns; mapping(address => uint[]) internal donor2campaigns; //mapping donors to campaigns id address internal deployer; event Added(uint id); event Accepted(uint id); event Donated(uint id, address donor, uint token); event Refund(uint id, address donor, uint token); event Paid(uint id, address ownerCampaign, uint token); /* -- Constructor -- */ // /// @notice Constructor to create a campaign contract /// @dev This contract MUST be run after Wallet /// @param addrIdentity is address of Identity contract constructor(Identity addrIdentity) public { deployer = msg.sender; id = addrIdentity; } /// @notice Update address of other contracts /// @param addrWallet is address of Wallet contract /// @param addrDisb is address of Disbursement contract function linkOtherContracts(Wallet addrWallet, Disbursement addrDisb) external { require( msg.sender == deployer, "Only deployer" ); token = addrWallet; disb = addrDisb; } /// @notice Get properties of a campaign /// @param i is index of campaigns array /// @return object {startDate, endDate, goal, collected, owner, finStatus, status, ref} function getInfo(uint i) external view returns( uint startDate, uint endDate, uint goal, uint collected, address owner, FinStatus finStatus, Status status, string memory ref, string memory hashIntegrity ) { ref = campaigns[i].ref; hashIntegrity = campaigns[i].hashIntegrity; startDate = campaigns[i].startDate; endDate = campaigns[i].endDate; goal = campaigns[i].goal; collected = campaigns[i].collected; owner = campaigns[i].owner; finStatus = campaigns[i].finstt; status = getStatus(i); } /// @notice Create a campaign /// @dev Add an element to variable campaigns array /// @param deadline is deadline for fundraising of a campaign. (unit: seconds) /// @param goal is goal of a campaign. Min-Max: 100.000-1.000.000.000 /// @param numStage is number of stage withdraw campaign /// @param amountStages is amount of each stage withdraw campaign /// @param mode is mode for disburse campaign /// @param timeStages is deadline for each stage withdraw campaign /// @param ref is campaign reference to other information about campaign /// @param hashData is hash of data will store in db server, to check integrity function createCampaign( uint deadline, uint goal, uint numStage, uint[] calldata amountStages, Disbursement.Mode mode, uint[] calldata timeStages, string calldata ref, string calldata hashData ) external { // To testing, you can comment following lines // require( // _goal >= 100000 && _goal <= 1000000000, // "The goal of campaign must be include range is from 100.000 to 1.000.000.000 tokens" // ); require( goal >= 1000 && goal <= 1e9, "Campaign's goal must be include range is from 1000 to 1.000.000.000 tokens" ); require( id.isVerified(msg.sender), "You must be register identity and be accepted" ); // To testing, you can comment following lines //require( // _days >= 15, // "The minimum fundraising time for the campaign is 15 days." //); campaigns.push(CampaignInfo( msg.sender, now, now + deadline, goal, 0, 0, FinStatus.pending, ref, hashData, new address[](0) )); // CampaignInfo memory temp; // temp.ref = ref; // temp.hashIntegrity = hashData; // temp.owner = msg.sender; // temp.startDate = now; // temp.endDate = now + deadline; // temp.goal = goal; // temp.collected = 0; // temp.finstt = FinStatus.pending; //In current Testing, default set Finacial Status is Accepted // campaigns.push(temp); if (numStage > 1) { if (amountStages.length != numStage) { revert('number element amount stage is invalid'); } if (mode >= Disbursement.Mode.TimingFlexible && timeStages.length != numStage) { revert('Number of deadline is invalid'); } uint sumOfAmount; uint[] memory times = new uint[](numStage); for (uint i = 0; i < numStage; i++) { sumOfAmount += amountStages[i]; if (mode >= Disbursement.Mode.TimingFlexible) { if (i == 0) { times[0] = now + deadline; } else { times[i] = times[i-1] + timeStages[i]; } } } if (sumOfAmount != goal) { revert('Sum of amount must be equal goal'); } disb.create( campaigns.length-1, numStage, amountStages, mode, times ); } emit Added(campaigns.length - 1); } /// @notice Count how many people donated into a campaign /// @param i is index of campaign /// @return Number of donors of a campaign function getNumberOfDonors(uint i) external view returns(uint) { return campaigns[i].donors.length; } /// @notice Determine a campaign is allow all donor can invest to that campaign /// @param i is index of campaigns array /// @param isAccept is variable used for decide a campaign be allowed transact function verifyCampaign(uint i, bool isAccept) external { require( id.isVerifier(msg.sender), "You MUST be verifier"); campaigns[i].finstt = isAccept ? FinStatus.accepted : FinStatus.rejected; emit Accepted(i); } /// @notice Allow donor can donate to a campaign /// @param i is index of campaigns array /// @param amount is amount of token that you want to donate function donate(uint i, uint amount) external { CampaignInfo memory campaign = campaigns[i]; require( amount > 0, "amount of token must be greater than zero" ); require( now <= campaign.endDate, "Campaign is ended" ); require( campaign.collected < campaign.goal, "Campaign is reached goal" ); require( campaign.collected + amount <= campaign.goal, "Amount without goal of campaign" ); require( campaigns[i].finstt == FinStatus.accepted, "This campaign MUST be accepted and NOT paid" ); require( amount <= (token.balances(msg.sender) - getAllDonation(msg.sender)), "You don't have enough token"); campaigns[i].donation[msg.sender] = campaigns[i].donation[msg.sender].add(amount); if (!campaigns[i].isDonate[msg.sender]) { donor2campaigns[msg.sender].push(i); campaigns[i].isDonate[msg.sender] = true; campaigns[i].donors.push(msg.sender); } campaigns[i].collected = campaigns[i].collected.add(amount); emit Donated(i, msg.sender, amount); } /// @notice Allow donor can claim refund when campaign during /// when campaign failed, you don't need claim refund, because it is automatic proccess /// @param i is index of campaigns array /// @param amount Amount donor want withdraw function claimRefund(uint i, uint amount) external { require( amount > 0, "amount of token must be greater than zero" ); require( campaigns[i].donation[msg.sender] >= amount, "You don't have enough to claim refund" ); require( getStatus(i) == Status.during, "You only can claim refund when campaigns during" ); campaigns[i].donation[msg.sender] -= amount; campaigns[i].collected -= amount; emit Refund(i, msg.sender, amount); } /// @notice Handle after campaign. Only allow campaign's owner run this function /// @dev If campaign is succeed, campaign's owner will receive funds /// @param i is index of campaign array function endCampaign(uint i) external { require( msg.sender == campaigns[i].owner, "This function MUST be run by owner" ); require( getStatus(i) == Status.succeed, "Campaign MUST be succeed" ); require( campaigns[i].finstt == FinStatus.accepted, "Campaign MUST be accepted (NOT reject or paid)"); uint numStage = 1; uint amount = 0; bool isCompleted = false; (numStage, amount) = disb.getWithdrawInfo( i, campaigns[i].stage, campaigns[i].donors.length, campaigns[i].collected ); if (numStage > 1) { if (amount > 0) { campaigns[i].stage += 1; if (campaigns[i].stage == numStage) { isCompleted = true; } } else { revert("Missing condition for withdraw"); } } else { // Important: set status PAID before call external function to withdraw isCompleted = true; amount = campaigns[i].collected; } if (amount > 0) { if (isCompleted) { campaigns[i].finstt = FinStatus.paid; } emit Paid(i, msg.sender, amount); if(!token.addToken(msg.sender, amount)) { if (isCompleted) { campaigns[i].finstt = FinStatus.accepted; } if (numStage > 1) { campaigns[i].stage -= 1; } } } } /// @notice Get token donated for a campaign of donor /// @param i is index of campaigns /// @param donor is address of donor that you want to check /// @return Number of token that donor donated for a campaign function getDonation(uint i, address donor) external view returns(uint) { return campaigns[i].donation[donor]; } /// @notice Get all amount of donor that invest to campaigns /// @dev Get all amount of donor that donated and have checked campaign failed or succeed /// If campaign is failed, NOT count that token /// @param donor is address that you want check to amount of invest /// @return Number of token that donated all campaigns function getAllDonation(address donor) public view returns(uint) { uint tokens = 0; uint[] memory campaignsOf = donor2campaigns[donor]; for (uint i = 0; i < campaignsOf.length; i++) { uint campID = campaignsOf[i]; if (getStatus(campID) != Status.failed) { if (campaigns[campID].donation[donor] > 0) { tokens += campaigns[campID].donation[donor]; } } } return tokens; } /// @notice Get list of campaign that donor donated /// @param donor is address of donor /// @return Array of campaign's id function getCampaignList(address donor) external view returns(uint[] memory) { return donor2campaigns[donor]; } /// @notice Get status of a campaign /// @param i is index of campaigns array /// @return {0 => during, 1 => failed, 2 => succeed, 3 => paid} function getStatus(uint i) public view returns(Status) { if (now < campaigns[i].endDate) { return Status.during; } else { if (campaigns[i].collected < campaigns[i].goal) { return Status.failed; } else { return Status.succeed; } } } /// @notice Get financial status of campaign /// @param i is index of campaign /// @return {0 => pending, 1 => accepted, 2 => paid} function getFinStatus(uint i) external view returns(FinStatus) { return campaigns[i].finstt; } /// @notice Get number of campaigns /// @return Number of campaigns function length() external view returns(uint) { return campaigns.length; } }
mapping donors to campaigns id
mapping(address => uint[]) internal donor2campaigns;
1,056,922
[ 1, 6770, 2727, 1383, 358, 8965, 87, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 63, 5717, 2713, 2727, 280, 22, 14608, 87, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]