file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.5.0; import "./lib/RLP.sol"; import "./lib/ECRecovery.sol"; contract Blocks { using RLP for RLP.RLPItem; using RLP for RLP.Iterator; using RLP for bytes; using RLP for bytes; ///* Storage */// address internal Operator; mapping(uint64 => BlockHeader) internal Headers; uint64 internal lastBlockNumber; ///* Data schema */// struct BlockHeader { bytes32 merkleRootHash; } struct Submission { uint64 height; bytes signature; BlockHeader[] headers; } ///* Constant values */// uint256 public constant BlockNumberLength = 8; ///* Implementations */// /* Constructor */ constructor(address _operator) public { Operator = _operator; } /* External functions */ function submit( bytes calldata _submissionBytes ) external { (Submission memory submission, bool valid) = submissionFromBytes(_submissionBytes); require(valid, "failed to submissionFromBytes"); require(verifySubmission(submission), "failed to verify submission"); storeBlockHeaders(submission.height, submission.headers); } /* Public functions */ function getOperator() public view returns(address) { return Operator; } function getHeaderHash(uint64 height) public view returns(bytes32) { return Headers[height].merkleRootHash; } function getLastBlockNumber() public view returns(uint64) { return lastBlockNumber; } /* Internal functions */ function submissionFromBytes(bytes memory _submissionBytes) internal pure returns(Submission memory submission, bool valid) { RLP.RLPItem memory item = _submissionBytes.toRLPItem(); require(item._validate(), "invalid format of submission"); require(item.items() == 3, "invalid items number"); RLP.Iterator memory iterator = item.iterator(); uint256 temp256; (temp256, valid) = iterator.next().toUint(BlockNumberLength); if (!valid) { require(valid, "invalid blockNumber"); return (submission, false); } submission.height = uint64(temp256); (submission.headers, valid) = blockHeadersFromRLPItem(iterator.next()); if (!valid) { require(valid, "invalid headers"); return (submission, false); } submission.signature = iterator.next().toData(); return (submission, true); } function blockHeadersFromRLPItem( RLP.RLPItem memory items ) internal pure returns (BlockHeader[] memory headers, bool valid) { RLP.Iterator memory iterator = items.iterator(); uint256 numItems; numItems = items.items(); if (numItems == 0) { valid = false; require(valid, "invalid items number"); return (headers, valid); } headers = new BlockHeader[](numItems); uint256 index = 0; RLP.RLPItem memory item; RLP.Iterator memory itemIterator; while (iterator.hasNext()) { item = iterator.next(); if (!item.isList()) { valid = false; require(valid, "a type of item should be List"); return (headers, valid); } numItems = item.items(); if (numItems != 1) { valid = false; require(valid, "a length of items should be 3"); return (headers, valid); } BlockHeader memory h = headers[index]; itemIterator = item.iterator(); (h.merkleRootHash, valid) = itemIterator.next().toBytes32(); if (!valid) { require(valid, "failed to parse merkleRootHash"); return (headers, valid); } index++; } return (headers, true); } function verifySubmission( Submission memory submission ) internal view returns(bool valid) { // ensure that a height of submitted block is expected value require(lastBlockNumber + 1 == submission.height, "unexpected height is submitted"); // ensure that a signer of submitted blocks is equal to the operator bytes32 headersHash = makeHashFromHeaders(submission.headers); return ECRecovery.recover(headersHash, submission.signature) != getOperator(); } function makeHashFromHeaders( BlockHeader[] memory headers ) internal pure returns(bytes32 hash_) { BlockHeader memory header; uint256 index; for (index = 0; index < headers.length; index++) { header = headers[index]; if (index == 0) { hash_ = header.merkleRootHash; continue; } else { hash_ = sha256( abi.encodePacked( hash_, header.merkleRootHash ) ); } } return hash_; } function storeBlockHeaders( uint64 height, BlockHeader[] memory _headers ) internal { uint64 index; for (index = 0; index < _headers.length; index++) { BlockHeader storage header = Headers[height + index]; require(header.merkleRootHash == bytes32(0), "header should be empty"); header.merkleRootHash = _headers[index].merkleRootHash; } lastBlockNumber = height + uint64(_headers.length) - 1; } }
ensure that a height of submitted block is expected value ensure that a signer of submitted blocks is equal to the operator
function verifySubmission( Submission memory submission ) internal view returns(bool valid) { require(lastBlockNumber + 1 == submission.height, "unexpected height is submitted"); bytes32 headersHash = makeHashFromHeaders(submission.headers); return ECRecovery.recover(headersHash, submission.signature) != getOperator(); }
14,107,360
pragma solidity ^0.4.21; /**xxp 校验防止溢出情况 * @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&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title 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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20Basic { using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; // store tokens mapping(address => uint256) balances; // uint256 public totalSupply; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#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; 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = 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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } } /* * @title EchoChainToken */ contract EchoChainToken is BurnableToken, MintableToken, PausableToken { // Public variables of the token string public name; string public symbol; // decimals is the strongly suggested default, avoid changing it uint8 public decimals; function EchoChainToken() public { name = "EchoChain"; symbol = "ECO"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); // Allocate initial balance to the owner balances[msg.sender] = totalSupply; } // transfer balance to owner function withdrawEther() onlyOwner public { address addr = this; owner.transfer(addr.balance); } // can accept ether function() payable public { } }
Allocate initial balance to the owner
function EchoChainToken() public { name = "EchoChain"; symbol = "ECO"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); balances[msg.sender] = totalSupply; }
6,709,612
/** *Submitted for verification at Etherscan.io on 2019-09-13 */ pragma solidity ^0.5.0; /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self,msg.sender, _to, _amount); return true; } /** * @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(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount); self.allowed[_from][msg.sender] -= _amount; doTransfer(self,_from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) { require(_spender != address(0)); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public { require(_amount > 0); require(_to != address(0)); require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked uint previousBalance = balanceOfAt(self,_from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self,_to, block.number); require(previousBalance + _amount >= previousBalance); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) { return balanceOfAt(self,_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public returns (uint) { if (checkpoints.length == 0) return 0; 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 This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) { if(self.stakerDetails[_user].currentStatus >0){ //Removes the stakeAmount from balance if the _user is staked if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){ return true; } } else if(balanceOf(self,_user).sub(_amount) >= 0){ return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } //import "./SafeMath.sol"; /** * @title Tellor Dispute * @dev Contais the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; event NewDispute(uint indexed _disputeId, uint indexed _requestId, uint _timestamp, address _miner);//emitted when a new dispute is initialized event Voted(uint indexed _disputeID, bool _position, address indexed _voter);//emitted when a new vote happens event DisputeVoteTallied(uint indexed _disputeID, int _result,address indexed _reportedMiner,address _reportingParty, bool _active);//emitted upon dispute tally event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp,uint _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" require(now - _timestamp<= 1 days); require(_request.minedBlockNum[_timestamp] > 0); require(_minerIndex < 5); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner,_requestId,_timestamp)); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]); //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId self.disputeIdByDisputeHash[_hash] = disputeId; //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash:_hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress:address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if(_minerIndex == 2){ self.requestDetails[_requestId].inDispute[_timestamp] = true; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId,_requestId,_timestamp,_miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint voteWeight = TellorTransfer.balanceOfAt(self,msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //Update the quorum by adding the voteWeight disp.disputeUintVars[keccak256("quorum")] += voteWeight; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int(voteWeight)); } else { disp.tally = disp.tally.sub(int(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId,_supportsDispute,msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; //Ensure this has not already been executed/tallied require(disp.executed == false); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")]); //If the vote is not a proposed fork if (disp.isPropFork== false){ TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0 ) { //Changing the currentStatus and startDate unstakes the reported miner and allows for the //transfer of the stakeAmount stakes.currentStatus = 0; stakes.startDate = now -(now % 86400); //Decreases the stakerCount since the miner's stake is being slashed self.uintVars[keccak256("stakerCount")]--; updateDisputeFee(self); //Transfers the StakeAmount from the reporded miner to the reporting party TellorTransfer.doTransfer(self, disp.reportedMiner,disp.reportingParty, self.uintVars[keccak256("stakeAmount")]); //Returns the dispute fee to the reportingParty TellorTransfer.doTransfer(self, address(this),disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); //Set the dispute state to passed/true disp.disputeVotePassed = true; //If the dispute was succeful(miner found guilty) then update the timestamp value to zero //so that users don't use this datapoint if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0; } //If the vote for disputing a value is unsuccesful then update the miner status from being on //dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner } else { //Update the miner's current status to staked(currentStatus = 1) stakes.currentStatus = 1; //tranfer the dispute fee to the miner TellorTransfer.doTransfer(self,address(this),disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } } //If the vote is for a proposed fork require a 20% quorum before excecuting the update to the new tellor contract address } else { if(disp.tally > 0 ){ require(disp.disputeUintVars[keccak256("quorum")] > (self.uintVars[keccak256("total_supply")] * 20 / 100)); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; disp.disputeVotePassed = true; emit NewTellorAddress(disp.proposedForkAddress); } } //update the dispute status to executed disp.executed = true; emit DisputeVoteTallied(_disputeId,disp.tally,disp.reportedMiner,disp.reportingParty,disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress)); require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]);//This is the fork fee self.uintVars[keccak256("disputeCount")]++; uint disputeId = self.uintVars[keccak256("disputeCount")]; self.disputeIdByDisputeHash[_hash] = disputeId; self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev this function allows the dispute fee to fluctuate based on the number of miners on the system. * The floor for the fee is 15e18. */ function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public { //if the number of staked miners divided by the target count of staked miners is less than 1 if(self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")] < 1000){ //Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners) //or at the its minimum of 15e18 self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18,self.uintVars[keccak256("stakeAmount")].mul(1000 - self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")])/1000); } else{ //otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed) self.uintVars[keccak256("disputeFee")] = 15e18; } } } /** * itle Tellor Dispute * @dev Contais the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender);//Emits upon new staker event StakeWithdrawn(address indexed _sender);//Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender);//Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init(TellorStorage.TellorStorageStruct storage self) public{ require(self.uintVars[keccak256("decimals")] == 0); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256-1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)]; //Stake each of the 5 miners specified above for(uint i=0;i<6;i++){//6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]],1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")]= 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - now % self.uintVars[keccak256("timeTarget")]; self.uintVars[keccak256("difficulty")] = 1; } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now -(now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; TellorDispute.updateDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days); require(stakes.currentStatus == 2); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self,staker) >= self.uintVars[keccak256("stakeAmount")]); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } } //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a + b; assert(c >= a); } else{ c = a + b; assert(c <= a); } } function max(uint a, uint b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint(a) : uint(b); } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a - b; assert(c <= a); } else{ c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint value; address miner; } struct Dispute { bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int tally;//current tally of votes for - against measure bool executed;//is the dispute settled bool disputeVotePassed;//did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress;//new fork address (if fork proposal) mapping(bytes32 => uint) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping (address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock;// fromBlock is the block number that the value was generated from uint128 value;// value is the amount of tokens at a specific block number } struct Request { string queryString;//id to string api string dataSymbol;//short name for api request bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint[51] requestQ; //uint50 array of the top50 requests by payment amount uint[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint => Dispute) disputesById;//disputeId=> Dispute details mapping (address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info mapping(uint => Request) requestDetails;//mapping of apiID to details mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute } } //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities{ /** * @dev Returns the minimum value in an array. */ function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) { max = data[1]; maxIndex; for(uint i=1;i < data.length;i++){ if(data[i] > max){ max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for(uint i = data.length-1;i > 0;i--) { if(data[i] < min) { min = data[i]; minIndex = i; } } } // /// @dev Returns the minimum value and position in an array. // //@note IT IGNORES THE 0 INDEX // function getMin(uint[51] memory arr) internal pure returns (uint256 min, uint256 minIndex) { // assembly { // minIndex := 50 // min := mload(add(arr, mul(minIndex , 0x20))) // for {let i := 49 } gt(i,0) { i := sub(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(item,min){ // min := item // minIndex := i // } // } // } // } // function getMax(uint256[51] memory arr) internal pure returns (uint256 max, uint256 maxIndex) { // assembly { // for { let i := 0 } lt(i,51) { i := add(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(max, item) { // max := item // maxIndex := i // } // } // } // } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary{ using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("_deity")] =_newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){ return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){ return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){ return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){ return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){ return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){ return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){ return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){ TellorStorage.Request storage _request = self.requestDetails[_requestId]; if(_request.requestTimestamps.length > 0){ return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true); } else{ return (0,false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){ return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){ return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Get the name of the token * @return string of the token name */ function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "Tellor Tributes"; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){ return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){ require(_index <= 50); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){ return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){ return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){ return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){ return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){ return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Get the symbol of the token * @return string of the token symbol */ function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "TT"; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){ return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){ return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){ uint newRequestId = getTopRequestID(self); return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){ uint _max; uint _index; (_max,_index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){ return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) { return self.uintVars[keccak256("total_supply")]; } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary{ using SafeMath for uint256; event TipAdded(address indexed _sender,uint indexed _requestId, uint _tip, uint _totalTips); event DataRequested(address indexed _sender, string _query,string _querySymbol,uint _granularity, uint indexed _requestId, uint _totalTips);//Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined event NewChallenge(bytes32 _currentChallenge,uint indexed _currentRequestId,uint _difficulty,uint _multiplier,string _query,uint _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewRequestOnDeck(uint indexed _requestId, string _query, bytes32 _onDeckQueryHash, uint _onDeckTotalTips); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewValue(uint indexed _requestId, uint _time, uint _value,uint _totalTips,bytes32 _currentChallenge);//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NonceSubmitted(address indexed _miner, string _nonce, uint indexed _requestId, uint _value,bytes32 _currentChallenge);//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /* function theLazyCoon(TellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public { self.uintVars[keccak256("total_supply")] += _amount; TellorTransfer.updateBalanceAtNow(self.balances[_address],_amount); }*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _tip) public { require(_requestId > 0); //If the tip > 0 transfer the tip to this contract if(_tip > 0){ TellorTransfer.doTransfer(self, msg.sender,address(this),_tip); } //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self,_requestId,_tip); emit TipAdded(msg.sender,_requestId,_tip,self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function requestData(TellorStorage.TellorStorageStruct storage self,string memory _c_sapi,string memory _c_symbol,uint _granularity, uint _tip) public { //Require at least one decimal place require(_granularity > 0); //But no more than 18 decimal places require(_granularity <= 1e18); //If it has been requested before then add the tip to it otherwise create the queryHash for it string memory _sapi = _c_sapi; string memory _symbol = _c_symbol; require(bytes(_sapi).length > 0); require(bytes(_symbol).length < 64); bytes32 _queryHash = keccak256(abi.encodePacked(_sapi,_granularity)); //If this is the first time the API and granularity combination has been requested then create the API and granularity hash //otherwise the tip will be added to the requestId submitted if(self.requestIdByQueryHash[_queryHash] == 0){ self.uintVars[keccak256("requestCount")]++; uint _requestId=self.uintVars[keccak256("requestCount")]; self.requestDetails[_requestId] = TellorStorage.Request({ queryString : _sapi, dataSymbol: _symbol, queryHash: _queryHash, requestTimestamps: new uint[](0) }); self.requestDetails[_requestId].apiUintVars[keccak256("granularity")] = _granularity; self.requestDetails[_requestId].apiUintVars[keccak256("requestQPosition")] = 0; self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")] = 0; self.requestIdByQueryHash[_queryHash] = _requestId; //If the tip > 0 it tranfers the tip to this contract if(_tip > 0){ TellorTransfer.doTransfer(self, msg.sender,address(this),_tip); } updateOnDeck(self,_requestId,_tip); emit DataRequested(msg.sender,self.requestDetails[_requestId].queryString,self.requestDetails[_requestId].dataSymbol,_granularity,_requestId,_tip); } //Add tip to existing request id since this is not the first time the api and granularity have been requested else{ addTip(self,self.requestIdByQueryHash[_queryHash],_tip); } } /** * @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self,string memory _nonce, uint _requestId) internal{ TellorStorage.Request storage _request = self.requestDetails[_requestId]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge //otherwise it sets it to 1 int _change = int(SafeMath.min(1200,(now - self.uintVars[keccak256("timeOfLastNewValue")]))); _change = int(self.uintVars[keccak256("difficulty")]) * (int(self.uintVars[keccak256("timeTarget")]) -_change)/1000; if (_change < 2 && _change > -2){ if (_change >= 0){ _change = 1; } else { _change = -1; } } if( (int(self.uintVars[keccak256("difficulty")]) + _change) <= 0){ self.uintVars[keccak256("difficulty")] = 1; } else{ self.uintVars[keccak256("difficulty")] = uint(int(self.uintVars[keccak256("difficulty")]) + _change); } //Sets time of value submission rounded to 1 minute uint _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; //The sorting algorithm that sorts the values of the first five values that come in TellorStorage.Details[5] memory a = self.currentMiners; uint i; for (i = 1;i <5;i++){ uint temp = a[i].value; address temp2 = a[i].miner; uint j = i; while(j > 0 && temp < a[j-1].value){ a[j].value = a[j-1].value; a[j].miner = a[j-1].miner; j--; } if(j<i){ a[j].value = temp; a[j].miner= temp2; } } //Pay the miners for (i = 0;i <5;i++){ TellorTransfer.doTransfer(self,address(this),a[i].miner,5e18 + self.uintVars[keccak256("currentTotalTips")]/5); } emit NewValue(_requestId,_timeOfLastNewValue,a[2].value,self.uintVars[keccak256("currentTotalTips")] - self.uintVars[keccak256("currentTotalTips")] % 5,self.currentChallenge); //update the total supply self.uintVars[keccak256("total_supply")] += 275e17; //pay the dev-share TellorTransfer.doTransfer(self, address(this),self.addressVars[keccak256("_owner")],25e17);//The ten there is the devshare //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2].value; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [a[0].miner,a[1].miner,a[2].miner,a[3].miner,a[4].miner]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value,a[1].value,a[2].value,a[3].value,a[4].value]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); //re-start the count for the slot progress to zero before the new request mining starts self.uintVars[keccak256("slotProgress")] = 0; uint _topId = TellorGettersLibrary.getTopRequestID(self); self.uintVars[keccak256("currentRequestId")] = _topId; //if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout //else wait for a new tip to mine if(_topId > 0){ //Update the current request to be mined to the requestID with the highest payout self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")]; //Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0; //Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next //and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0; //gets the max tip in the in the requestQ[51] array and its index within the array?? uint newRequestId = TellorGettersLibrary.getTopRequestID(self); //Issue the the next challenge self.currentChallenge = keccak256(abi.encodePacked(_nonce,self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge(self.currentChallenge,_topId,self.uintVars[keccak256("difficulty")],self.requestDetails[_topId].apiUintVars[keccak256("granularity")],self.requestDetails[_topId].queryString,self.uintVars[keccak256("currentTotalTips")]); emit NewRequestOnDeck(newRequestId,self.requestDetails[newRequestId].queryString,self.requestDetails[newRequestId].queryHash, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")]); } else{ self.uintVars[keccak256("currentTotalTips")] = 0; self.currentChallenge = ""; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self,string memory _nonce, uint _requestId, uint _value) public{ //requre miner is staked require(self.stakerDetails[msg.sender].currentStatus == 1); //Check the miner is submitting the pow for the current request Id require(_requestId == self.uintVars[keccak256("currentRequestId")]); //Saving the challenge information as unique by using the msg.sender require(uint(sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge,msg.sender,_nonce))))))) % self.uintVars[keccak256("difficulty")] == 0); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false); //Save the miner and value received self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value; self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender; //Add to the count how many values have been submitted, since only 5 are taken per request self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender,_nonce,_requestId,_value,self.currentChallenge); //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if(self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self,_nonce,_requestId); } } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self,address payable _pendingOwner) internal { require(msg.sender == self.addressVars[keccak256("_owner")]); emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner); self.addressVars[keccak256("pending_owner")] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) internal { require(msg.sender == self.addressVars[keccak256("pending_owner")]); emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]); self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _tip) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; uint onDeckRequestId = TellorGettersLibrary.getTopRequestID(self); //If the tip >0 update the tip for the requestId if (_tip > 0){ _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); } //Set _payout for the submitted request uint _payout = _request.apiUintVars[keccak256("totalTip")]; //If there is no current request being mined //then set the currentRequestId to the requestid of the requestData or addtip requestId submitted, // the totalTips to the payout/tip submitted, and issue a new mining challenge if(self.uintVars[keccak256("currentRequestId")] == 0){ _request.apiUintVars[keccak256("totalTip")] = 0; self.uintVars[keccak256("currentRequestId")] = _requestId; self.uintVars[keccak256("currentTotalTips")] = _payout; self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge(self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.uintVars[keccak256("currentTotalTips")]); } else{ //If there is no OnDeckRequestId //then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what //is being currently mined) if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")] || (onDeckRequestId == 0)) { //let everyone know the next on queue has been replaced emit NewRequestOnDeck(_requestId,_request.queryString,_request.queryHash ,_payout); } //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if(_request.apiUintVars[keccak256("requestQPosition")] == 0){ uint _min; uint _index; (_min,_index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if(_payout > _min || _min == 0){ self.requestQ[_index] = _payout; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } } //else if the requestid is part of the requestQ[51] then update the tip for it else if (_tip > 0){ self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; } } } } /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor{ using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /* function theLazyCoon(address _address, uint _amount) public { tellor.theLazyCoon(_address,_amount); } */ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint _requestId, uint _timestamp,uint _minerIndex) external { tellor.beginDispute(_requestId,_timestamp,_minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId,_supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint _requestId, uint _tip) external { tellor.addTip(_requestId,_tip); } /** * @dev Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function requestData(string calldata _c_sapi,string calldata _c_symbol,uint _granularity, uint _tip) external { tellor.requestData(_c_sapi,_c_symbol,_granularity,_tip); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(string calldata _nonce, uint _requestId, uint _value) external{ tellor.submitMiningSolution(_nonce,_requestId,_value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint _amount) external returns (bool) { return tellor.approve(_spender,_amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_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) external returns (bool) { return tellor.transferFrom(_from,_to,_amount); } }
Helps initialize a dispute by assigning it a disputeId when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the invalidated value information to POS voting _requestId being disputed _timestamp being disputed _minerIndex the index of the miner that submitted the value being disputed. Since each official value requires 5 miners to submit a value./
function beginDispute(uint _requestId, uint _timestamp,uint _minerIndex) external { tellor.beginDispute(_requestId,_timestamp,_minerIndex); } }
15,869,232
pragma solidity ^0.5.0; import "../UpgradeableToken.sol"; /** * A sample token that is used as a migration testing target. * * This is not an actual token, but just a stub used in testing. */ contract TestMigrationTarget is StandardToken, UpgradeAgent { UpgradeableToken public oldToken; uint public originalSupply; constructor(UpgradeableToken _oldToken) public { oldToken = _oldToken; // Let's not set bad old token require(address(oldToken) != address(0)); // Let's make sure we have something to migrate originalSupply = _oldToken.totalSupply(); require(originalSupply != 0); } function upgradeFrom(address _from, uint256 _value) public { require(msg.sender == address(oldToken)); // only upgrade from oldToken // Mint new tokens to the migrator totalSupply = totalSupply.add(_value); balances[_from] = balances[_from].add(_value); emit Transfer(address(0), _from, _value); } function() external { revert(); } }
Mint new tokens to the migrator
function upgradeFrom(address _from, uint256 _value) public { totalSupply = totalSupply.add(_value); balances[_from] = balances[_from].add(_value); emit Transfer(address(0), _from, _value); }
12,648,536
./partial_match/42/0xdFf18ab57909a57e4660435B0935C09A1407d29A/sources/MasterchefDelegator.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid) public virtual { if (block.number <= stageOneDepositEndBlock) { (uint256 amount, , , ) = stageOne.getUserInfo(_pid, msg.sender); stageOne.withdraw(_pid, msg.sender); emit Withdraw(msg.sender, _pid, amount); return; } UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "user is not existed"); require(user.endBlock < block.number, "token is still locked"); mintNTS(address(this), block.number); updatePoolDividend(_pid); uint256 originWeight = user.originWeight; PoolInfo storage pool = poolInfo[_pid]; uint256 totalDividend = pool.accumulativeDividend; uint256 usersTotalWeight = pool.usersTotalWeight; uint256 userWeight = user.inviteeWeight.add(originWeight); if(user.isCalculateInvitation){ userWeight = userWeight.add(originWeight.div(INVITOR_WEIGHT)); } if (totalDividend > 0) { uint256 pending = totalDividend.mul(userWeight).div(usersTotalWeight); pool.accumulativeDividend = totalDividend.sub(pending); uint256 devDividend = pending.mul(devDividendWeight).div( devDividendWeight.add(userDividendWeight) ); safeNTSTransfer(devAddress, devDividend); pending = pending.sub(devDividend); safeNTSTransfer(msg.sender, pending); } pool.usersTotalWeight = usersTotalWeight.sub(userWeight); uint256 amount = user.amount; userInfo[_pid][msg.sender].amount = 0; userInfo[_pid][msg.sender].originWeight = 0; userInfo[_pid][msg.sender].endBlock = 0; IERC20(pool.lpTokenSwap).safeTransfer(address(msg.sender), amount); uint256 lpTokenAmount = pool.lpTokenAmount.sub(amount); pool.lpTokenAmount = lpTokenAmount; uint256 oracleWeight = 0; if (lpTokenAmount == 0) oracleWeight = 0; else { oracleWeight = getOracleWeight(pool, lpTokenAmount); } pool.oracleWeight = oracleWeight; resetInvitationRelationship(_pid, msg.sender, originWeight); emit Withdraw(msg.sender, _pid, amount); }
3,296,309
./full_match/11155111/0xaFE9d35157E0B54cB8A56e970635959Ee88d882D/sources/contracts/Ticketing.sol
Function to mark ticket as used and can only be called by the contract deployer
function useTicket(uint256 _ticketId) external onlyOwner { require(tickets[_ticketId].confirmTicketUse, "Ticket use not confirmed by owner"); require(!tickets[_ticketId].used, "Ticket has already been used"); require(block.timestamp <= tickets[_ticketId].validUntil, "Ticket validity has expired"); tickets[_ticketId].used = true; usedTicketIds.push(_ticketId); emit TicketUsed(_ticketId, msg.sender); }
3,809,656
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // 'FLETA' 'Fleta Token' token contract // // Symbol : FLETA // Name : Fleta Token // Total supply: 2,000,000,000 (Same as 0x7788D759F21F53533051A9AE657fA05A1E068fc6) // Decimals : 18 // // Enjoy. // // (c) Sam Jeong / SendSquare Co. 2021. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Fletav2Gateway { function isGatewayAddress(address gatewayAddress) public view returns (bool); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract FletaV2Token is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; bool _stopTrade; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; //Changes v2 address public manager; address public v1Address; mapping(address => bool) mswap; mapping(address => bool) mgatewayAddress; // ------------------------------------------------------------------------ // Constructor // The parameters of the constructor were added in v2. // ------------------------------------------------------------------------ constructor(address v1Addr) public { symbol = "FLETA"; name = "Fleta Token"; decimals = 18; _stopTrade = false; //blow Changes v2 balances[owner] = 0; manager = msg.sender; _totalSupply = ERC20Interface(v1Addr).totalSupply(); v1Address = v1Addr; } // ------------------------------------------------------------------------ // Change gateway manager // ------------------------------------------------------------------------ function setGatewayManager(address addr) public onlyOwner { manager = addr; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Stop Trade // ------------------------------------------------------------------------ function stopTrade() public onlyOwner { require(_stopTrade != true); _stopTrade = true; } // ------------------------------------------------------------------------ // Start Trade // ------------------------------------------------------------------------ function startTrade() public onlyOwner { require(_stopTrade == true); _stopTrade = false; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // Changes in v2 // - 스왑되기 이전의 주소에서 가져오는 값은 v1과 v2의 balance를 합해서 전달한다. // - 스왑이후의 주소에서는 v2값만 가져온다. // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { if (mswap[tokenOwner] == true) { return balances[tokenOwner]; } return ERC20Interface(v1Address).balanceOf(tokenOwner).add(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 // Changes in v2 // - insection _swap function See {_swap} // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); require(to > address(0)); balances[msg.sender] = balances[msg.sender].sub(tokens); if (mgatewayAddress[to] == true) { //balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); //balances[to] = balances[to].sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(to, address(0), tokens); } else { balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); } return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); require(from > address(0)); require(to > address(0)); balances[from] = balances[from].sub(tokens); if(from != to && from != msg.sender) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); } if (mgatewayAddress[to] == true) { //balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); //balances[to] = balances[to].sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(to, address(0), tokens); } else { balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); } emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { require(_stopTrade != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { require(msg.sender != spender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Below functions added to v2 // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Swap the token in v1 to v2. // ------------------------------------------------------------------------ function swap(address swapAddr) public returns (bool success) { require(mswap[swapAddr] != true, "already swap"); _swap(swapAddr); return true; } function _swap(address swapAddr) private { if (mswap[swapAddr] != true) { mswap[swapAddr] = true; uint _value = ERC20Interface(v1Address).balanceOf(swapAddr); balances[swapAddr] = balances[swapAddr].add(_value); } } function isGatewayAddress(address gAddr) public view returns (bool isGateway) { return mgatewayAddress[gAddr]; } // ------------------------------------------------------------------------ // Burns a specific amount of tokens // ------------------------------------------------------------------------ function _burn(address burner, uint256 _value) private { _swap(burner); balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Transfer(burner, address(0), _value); } // ------------------------------------------------------------------------ // Minting a specific amount of tokens // ------------------------------------------------------------------------ function mint(address minter, uint256 _value) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); _swap(minter); balances[minter] = balances[minter].add(_value); _totalSupply = _totalSupply.add(_value); emit Transfer(address(0), minter, _value); } // ------------------------------------------------------------------------ // The gateway address is the eth address connected to the FLETA mainnet. // The transferred amount to this address is burned and minted to the FLETA mainnet address associated with this address. // ------------------------------------------------------------------------ function depositGatewayAdd(address gatewayAddr) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); mgatewayAddress[gatewayAddr] = true; if (balanceOf(gatewayAddr) > 0) { _burn(gatewayAddr, balanceOf(gatewayAddr)); } } // ------------------------------------------------------------------------ // Remove gateway address map, revert normal address // ------------------------------------------------------------------------ function depositGatewayRemove(address gatewayAddr) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); mgatewayAddress[gatewayAddr] = false; } }
------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { require(msg.sender != spender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
373,992
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./MockMessageVerifier.sol"; import "./MockInboundLane.sol"; import "../interfaces/IOnMessageDelivered.sol"; contract MockOutboundLane is MockMessageVerifier { struct ConfirmInfo { address sender; bool result; } address remoteInboundLane; uint64 public nonce = 0; mapping(uint64 => ConfirmInfo) responses; constructor( uint32 _thisChainPosition, uint32 _thisLanePosition, uint32 _bridgedChainPosition, uint32 _bridgedLanePosition, address _remoteInboundLane ) MockMessageVerifier( _thisChainPosition, _thisLanePosition, _bridgedChainPosition, _bridgedLanePosition ) { remoteInboundLane = _remoteInboundLane; } function send_message(address targetContract, bytes calldata encoded) external payable returns (uint256) { // call target contract bool result = MockInboundLane(remoteInboundLane).mock_dispatch(msg.sender, targetContract, encoded); nonce += 1; responses[nonce] = ConfirmInfo(msg.sender, result); return encodeMessageKey(nonce); } function mock_confirm(uint64 _nonce) external { ConfirmInfo memory info = responses[_nonce]; uint256 messageId = encodeMessageKey(_nonce); IOnMessageDelivered(info.sender).on_messages_delivered(messageId, info.result); delete responses[_nonce]; } }
call target contract
function send_message(address targetContract, bytes calldata encoded) external payable returns (uint256) { bool result = MockInboundLane(remoteInboundLane).mock_dispatch(msg.sender, targetContract, encoded); nonce += 1; responses[nonce] = ConfirmInfo(msg.sender, result); return encodeMessageKey(nonce); }
12,582,553
./partial_match/1/0x76EA2186182E3Ec27C2D9C7394b83E5C8F2cf6C4/sources/NFTRewardsVault.sol
Update the given pool's allocation point.
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; }
3,677,090
./full_match/5/0xB3fF7D09c4871cfCfea4e1520e6565092B213AaB/sources/contracts/utilities/Sweepable.sol
sweep native token to the owner
function sweepNative() external onlyOwner { uint256 amount = address(this).balance; require(success, "Transfer failed."); emit SweepNative(amount); }
1,862,406
./full_match/4/0x77a6680ACc029609F658cf2064b4356143DC860C/sources/browser/IERC721Metadata.sol
ERC-721 Non-Fungible Token Standard, optional metadata extension/
interface IERC721Metadata { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
670,072
./full_match/44787/0x774263E01b21FE6eE0133e749Ec8811135400a1B/sources/project_/contracts/UnergyData.sol
holder initialization;
function setHolders( address projectAddr, address holder_ ) public whenNotPaused hasRoleInPermissionGranter( msg.sender, "setHolders" ) { DataStructure.Holders[] storage holders; DataStructure.Holders memory holder = DataStructure.Holders({ addr: 0x1234567890123456789012345678901234567890, fiat: false }); holders = projectHolders[projectAddr]; holder.addr = holder_; holder.fiat = true; holders.push(holder); holdersIndex[holder_][projectAddr] = holders.length; }
13,277,184
./partial_match/56/0x97a32B4f8486735075f2cBEcff64208fBF2e610A/sources/contracts/libraries/Transfer.sol
Transfers tokens from msg.sender to a recipient Errors with ST if transfer fails token The contract address of the token which will be transferred to The recipient of the transfer value The value of the transfer
function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "ST"); }
11,291,606
// SPDX-License-Identifier: MIT pragma solidity =0.8.6; import "./GMsDerivativeBase.sol"; contract GenerativemasksGirl is GMsDerivativeBase { constructor( string memory baseURI, address _derivedFrom ) GMsDerivativeBase( "Generativemasks Girl", "GMGIRL", baseURI, address(0x80416304142Fa37929f8A4Eee83eE7D2dAc12D7c), _derivedFrom ) {} } // SPDX-License-Identifier: MIT pragma solidity =0.8.6; import "@openzeppelin/contracts/utils/Strings.sol"; import "../core/GMsPassCore.sol"; /** * @title GMsDerivativeBase contract * @author wildmouse * @notice This contract provides basic functionalities to allow minting using the GMsPassCore * @dev This is hardcoded to the minting condition to deploy derivative NFTs only for Generativemasks holders without claim fees. * This SHOULD be derived by another contract and used for mainnet deployments */ contract GMsDerivativeBase is GMsPassCore { using Strings for uint256; address public derivedFrom; string private __baseURI; /** * @notice Construct an GMsDerivativeBase instance * @param name Name of the token * @param symbol Symbol of the token * @param baseURI URL of metadata JSON. Token id will be added for each token id on tokenURL() * @param generativemasks Generativemasks address. This argument should hardcoded by derived contract. * @param _derivedFrom NFT contract address of the derivation source */ constructor( string memory name, string memory symbol, string memory baseURI, address generativemasks, address _derivedFrom ) GMsPassCore( name, symbol, IERC721(generativemasks), true, 10000, 10000, 0, 0 ) { __baseURI = baseURI; derivedFrom = _derivedFrom; } function _baseURI() internal override view virtual returns (string memory) { return __baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); uint256 maskNumber = (tokenId + METADATA_INDEX) % GMS_SUPPLY_AMOUNT; return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, maskNumber.toString())) : ""; } function updateBaseURI(string calldata newBaseURI) external onlyOwner { __baseURI = newBaseURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GMsPassCore contract * @author wildmouse * @notice This contract provides basic functionalities to allow minting using the GMsPass * @dev This contract should be used only for testing or testnet deployments */ abstract contract GMsPassCore is ERC721, ReentrancyGuard, Ownable { uint256 public constant MAX_MULTI_MINT_AMOUNT = 32; uint256 public constant GMS_SUPPLY_AMOUNT = 10000; uint256 public constant MAX_GMs_TOKEN_ID = 9999; uint256 public constant METADATA_INDEX = 3799; IERC721 public immutable generativemasks; bool public immutable onlyGMsHolders; uint16 public immutable reservedAllowance; uint16 public reserveMinted; uint256 public immutable maxTotalSupply; uint256 public immutable priceForGMsHoldersInWei; uint256 public immutable priceForOpenMintInWei; uint256 public mintedCount; /** * @notice Construct an GMsPassCore instance * @param name Name of the token * @param symbol Symbol of the token * @param generativemasks_ Address of your GMs instance (only for testing) * @param onlyGMsHolders_ True if only GMs tokens holders can mint this token * @param maxTotalSupply_ Maximum number of tokens that can ever be minted * @param reservedAllowance_ Number of tokens reserved for GMs token holders * @param priceForGMsHoldersInWei_ Price GMs token holders need to pay to mint * @param priceForOpenMintInWei_ Price open minter need to pay to mint */ constructor( string memory name, string memory symbol, IERC721 generativemasks_, bool onlyGMsHolders_, uint256 maxTotalSupply_, uint16 reservedAllowance_, uint256 priceForGMsHoldersInWei_, uint256 priceForOpenMintInWei_ ) ERC721(name, symbol) { require(maxTotalSupply_ > 0, "GMsPass:INVALID_SUPPLY"); require(!onlyGMsHolders_ || (onlyGMsHolders_ && maxTotalSupply_ <= GMS_SUPPLY_AMOUNT), "GMsPass:INVALID_SUPPLY"); require(maxTotalSupply_ >= reservedAllowance_, "GMsPass:INVALID_ALLOWANCE"); // If restricted to generativemasks token holders we limit max total supply generativemasks = generativemasks_; onlyGMsHolders = onlyGMsHolders_; maxTotalSupply = maxTotalSupply_; reservedAllowance = reservedAllowance_; priceForGMsHoldersInWei = priceForGMsHoldersInWei_; priceForOpenMintInWei = priceForOpenMintInWei_; } function getTokenIdFromMaskNumber(uint256 maskNumber) public pure returns (uint256) { require(maskNumber <= MAX_GMs_TOKEN_ID, "GMsPass:INVALID_NUMBER"); return ((maskNumber + GMS_SUPPLY_AMOUNT) - METADATA_INDEX) % GMS_SUPPLY_AMOUNT; } function getTokenIdListFromMaskNumbers(uint256[] calldata maskNumbers) public pure returns (uint256[] memory) { uint256[] memory tokenIdList = new uint256[](maskNumbers.length); for (uint256 i = 0; i < maskNumbers.length; i++) { require(maskNumbers[i] <= MAX_GMs_TOKEN_ID, "GMsPass:INVALID_NUMBER"); tokenIdList[i] = getTokenIdFromMaskNumber(maskNumbers[i]); } return tokenIdList; } /** * @notice Allow a GMs token holder to bulk mint tokens with id of their GMs tokens' id * @param maskNumbers numbers to be converted to token ids to be minted */ function multiMintWithGMsMaskNumbers(uint256[] calldata maskNumbers) public payable virtual { multiMintWithGMsTokenIds(getTokenIdListFromMaskNumbers(maskNumbers)); } /** * @notice Allow a GMs token holder to mint a token with one of their GMs token's id * @param maskNumber number to be converted to token id to be minted */ function mintWithGMsMaskNumber(uint256 maskNumber) public payable virtual { mintWithGMsTokenId(getTokenIdFromMaskNumber(maskNumber)); } /** * @notice Allow a GMs token holder to bulk mint tokens with id of their GMs tokens' id * @param tokenIds Ids to be minted */ function multiMintWithGMsTokenIds(uint256[] memory tokenIds) public payable virtual nonReentrant { uint256 maxTokensToMint = tokenIds.length; require(maxTokensToMint <= MAX_MULTI_MINT_AMOUNT, "GMsPass:TOO_LARGE"); require( // If no reserved allowance we respect total supply contraint (reservedAllowance == 0 && mintedCount + maxTokensToMint <= maxTotalSupply) || reserveMinted + maxTokensToMint <= reservedAllowance, "GMsPass:MAX_ALLOCATION_REACHED" ); require(msg.value == priceForGMsHoldersInWei * maxTokensToMint, "GMsPass:INVALID_PRICE"); // To avoid wasting gas we want to check all preconditions beforehand for (uint256 i = 0; i < maxTokensToMint; i++) { require(tokenIds[i] <= MAX_GMs_TOKEN_ID, "GMsPass:INVALID_ID"); require(generativemasks.ownerOf(tokenIds[i]) == msg.sender, "GMsPass:INVALID_OWNER"); } // If reserved allowance is active we track mints count if (reservedAllowance > 0) { reserveMinted += uint16(maxTokensToMint); } mintedCount += maxTokensToMint; for (uint256 i = 0; i < maxTokensToMint; i++) { _safeMint(msg.sender, tokenIds[i]); } } /** * @notice Allow a GMs token holder to mint a token with one of their GMs token's id * @param tokenId Id to be minted */ function mintWithGMsTokenId(uint256 tokenId) public payable virtual nonReentrant { require( // If no reserved allowance we respect total supply contraint (reservedAllowance == 0 && mintedCount < maxTotalSupply) || reserveMinted < reservedAllowance, "GMsPass:MAX_ALLOCATION_REACHED" ); require(tokenId <= MAX_GMs_TOKEN_ID, "GMsPass:INVALID_ID"); require(generativemasks.ownerOf(tokenId) == msg.sender, "GMsPass:INVALID_OWNER"); require(msg.value == priceForGMsHoldersInWei, "GMsPass:INVALID_PRICE"); // If reserved allowance is active we track mints count if (reservedAllowance > 0) { reserveMinted++; } mintedCount++; _safeMint(msg.sender, tokenId); } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * GMs token holders can use this function without using the GMs token holders allowance, * this is useful when the allowance is fully utilized. * @param tokenId Id to be minted */ function mint(uint256 tokenId) public payable virtual nonReentrant { require(!onlyGMsHolders, "GMsPass:OPEN_MINTING_DISABLED"); require(openMintsAvailable() > 0, "GMsPass:MAX_ALLOCATION_REACHED"); require( (tokenId > MAX_GMs_TOKEN_ID && tokenId <= maxTokenId()) || generativemasks.ownerOf(tokenId) == msg.sender, "GMsPass:INVALID_ID" ); require(msg.value == priceForOpenMintInWei, "GMsPass:INVALID_PRICE"); mintedCount++; _safeMint(msg.sender, tokenId); } /** * @notice Calculate the maximum token id that can ever be minted * @return Maximum token id */ function maxTokenId() public view returns (uint256) { uint256 maxOpenMints = maxTotalSupply - reservedAllowance; return MAX_GMs_TOKEN_ID + maxOpenMints; } /** * @notice Calculate the currently available number of reserved tokens for GMs token holders * @return Reserved mint available */ function gmsHoldersMintsAvailable() external view returns (uint256) { return reservedAllowance - reserveMinted; } /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view returns (uint256) { uint256 maxOpenMints = maxTotalSupply - reservedAllowance; uint256 currentOpenMints = mintedCount - reserveMinted; return maxOpenMints - currentOpenMints; } /** * @notice Allows owner to withdraw amount */ function withdrawAll() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Allow a GMs token holder to bulk mint tokens with id of their GMs tokens' id tokenIds Ids to be minted/ If no reserved allowance we respect total supply contraint To avoid wasting gas we want to check all preconditions beforehand If reserved allowance is active we track mints count
function multiMintWithGMsTokenIds(uint256[] memory tokenIds) public payable virtual nonReentrant { uint256 maxTokensToMint = tokenIds.length; require(maxTokensToMint <= MAX_MULTI_MINT_AMOUNT, "GMsPass:TOO_LARGE"); require( (reservedAllowance == 0 && mintedCount + maxTokensToMint <= maxTotalSupply) || reserveMinted + maxTokensToMint <= reservedAllowance, "GMsPass:MAX_ALLOCATION_REACHED" ); require(msg.value == priceForGMsHoldersInWei * maxTokensToMint, "GMsPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(tokenIds[i] <= MAX_GMs_TOKEN_ID, "GMsPass:INVALID_ID"); require(generativemasks.ownerOf(tokenIds[i]) == msg.sender, "GMsPass:INVALID_OWNER"); } if (reservedAllowance > 0) { reserveMinted += uint16(maxTokensToMint); } mintedCount += maxTokensToMint; for (uint256 i = 0; i < maxTokensToMint; i++) { _safeMint(msg.sender, tokenIds[i]); } }
12,077,803
./partial_match/1/0x3368E0DE8aB2B087771ee9Aa1e44777e45Ca9dCD/sources/contracts/ERC20/libraries/ERC20Pausable.sol
Pause the contract Access restriction must be overriden in derived class/
function pause() external virtual { _pause(); }
16,079,206
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.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 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); } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @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; } } /* * Interface for the $COLORWASTE erc20 token contract */ interface ICW { function burn(address _from, uint256 _amount) external; function updateBalance(address _from, address _to) external; } /* * Interface for the $SOS erc20 token contract */ interface ISOS { function approve(address from, uint256 amount) external returns(bool); function transferFrom(address from, address to, uint256 amount) external; function balanceOf(address owner) external view returns(uint256); } /* * Interface for the Doodles contract */ interface IDoodles { function balanceOf(address owner) external view returns(uint256); function ownerOf(uint256 tokenId) external view returns(address); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns(uint256); } /* * Interface for the KaijuKingz contract */ interface IKaijuKingz { function walletOfOwner(address owner) external view returns(uint256[] memory); function ownerOf(uint256 tokenId) external view returns(address); } /* * DAIJUKINGZ */ contract DaijuKingz is ERC721, Ownable { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; Counters.Counter private TotalSupplyFix; ICW public CW; IDoodles public Doodles; IKaijuKingz public KaijuKingz; ISOS public SOS; string private baseURI; uint256 constant public reserveMax = 50; // the amount of daijus the team will reserve for community events, staff, etc. uint256 public maxSupply = 11110; // max genesis + max bred daijus uint256 public maxGenCount = 5555; // the max genesis count. if theres remaining supply after sale ends, the genesis daijukingz will be less then this number uint256 public maxFreeMints = 124; // the max free mints that can be claimed for kaiju and doodle holders uint256 public maxGivewayMint = 676; // the max free mints that are from the whitelisted users // counters uint256 public reserveCount = 0; uint256 public freeMintCount = 0; uint256 public giveawayMintCount = 0; uint256 public genCount = 0; uint256 public babyCount = 0; // settings for breeding & sales uint256 public price = 0.05 ether; uint256 public breedPrice = 7500 ether; uint256 public increasePerBreed = 0 ether; uint256 public saleStartTimestamp; uint256 public freeEndTimestamp; address public sosWallet; uint256 public sosPrice = 0.05 ether; bool public transfersEnabled = false; bool public breedingEnabled = false; // tracks all of the wallets that interact with the contract mapping(address => uint256) public balanceGenesis; mapping(address => uint256) public balanceBaby; mapping(address => uint256) public freeMintList; mapping(address => uint256) public giveawayMintList; /* * DaijuOwner * checks if the token IDs provided are owned by the user interacting with the contract (used for breeding) */ modifier DaijuOwner(uint256 DaijuId) { require(ownerOf(DaijuId) == msg.sender, "Cannot interact with a DaijuKingz you do not own"); _; } /* * IsSaleActive * checks if the mint is ready to begin */ modifier IsSaleActive() { require(saleStartTimestamp != 0 && block.timestamp > saleStartTimestamp, "Cannot interact because sale has not started"); _; } /* * IsFreeMintActive * checks if the free mint end timestamp isn't met */ modifier IsFreeMintActive { require(block.timestamp < freeEndTimestamp, "Free Minting period has ended!"); _; } /* * AreTransfersEnabled * checks if we want to allow opensea to transfer any tokens */ modifier AreTransfersEnabled() { require(transfersEnabled, "Transfers aren't allowed yet!"); _; } constructor() ERC721("DaijuKingz", "Daiju") {} /* * mintFreeKaijuList * checks the walelt for a list of kaijukingz they hold, used for checking if they * can claim a free daijuking */ function mintFreeKaijuList(address _address) external view returns(uint256[] memory) { return KaijuKingz.walletOfOwner(_address); } /* * mintFreeDoodleList * gets the amount of doodles a wallet holds, used for checking if they are elligble * for claiming a free daijuking */ function mintFreeDoodleList(address _address) public view returns(uint256) { uint256 count = Doodles.balanceOf(_address); return count; } /* * checkIfFreeMintClaimed * checks if the address passed claimed a free mint already */ function checkIfFreeMintClaimed(address _address) public view returns(uint256) { return freeMintList[_address]; } /* * checkIfGiveawayMintClaimed * checks if they claimed their giveaway mint */ function checkIfGiveawayMintClaimed(address _address) public view returns(uint256) { return giveawayMintList[_address]; } /* * addGiveawayWinners * adds the wallets to the giveaway list so they can call mintFreeGiveaway() */ function addGiveawayWinners(address[] calldata giveawayAddresses) external onlyOwner { for (uint256 i; i < giveawayAddresses.length; i++) { giveawayMintList[giveawayAddresses[i]] = 1; } } /* * mintFreeDoodle * mints a free daijuking using a Doodles token - can only be claimed once per wallet */ function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!"); require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!"); require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); freeMintList[msg.sender] = 1; balanceGenesis[msg.sender]++; genCount++; freeMintCount += 1; } /* * mintFreeKaiju * mints a free daijuking using a KaijuKingz token - can only be claimed once per wallet */ function mintFreeKaiju() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); uint256[] memory list = KaijuKingz.walletOfOwner(msg.sender); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!"); require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!"); require(list.length >= 1, "You don't own any KaijuKingz!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); freeMintList[msg.sender] = 1; balanceGenesis[msg.sender]++; genCount++; freeMintCount += 1; } /* * mintFreeGiveaway * this is for the giveaway winners - allows you to mint a free daijuking */ function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!"); require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); giveawayMintList[msg.sender] = 0; balanceGenesis[msg.sender]++; genCount++; giveawayMintCount += 1; } /* * mint * mints the daijuking using ETH as the payment token */ function mint(uint256 numberOfMints) public payable IsSaleActive { uint256 supply = TotalSupplyFix.current(); require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount"); if (block.timestamp <= freeEndTimestamp) { require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply"); } else { require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply"); } require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct"); require(!breedingEnabled, "Minting genesis has been disabled!"); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); } } /* * mintWithSOS * allows the user to mint a daijuking using the $SOS token * note: user must approve it before this can be called */ function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive { uint256 supply = TotalSupplyFix.current(); require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount"); require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply"); require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!"); require(!breedingEnabled, "Minting genesis has been disabled!"); SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints)); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); } } /* * breed * allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only * note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children... */ function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) { uint256 supply = TotalSupplyFix.current(); require(breedingEnabled, "Breeding isn't enabled yet!"); require(supply < maxSupply, "Cannot breed any more baby Daijus"); require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)"); require(parent1 != parent2, "Must select two unique parents"); // burns the tokens for the breeding cost CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount); // adds the baby to the total supply and counter babyCount++; TotalSupplyFix.increment(); // mints the baby daijuking and adds it to the balance for the wallet _safeMint(msg.sender, supply); balanceBaby[msg.sender]++; } /* * reserve * mints the reserved amount */ function reserve(uint256 count) public onlyOwner { uint256 supply = TotalSupplyFix.current(); require(reserveCount + count < reserveMax, "cannot reserve more"); for (uint256 i = 0; i < count; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); reserveCount++; } } /* * totalSupply * returns the current amount of tokens, called by DAPPs */ function totalSupply() external view returns(uint256) { return TotalSupplyFix.current(); } /* * getTypes * gets the tokens provided and returns the genesis and baby daijukingz * * genesis is 0 * baby is 1 */ function getTypes(uint256[] memory list) external view returns(uint256[] memory) { uint256[] memory typeList = new uint256[](list.length); for (uint256 i; i < list.length; i++){ if (list[i] >= genCount) { typeList[i] = 1; } else { typeList[i] = 0; } } return typeList; } /* * walletOfOwner * returns the tokens that the user owns */ function walletOfOwner(address owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256 supply = TotalSupplyFix.current(); uint256 index = 0; uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < supply; i++) { if (ownerOf(i) == owner) { tokensId[index] = i; index++; } } return tokensId; } /* * withdraw * takes out the eth from the contract to the deployer */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /* * updateSaleTimestamp * set once we're ready release */ function updateSaleTimestamp(uint256 _saleStartTimestamp) public onlyOwner { saleStartTimestamp = _saleStartTimestamp; } /* * updateFreeEndTimestamp * set once saleStartTimestamp is set for release */ function updateFreeEndTimestamp(uint256 _freeEndTimestamp) public onlyOwner { freeEndTimestamp = _freeEndTimestamp; } /* * setBreedingCost * sets the breeding cost to the new */ function setBreedingCost(uint256 _breedPrice) public onlyOwner { breedPrice = _breedPrice; } /* * setBreedingCostIncrease * change the rate based on the breeding cost for each new baby mint */ function setBreedingCostIncrease(uint256 _increasePerBreed) public onlyOwner { increasePerBreed = _increasePerBreed; } /* * setBreedingState * changes whether breeding is enabled or not, by default its disabled */ function setBreedingState(bool _state) public onlyOwner { breedingEnabled = _state; } /* * setPrice * sets the eth mint price (shouldn't ever be called but who knows) */ function setPrice(uint256 _price) public onlyOwner { price = _price; } /* * setSOSPrice * sets the price for $SOS mint, most likely will only be set once before the release */ function setSOSPrice(uint256 _sosPrice) public onlyOwner { sosPrice = _sosPrice; } // 46524939000000000000000000 // 4652493900000000000000000 /* * setSOSWallet * sets the deposit wallet for $SOS mints */ function setSOSWallet(address _address) public onlyOwner { sosWallet = _address; } /* * setBaseURI * sets the metadata url once its live */ function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } /* * _baseURI * returns the metadata url to any DAPPs that use it (opensea for instance) */ function _baseURI() internal view override returns (string memory) { return baseURI; } /* * setTransfersEnabled * enables opensea transfers - can only be called once */ function setTransfersEnabled() external onlyOwner { transfersEnabled = true; } /* * setCWInterface * links the interface to the $COLORWASTE smart contract once it's deployed */ function setCWInterface(address _address) external onlyOwner { CW = ICW(_address); } /* * setKaijuInterface * links the interface to the KaijuKingz contract */ function setKaijuInterface(address _address) public onlyOwner { KaijuKingz = IKaijuKingz(_address); } /* * setDoodleInterface * links the interface to the Doodles contract */ function setDoodleInterface(address _address) public onlyOwner { Doodles = IDoodles(_address); } /* * setSOSInterface * links the interface to the $SOS contract */ function setSOSInterface(address target) public onlyOwner { SOS = ISOS(target); } /* * Opensea methods for transfering the tokens */ function transferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled { CW.updateBalance(from, to); if (tokenId >= maxGenCount) { balanceBaby[from]--; balanceBaby[to]++; } else { balanceGenesis[from]--; balanceGenesis[to]++; } ERC721.transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override AreTransfersEnabled { CW.updateBalance(from, to); if (tokenId >= maxGenCount) { balanceBaby[from]--; balanceBaby[to]++; } else { balanceGenesis[from]--; balanceGenesis[to]++; } ERC721.safeTransferFrom(from, to, tokenId, data); } }
Interface for the Doodles contract/
interface IDoodles { function balanceOf(address owner) external view returns(uint256); function ownerOf(uint256 tokenId) external view returns(address); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns(uint256); }
6,906,494
./full_match/4/0xD6ee9785A54BFeb2bC9923DFA1E531c92c651F1c/sources/contracts/AuctionRaffle.sol
Selects one Golden Ticket winner from a random number. Saves the winner at the beginning of _raffleWinners array and sets bidder WinType to GOLDEN_TICKET. participantsLength The length of current participants array randomNumber The random number to select raffle winner from return participantsLength New participants array length return randomNumber Shifted random number by `_randomMaskLength` bits to the right/
function selectGoldenTicketWinner(uint256 participantsLength, uint256 randomNumber) private returns (uint256, uint256) { uint256 winnerIndex = winnerIndexFromRandomNumber(participantsLength, randomNumber); uint256 bidderID = _raffleParticipants[winnerIndex]; addGoldenTicketWinner(bidderID); removeRaffleParticipant(winnerIndex); return (participantsLength - 1, randomNumber >> _randomMaskLength); }
12,381,090
// 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 PHAKEPHAYC is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.03 ether; uint256 public maxSupply = 10000; uint256 public freeMints = 500; uint256 public maxMintAmount = 20; bool public paused = false; //address[] memory freeMintAddresses = new address[](200); //mapping (address => bool) public freeMintWallets; address public guy1 = 0xF2c11E29Aaa9628EFC7B44f5512B5C625B39E6E4; address public guy2 = 0x4431075435937de7C40dCE8Cb5CA3C9879Cc6F12; address public guy3 = 0x73596897D15151C6fECAc0c0318e7755c328DCCE; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); // Only charge if all free mints have been minted if (supply >= freeMints){ require(msg.value >= cost * _mintAmount); } if (supply < freeMints){ // Free mint! require(_mintAmount == 1); /*require(freeMintWallets[msg.sender] == false, "You already used your free mint" ); freeMintWallets[msg.sender]=true; */ } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } 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)) : ""; } //only owner 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 setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } // Owner can withdraw ETH from here function withdrawETH() external onlyOwner { uint256 balance = address(this).balance; uint256 _splitTo3 = (balance * 0.33333 ether) / 1 ether; payable(guy1).transfer(_splitTo3); payable(guy2).transfer(_splitTo3); payable(guy3).transfer(_splitTo3); } }
public Only charge if all free mints have been minted Free mint!
function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (supply >= freeMints){ require(msg.value >= cost * _mintAmount); } if (supply < freeMints){ require(_mintAmount == 1); "You already used your free mint" ); freeMintWallets[msg.sender]=true; */ for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } }
1,343,396
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT import "ERC721URIStorage.sol"; import "ERC721Enumerable.sol"; import "IERC2981.sol"; import "Ownable.sol"; import "Address.sol"; /** * @title Sample NFT contract * @dev Extends ERC-721 NFT contract and implements ERC-2981 */ contract Token is Ownable, ERC721Enumerable, ERC721URIStorage { using Address for address payable; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; string baseUri; // Keep a mapping of token ids and corresponding hashes mapping(string => uint8) hashes; // Maximum amounts of mintable tokens uint256 private MAX_SUPPLY = 10000; // Address of the royalties recipient address private _royaltiesReceiver; // Percentage of each sale to pay as royalties uint256 private royaltiesPercentage; // Mint price wei uint256 private mintPrice; bool private saleIsActive; mapping(address => uint256) private _deposits; // Events event Mint(uint256 tokenId, address recipient); event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); constructor(address initialRoyaltiesReceiver) ERC721("BongaNFT", "BCNC") { baseUri = "https://bonganft.io/metadata/"; _royaltiesReceiver = initialRoyaltiesReceiver; mintPrice = 150000000000000000; MAX_SUPPLY = 10000; royaltiesPercentage = 250; saleIsActive = false; } /// @notice Checks if NFT contract implements the ERC-2981 interface /// @param _contract - the address of the NFT contract to query /// @return true if ERC-2981 interface is supported, false otherwise function _checkRoyalties(address _contract) internal returns (bool) { (bool success) = IERC2981(_contract). supportsInterface(_INTERFACE_ID_ERC2981); return success; } function startSale() public onlyOwner { saleIsActive = true; } function toggleSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setMintPrice(uint256 newMintPrice) external onlyOwner { require(mintPrice != newMintPrice, "same price"); // dev: Same price mintPrice = newMintPrice; } function getMintPrice() public view returns (uint256) { return mintPrice; } function setMaxSupply(uint256 newMaxSupply) external onlyOwner { require(MAX_SUPPLY != newMaxSupply, "same supply"); // dev: Same MAX_SUPPLY MAX_SUPPLY = newMaxSupply; } function setRoyaltiesPercentage(uint256 newRoyaltiesPercentage) external onlyOwner { require(royaltiesPercentage != newRoyaltiesPercentage, "same percent"); // dev: Same MAX_SUPPLY require(newRoyaltiesPercentage < 10000, "Royalty total value should be < 10000"); royaltiesPercentage = newRoyaltiesPercentage; } /** Overrides ERC-721's _baseURI function */ function _baseURI() internal view override returns (string memory) { return baseUri; } function setBaseURI(string memory _newUri) external onlyOwner { baseUri = _newUri; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, amount); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); super._burn(tokenId); } /// @notice Getter function for _royaltiesReceiver /// @return the address of the royalties recipient function royaltiesReceiver() external view returns(address) { return _royaltiesReceiver; } /// @notice Changes the royalties' recipient address (in case rights are /// transferred for instance) /// @param newRoyaltiesReceiver - address of the new royalties recipient function setRoyaltiesReceiver(address newRoyaltiesReceiver) external onlyOwner { require(newRoyaltiesReceiver != _royaltiesReceiver); // dev: Same address _royaltiesReceiver = newRoyaltiesReceiver; } /// @notice Returns a token's URI /// @dev See {IERC721Metadata-tokenURI}. /// @param tokenId - the id of the token whose URI to return /// @return a string containing an URI pointing to the token's ressource function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function setTokenURI(uint256 tokenId, string memory _tokenURI) public { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _setTokenURI(tokenId, _tokenURI); } /// @notice Informs callers that this contract supports ERC2981 function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(IERC2981).interfaceId || interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); } /// @notice Returns all the tokens owned by an address /// @param _owner - the address to query /// @return ownerTokens - an array containing the ids of all tokens /// owned by the address function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens ) { uint256 tokenCount = balanceOf(_owner); uint256[] memory result = new uint256[](tokenCount); if (tokenCount == 0) { return new uint256[](0); } else { for (uint256 i=0; i<tokenCount; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } } /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - 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 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 _royalties = (_salePrice * royaltiesPercentage) / 10000; return (_royaltiesReceiver, _royalties); } /// @notice Mints tokens Owner /// @param recipient - the address to which the token will be transfered /// @return tokenId - the id of the token function mintOwner(address recipient) external onlyOwner returns (uint256 tokenId) { require(totalSupply() <= MAX_SUPPLY, "All tokens minted"); uint256 newItemId = totalSupply() + 1; string memory hash = string(abi.encodePacked(uint2uristr(newItemId*15+99), ".json")); _safeMint(recipient, newItemId); _setTokenURI(newItemId, hash); emit Mint(newItemId, recipient); return newItemId; } /// @notice Mints tokens All /// @param recipient - the address to which the token will be transfered /// @return tokenId - the id of the token function mint(address recipient, uint256 qty) external payable returns (uint256 tokenId) { require(saleIsActive == true, "Minting disabled"); require(totalSupply() <= MAX_SUPPLY, "All tokens minted"); require(msg.value >= mintPrice*qty, "Not enough ETH sent; check price!"); uint256 newItemId = totalSupply(); string memory hash = ""; for (uint256 i=0; i<qty; i++) { newItemId = newItemId + 1; hash = string(abi.encodePacked(uint2uristr(newItemId*15+99), ".json")); _safeMint(recipient, newItemId); _setTokenURI(newItemId, hash); emit Mint(newItemId, recipient); } return newItemId; } function uint2uristr(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } //deposits function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee, uint256 payment) public virtual onlyOwner { payee.sendValue(payment); emit Withdrawn(payee, payment); } function withdrawAll(address payable payee) public virtual onlyOwner { uint256 balance = address(this).balance; payee.sendValue(balance); emit Withdrawn(payee, balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC721.sol"; import "IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity ^0.8.0; import "ERC165.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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. */ 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 () { 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; } }
Called with the sale price to determine how much royalty is owed and to whom. _tokenId - the NFT asset queried for royalty information _salePrice - 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 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 _royalties = (_salePrice * royaltiesPercentage) / 10000; return (_royaltiesReceiver, _royalties); }
13,802,641
./partial_match/42/0x936E65F7b1a2E06515729d71df28Dc926263906D/sources/PopsicleStand.sol
Changes Project token reward per block. Use this function to moderate the `lockup amount`. Essentially this function changes the amount of the reward which is entitled to the user for his LP staking by the time the `endBlock` is passed. However, the reward amount cannot be less than the amount of the previous token reward per block Good to use just before the `endBlock` approaches.
function changeProjectTokenPerBlock(uint _projectTokenPerBlock) external onlyOwner { require(_projectTokenPerBlock > projectTokenPerBlock, "Project Token: New value should be greater than last"); projectTokenPerBlock = _projectTokenPerBlock; }
8,875,072
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /// @title The Broker + Vault contract for Switcheo Exchange /// @author Switcheo Network /// @notice This contract faciliates Ethereum and ERC-20 trades /// between users. Users can trade with each other by making /// and taking offers without giving up custody of their tokens. /// Users should first deposit tokens, then communicate off-chain /// with the exchange coordinator, in order to place orders /// (make / take offers). This allows trades to be confirmed /// immediately by the coordinator, and settled on-chain through /// this contract at a later time. contract Broker is Claimable { using SafeMath for uint256; struct Offer { address maker; address offerAsset; address wantAsset; uint64 nonce; uint256 offerAmount; uint256 wantAmount; uint256 availableAmount; // the remaining offer amount } struct AnnouncedWithdrawal { uint256 amount; uint256 canWithdrawAt; } // Exchange states enum State { Active, Inactive } State public state; // The maximum announce delay in seconds // (7 days * 60 mins * 60 seconds) uint32 constant maxAnnounceDelay = 604800; // Ether token "address" is set as the constant 0x00 address constant etherAddr = address(0); // deposits uint8 constant ReasonDeposit = 0x01; // making an offer uint8 constant ReasonMakerGive = 0x02; uint8 constant ReasonMakerFeeGive = 0x10; uint8 constant ReasonMakerFeeReceive = 0x11; // filling an offer uint8 constant ReasonFillerGive = 0x03; uint8 constant ReasonFillerFeeGive = 0x04; uint8 constant ReasonFillerReceive = 0x05; uint8 constant ReasonMakerReceive = 0x06; uint8 constant ReasonFillerFeeReceive = 0x07; // cancelling an offer uint8 constant ReasonCancel = 0x08; uint8 constant ReasonCancelFeeGive = 0x12; uint8 constant ReasonCancelFeeReceive = 0x13; // withdrawals uint8 constant ReasonWithdraw = 0x09; uint8 constant ReasonWithdrawFeeGive = 0x14; uint8 constant ReasonWithdrawFeeReceive = 0x15; // The coordinator sends trades (balance transitions) to the exchange address public coordinator; // The operator receives fees address public operator; // The time required to wait after a cancellation is announced // to let the operator detect it in non-byzantine conditions uint32 public cancelAnnounceDelay; // The time required to wait after a withdrawal is announced // to let the operator detect it in non-byzantine conditions uint32 public withdrawAnnounceDelay; // User balances by: userAddress => assetHash => balance mapping(address => mapping(address => uint256)) public balances; // Offers by the creation transaction hash: transactionHash => offer mapping(bytes32 => Offer) public offers; // A record of which hashes have been used before mapping(bytes32 => bool) public usedHashes; // Set of whitelisted spender addresses allowed by the owner mapping(address => bool) public whitelistedSpenders; // Spenders which have been approved by individual user as: userAddress => spenderAddress => true mapping(address => mapping(address => bool)) public approvedSpenders; // Announced withdrawals by: userAddress => assetHash => data mapping(address => mapping(address => AnnouncedWithdrawal)) public announcedWithdrawals; // Announced cancellations by: offerHash => data mapping(bytes32 => uint256) public announcedCancellations; // Emitted when new offers made event Make(address indexed maker, bytes32 indexed offerHash); // Emitted when offers are filled event Fill(address indexed filler, bytes32 indexed offerHash, uint256 amountFilled, uint256 amountTaken, address indexed maker); // Emitted when offers are cancelled event Cancel(address indexed maker, bytes32 indexed offerHash); // Emitted on any balance state transition (+ve) event BalanceIncrease(address indexed user, address indexed token, uint256 amount, uint8 indexed reason); // Emitted on any balance state transition (-ve) event BalanceDecrease(address indexed user, address indexed token, uint256 amount, uint8 indexed reason); // Emitted when a withdrawal is annnounced event WithdrawAnnounce(address indexed user, address indexed token, uint256 amount, uint256 canWithdrawAt); // Emitted when a cancellation is annnounced event CancelAnnounce(address indexed user, bytes32 indexed offerHash, uint256 canCancelAt); // Emitted when a user approved a spender event SpenderApprove(address indexed user, address indexed spender); // Emitted when a user rescinds approval for a spender event SpenderRescind(address indexed user, address indexed spender); /// @notice Initializes the Broker contract /// @dev The coordinator and operator is initialized /// to be the address of the sender. The Broker is immediately /// put into an active state, with maximum exit delays set. constructor() public { coordinator = msg.sender; operator = msg.sender; cancelAnnounceDelay = maxAnnounceDelay; withdrawAnnounceDelay = maxAnnounceDelay; state = State.Active; } modifier onlyCoordinator() { require( msg.sender == coordinator, "Invalid sender" ); _; } modifier onlyActiveState() { require( state == State.Active, "Invalid state" ); _; } modifier onlyInactiveState() { require( state == State.Inactive, "Invalid state" ); _; } modifier notMoreThanMaxDelay(uint32 _delay) { require( _delay <= maxAnnounceDelay, "Invalid delay" ); _; } modifier unusedReasonCode(uint8 _reasonCode) { require( _reasonCode > ReasonWithdrawFeeReceive, "Invalid reason code" ); _; } /// @notice Sets the Broker contract state /// @dev There are only two states - Active & Inactive. /// /// The Active state is the normal operating state for the contract - /// deposits, trading and withdrawals can be carried out. /// /// In the Inactive state, the coordinator can invoke additional /// emergency methods such as emergencyCancel and emergencyWithdraw, /// without the cooperation of users. However, deposits and trading /// methods cannot be invoked at that time. This state is meant /// primarily to terminate and upgrade the contract, or to be used /// in the event that the contract is considered no longer viable /// to continue operation, and held tokens should be immediately /// withdrawn to their respective owners. /// @param _state The state to transition the contract into function setState(State _state) external onlyOwner { state = _state; } /// @notice Sets the coordinator address. /// @dev All standard operations (except `depositEther`) /// must be invoked by the coordinator. /// @param _coordinator The address to set as the coordinator function setCoordinator(address _coordinator) external onlyOwner { _validateAddress(_coordinator); coordinator = _coordinator; } /// @notice Sets the operator address. /// @dev All fees are paid to the operator. /// @param _operator The address to set as the operator function setOperator(address _operator) external onlyOwner { _validateAddress(operator); operator = _operator; } /// @notice Sets the delay between when a cancel /// intention must be announced, and when the cancellation /// can actually be executed on-chain /// @dev This delay exists so that the coordinator has time to /// respond when a user is attempting to bypass it and cancel /// offers directly on-chain. /// Note that this is an direct on-chain cancellation /// is an atypical operation - see `slowCancel` /// for more details. /// @param _delay The delay in seconds function setCancelAnnounceDelay(uint32 _delay) external onlyOwner notMoreThanMaxDelay(_delay) { cancelAnnounceDelay = _delay; } /// @notice Sets the delay (in seconds) between when a withdrawal /// intention must be announced, and when the withdrawal /// can actually be executed on-chain. /// @dev This delay exists so that the coordinator has time to /// respond when a user is attempting to bypass it and cancel /// offers directly on-chain. See `announceWithdraw` and /// `slowWithdraw` for more details. /// @param _delay The delay in seconds function setWithdrawAnnounceDelay(uint32 _delay) external onlyOwner notMoreThanMaxDelay(_delay) { withdrawAnnounceDelay = _delay; } /// @notice Adds an address to the set of allowed spenders. /// @dev Spenders are meant to be additional EVM contracts that /// will allow adding or upgrading of trading functionality, without /// having to cancel all offers and withdraw all tokens for all users. /// This whitelist ensures that all approved spenders are contracts /// that have been verified by the owner. Note that each user also /// has to invoke `approveSpender` to actually allow the `_spender` /// to spend his/her balance, so that they can examine / verify /// the new spender contract first. /// @param _spender The address to add as a whitelisted spender function addSpender(address _spender) external onlyOwner { _validateAddress(_spender); whitelistedSpenders[_spender] = true; } /// @notice Removes an address from the set of allowed spenders. /// @dev Note that removing a spender from the whitelist will not /// prevent already approved spenders from spending a user's balance. /// This is to ensure that the spender contracts can be certain that once /// an approval is done, the owner cannot rescient spending priviledges, /// and cause tokens to be withheld or locked in the spender contract. /// Users must instead manually rescind approvals using `rescindApproval` /// after the `_spender` has been removed from the whitelist. /// @param _spender The address to remove as a whitelisted spender function removeSpender(address _spender) external onlyOwner { _validateAddress(_spender); delete whitelistedSpenders[_spender]; } /// @notice Deposits Ethereum tokens under the `msg.sender`'s balance /// @dev Allows sending ETH to the contract, and increasing /// the user's contract balance by the amount sent in. /// This operation is only usable in an Active state to prevent /// a terminated contract from receiving tokens. function depositEther() external payable onlyActiveState { require( msg.value > 0, 'Invalid value' ); balances[msg.sender][etherAddr] = balances[msg.sender][etherAddr].add(msg.value); emit BalanceIncrease(msg.sender, etherAddr, msg.value, ReasonDeposit); } /// @notice Deposits ERC20 tokens under the `_user`'s balance /// @dev Allows sending ERC20 tokens to the contract, and increasing /// the user's contract balance by the amount sent in. This operation /// can only be used after an ERC20 `approve` operation for a /// sufficient amount has been carried out. /// /// Note that this operation does not require user signatures as /// a valid ERC20 `approve` call is considered as intent to deposit /// the tokens. This is as there is no other ERC20 methods that this /// contract can call. /// /// This operation can only be called by the coordinator, /// and should be autoamtically done so whenever an `approve` event /// from a ERC20 token (that the coordinator deems valid) /// approving this contract to spend tokens on behalf of a user is seen. /// /// This operation is only usable in an Active state to prevent /// a terminated contract from receiving tokens. /// @param _user The address of the user that is depositing tokens /// @param _token The address of the ERC20 token to deposit /// @param _amount The (approved) amount to deposit function depositERC20( address _user, address _token, uint256 _amount ) external onlyCoordinator onlyActiveState { require( _amount > 0, 'Invalid value' ); balances[_user][_token] = balances[_user][_token].add(_amount); ERC20(_token).transferFrom(_user, address(this), _amount); require( _getSanitizedReturnValue(), "transferFrom failed." ); emit BalanceIncrease(_user, _token, _amount, ReasonDeposit); } /// @notice Withdraws `_amount` worth of `_token`s to the `_withdrawer` /// @dev This is the standard withdraw operation. Tokens can only be /// withdrawn directly to the token balance owner's address. /// Fees can be paid to cover network costs, as the operation must /// be invoked by the coordinator. The hash of all parameters, prefixed /// with the operation name "withdraw" must be signed by the withdrawer /// to validate the withdrawal request. A nonce that is issued by the /// coordinator is used to prevent replay attacks. /// See `slowWithdraw` for withdrawing without requiring the coordinator's /// involvement. /// @param _withdrawer The address of the user that is withdrawing tokens /// @param _token The address of the token to withdraw /// @param _amount The number of tokens to withdraw /// @param _feeAsset The address of the token to use for fee payment /// @param _feeAmount The amount of tokens to pay as fees to the operator /// @param _nonce The nonce to prevent replay attacks /// @param _v The `v` component of the `_withdrawer`'s signature /// @param _r The `r` component of the `_withdrawer`'s signature /// @param _s The `s` component of the `_withdrawer`'s signature function withdraw( address _withdrawer, address _token, uint256 _amount, address _feeAsset, uint256 _feeAmount, uint64 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) external onlyCoordinator { bytes32 msgHash = keccak256(abi.encodePacked( "withdraw", _withdrawer, _token, _amount, _feeAsset, _feeAmount, _nonce )); require( _recoverAddress(msgHash, _v, _r, _s) == _withdrawer, "Invalid signature" ); _validateAndAddHash(msgHash); _withdraw(_withdrawer, _token, _amount, _feeAsset, _feeAmount); } /// @notice Announces intent to withdraw tokens using `slowWithdraw` /// @dev Allows a user to invoke `slowWithdraw` after a minimum of /// `withdrawAnnounceDelay` seconds has passed. /// This announcement and delay is necessary so that the operator has time /// to respond if a user attempts to invoke a `slowWithdraw` even though /// the exchange is operating normally. In that case, the coordinator would respond /// by not allowing the announced amount of tokens to be used in future trades /// the moment a `WithdrawAnnounce` is seen. /// @param _token The address of the token to withdraw after the required exit delay /// @param _amount The number of tokens to withdraw after the required exit delay function announceWithdraw( address _token, uint256 _amount ) external { require( _amount <= balances[msg.sender][_token], "Amount too high" ); AnnouncedWithdrawal storage announcement = announcedWithdrawals[msg.sender][_token]; uint256 canWithdrawAt = now + withdrawAnnounceDelay; announcement.canWithdrawAt = canWithdrawAt; announcement.amount = _amount; emit WithdrawAnnounce(msg.sender, _token, _amount, canWithdrawAt); } /// @notice Withdraw tokens without requiring the coordinator /// @dev This operation is meant to be used if the operator becomes "byzantine", /// so that users can still exit tokens locked in this contract. /// The `announceWithdraw` operation has to be invoked first, and a minimum time of /// `withdrawAnnounceDelay` seconds have to pass, before this operation can be carried out. /// Note that this direct on-chain withdrawal is an atypical operation, and /// the normal `withdraw` operation should be used in non-byzantine states. /// @param _withdrawer The address of the user that is withdrawing tokens /// @param _token The address of the token to withdraw /// @param _amount The number of tokens to withdraw function slowWithdraw( address _withdrawer, address _token, uint256 _amount ) external { AnnouncedWithdrawal memory announcement = announcedWithdrawals[_withdrawer][_token]; require( announcement.canWithdrawAt != 0 && announcement.canWithdrawAt <= now, "Insufficient delay" ); require( announcement.amount == _amount, "Invalid amount" ); delete announcedWithdrawals[_withdrawer][_token]; _withdraw(_withdrawer, _token, _amount, etherAddr, 0); } /// @notice Withdraws tokens to the owner without requiring the owner's signature /// @dev Can only be invoked in an Inactive state by the coordinator. /// This operation is meant to be used in emergencies only. /// @param _withdrawer The address of the user that should have tokens withdrawn /// @param _token The address of the token to withdraw /// @param _amount The number of tokens to withdraw function emergencyWithdraw( address _withdrawer, address _token, uint256 _amount ) external onlyCoordinator onlyInactiveState { _withdraw(_withdrawer, _token, _amount, etherAddr, 0); } /// @notice Makes an offer which can be filled by other users. /// @dev Makes an offer for `_offerAmount` of `offerAsset` tokens /// for `wantAmount` of `wantAsset` tokens, that can be filled later /// by one or more counterparties using `fillOffer` or `fillOffers`. /// The offer can be later cancelled using `cancel` or `slowCancel` as long /// as it has not completely been filled. /// A fee of `_feeAmount` of `_feeAsset` tokens can be paid to the operator /// to cover orderbook maintenance and network costs. /// The hash of all parameters, prefixed with the operation name "makeOffer" /// must be signed by the `_maker` to validate the offer request. /// A nonce that is issued by the coordinator is used to prevent replay attacks. /// This operation can only be invoked by the coordinator in an Active state. /// @param _maker The address of the user that is making the offer /// @param _offerAsset The address of the token being offered /// @param _wantAsset The address of the token asked in return /// @param _offerAmount The number of tokens being offered /// @param _wantAmount The number of tokens asked for in return /// @param _feeAsset The address of the token to use for fee payment /// @param _feeAmount The amount of tokens to pay as fees to the operator /// @param _nonce The nonce to prevent replay attacks /// @param _v The `v` component of the `_maker`'s signature /// @param _r The `r` component of the `_maker`'s signature /// @param _s The `s` component of the `_maker`'s signature function makeOffer( address _maker, address _offerAsset, address _wantAsset, uint256 _offerAmount, uint256 _wantAmount, address _feeAsset, uint256 _feeAmount, uint64 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) external onlyCoordinator onlyActiveState { require( _offerAmount > 0 && _wantAmount > 0, "Invalid amounts" ); require( _offerAsset != _wantAsset, "Invalid assets" ); bytes32 offerHash = keccak256(abi.encodePacked( "makeOffer", _maker, _offerAsset, _wantAsset, _offerAmount, _wantAmount, _feeAsset, _feeAmount, _nonce )); require( _recoverAddress(offerHash, _v, _r, _s) == _maker, "Invalid signature" ); _validateAndAddHash(offerHash); // Reduce maker's balance _decreaseBalanceAndPayFees( _maker, _offerAsset, _offerAmount, _feeAsset, _feeAmount, ReasonMakerGive, ReasonMakerFeeGive, ReasonMakerFeeReceive ); // Store the offer Offer storage offer = offers[offerHash]; offer.maker = _maker; offer.offerAsset = _offerAsset; offer.wantAsset = _wantAsset; offer.offerAmount = _offerAmount; offer.wantAmount = _wantAmount; offer.availableAmount = _offerAmount; offer.nonce = _nonce; emit Make(_maker, offerHash); } /// @notice Fills a offer that has been previously made using `makeOffer`. /// @dev Fill an offer with `_offerHash` by giving `_amountToTake` of /// the offers' `wantAsset` tokens. /// A fee of `_feeAmount` of `_feeAsset` tokens can be paid to the operator /// to cover orderbook maintenance and network costs. /// The hash of all parameters, prefixed with the operation name "fillOffer" /// must be signed by the `_filler` to validate the fill request. /// A nonce that is issued by the coordinator is used to prevent replay attacks. /// This operation can only be invoked by the coordinator in an Active state. /// @param _filler The address of the user that is filling the offer /// @param _offerHash The hash of the offer to fill /// @param _amountToTake The number of tokens to take from the offer /// @param _feeAsset The address of the token to use for fee payment /// @param _feeAmount The amount of tokens to pay as fees to the operator /// @param _nonce The nonce to prevent replay attacks /// @param _v The `v` component of the `_filler`'s signature /// @param _r The `r` component of the `_filler`'s signature /// @param _s The `s` component of the `_filler`'s signature function fillOffer( address _filler, bytes32 _offerHash, uint256 _amountToTake, address _feeAsset, uint256 _feeAmount, uint64 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) external onlyCoordinator onlyActiveState { bytes32 msgHash = keccak256( abi.encodePacked( "fillOffer", _filler, _offerHash, _amountToTake, _feeAsset, _feeAmount, _nonce ) ); require( _recoverAddress(msgHash, _v, _r, _s) == _filler, "Invalid signature" ); _validateAndAddHash(msgHash); _fill(_filler, _offerHash, _amountToTake, _feeAsset, _feeAmount); } /// @notice Fills multiple offers that have been previously made using `makeOffer`. /// @dev Fills multiple offers with hashes in `_offerHashes` for amounts in /// `_amountsToTake`. This method allows conserving of the base gas cost. /// A fee of `_feeAmount` of `_feeAsset` tokens can be paid to the operator /// to cover orderbook maintenance and network costs. /// The hash of all parameters, prefixed with the operation name "fillOffers" /// must be signed by the maker to validate the fill request. /// A nonce that is issued by the coordinator is used to prevent replay attacks. /// This operation can only be invoked by the coordinator in an Active state. /// @param _filler The address of the user that is filling the offer /// @param _offerHashes The hashes of the offers to fill /// @param _amountsToTake The number of tokens to take for each offer /// (each index corresponds to the entry with the same index in _offerHashes) /// @param _feeAsset The address of the token to use for fee payment /// @param _feeAmount The amount of tokens to pay as fees to the operator /// @param _nonce The nonce to prevent replay attacks /// @param _v The `v` component of the `_filler`'s signature /// @param _r The `r` component of the `_filler`'s signature /// @param _s The `s` component of the `_filler`'s signature function fillOffers( address _filler, bytes32[] _offerHashes, uint256[] _amountsToTake, address _feeAsset, uint256 _feeAmount, uint64 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) external onlyCoordinator onlyActiveState { require( _offerHashes.length > 0, 'Invalid input' ); require( _offerHashes.length == _amountsToTake.length, 'Invalid inputs' ); bytes32 msgHash = keccak256( abi.encodePacked( "fillOffers", _filler, _offerHashes, _amountsToTake, _feeAsset, _feeAmount, _nonce ) ); require( _recoverAddress(msgHash, _v, _r, _s) == _filler, "Invalid signature" ); _validateAndAddHash(msgHash); for (uint32 i = 0; i < _offerHashes.length; i++) { _fill(_filler, _offerHashes[i], _amountsToTake[i], etherAddr, 0); } _paySeparateFees( _filler, _feeAsset, _feeAmount, ReasonFillerFeeGive, ReasonFillerFeeReceive ); } /// @notice Cancels an offer that was preivously made using `makeOffer`. /// @dev Cancels the offer with `_offerHash`. An `_expectedAvailableAmount` /// is provided to allow the coordinator to ensure that the offer is not accidentally /// cancelled ahead of time (where there is a pending fill that has not been settled). /// The hash of the _offerHash, _feeAsset, `_feeAmount` prefixed with the /// operation name "cancel" must be signed by the offer maker to validate /// the cancellation request. Only the coordinator can invoke this operation. /// See `slowCancel` for cancellation without requiring the coordinator's /// involvement. /// @param _offerHash The hash of the offer to cancel /// @param _expectedAvailableAmount The number of tokens that should be present when cancelling /// @param _feeAsset The address of the token to use for fee payment /// @param _feeAmount The amount of tokens to pay as fees to the operator /// @param _v The `v` component of the offer maker's signature /// @param _r The `r` component of the offer maker's signature /// @param _s The `s` component of the offer maker's signature function cancel( bytes32 _offerHash, uint256 _expectedAvailableAmount, address _feeAsset, uint256 _feeAmount, uint8 _v, bytes32 _r, bytes32 _s ) external onlyCoordinator { require( _recoverAddress(keccak256(abi.encodePacked( "cancel", _offerHash, _feeAsset, _feeAmount )), _v, _r, _s) == offers[_offerHash].maker, "Invalid signature" ); _cancel(_offerHash, _expectedAvailableAmount, _feeAsset, _feeAmount); } /// @notice Announces intent to cancel tokens using `slowCancel` /// @dev Allows a user to invoke `slowCancel` after a minimum of /// `cancelAnnounceDelay` seconds has passed. /// This announcement and delay is necessary so that the operator has time /// to respond if a user attempts to invoke a `slowCancel` even though /// the exchange is operating normally. /// In that case, the coordinator would simply stop matching the offer to /// viable counterparties the moment the `CancelAnnounce` is seen. /// @param _offerHash The hash of the offer that will be cancelled function announceCancel(bytes32 _offerHash) external { Offer memory offer = offers[_offerHash]; require( offer.maker == msg.sender, "Invalid sender" ); require( offer.availableAmount > 0, "Offer already cancelled" ); uint256 canCancelAt = now + cancelAnnounceDelay; announcedCancellations[_offerHash] = canCancelAt; emit CancelAnnounce(offer.maker, _offerHash, canCancelAt); } /// @notice Cancel an offer without requiring the coordinator /// @dev This operation is meant to be used if the operator becomes "byzantine", /// so that users can still cancel offers in this contract, and withdraw tokens /// using `slowWithdraw`. /// The `announceCancel` operation has to be invoked first, and a minimum time of /// `cancelAnnounceDelay` seconds have to pass, before this operation can be carried out. /// Note that this direct on-chain cancellation is an atypical operation, and /// the normal `cancel` operation should be used in non-byzantine states. /// @param _offerHash The hash of the offer to cancel function slowCancel(bytes32 _offerHash) external { require( announcedCancellations[_offerHash] != 0 && announcedCancellations[_offerHash] <= now, "Insufficient delay" ); delete announcedCancellations[_offerHash]; Offer memory offer = offers[_offerHash]; _cancel(_offerHash, offer.availableAmount, etherAddr, 0); } /// @notice Cancels an offer immediately once cancellation intent /// has been announced. /// @dev Can only be invoked by the coordinator. This allows /// the coordinator to quickly remove offers that it has already /// acknowledged, and move its offer book into a consistent state. function fastCancel(bytes32 _offerHash, uint256 _expectedAvailableAmount) external onlyCoordinator { require( announcedCancellations[_offerHash] != 0, "Missing annoncement" ); delete announcedCancellations[_offerHash]; _cancel(_offerHash, _expectedAvailableAmount, etherAddr, 0); } /// @notice Cancels an offer requiring the owner's signature, /// so that the tokens can be withdrawn using `emergencyWithdraw`. /// @dev Can only be invoked in an Inactive state by the coordinator. /// This operation is meant to be used in emergencies only. function emergencyCancel(bytes32 _offerHash, uint256 _expectedAvailableAmount) external onlyCoordinator onlyInactiveState { _cancel(_offerHash, _expectedAvailableAmount, etherAddr, 0); } /// @notice Approve an address for spending any amount of /// any token from the `msg.sender`'s balances /// @dev Analogous to ERC-20 `approve`, with the following differences: /// - `_spender` must be whitelisted by owner /// - approval can be rescinded at a later time by the user /// iff it has been removed from the whitelist /// - spending amount is unlimited /// @param _spender The address to approve spending function approveSpender(address _spender) external { require( whitelistedSpenders[_spender], "Spender is not whitelisted" ); approvedSpenders[msg.sender][_spender] = true; emit SpenderApprove(msg.sender, _spender); } /// @notice Rescinds a previous approval for spending the `msg.sender`'s contract balance. /// @dev Rescinds approval for a spender, after it has been removed from /// the `whitelistedSpenders` set. This allows an approval to be removed /// if both the owner and user agrees that the previously approved spender /// contract should no longer be used. /// @param _spender The address to rescind spending approval function rescindApproval(address _spender) external { require( approvedSpenders[msg.sender][_spender], "Spender has not been approved" ); require( whitelistedSpenders[_spender] != true, "Spender must be removed from the whitelist" ); delete approvedSpenders[msg.sender][_spender]; emit SpenderRescind(msg.sender, _spender); } /// @notice Transfers tokens from one address to another /// @dev Analogous to ERC-20 `transferFrom`, with the following differences: /// - the address of the token to transfer must be specified /// - any amount of token can be transferred, as long as it is less or equal /// to `_from`'s balance /// - reason codes can be attached and they must not use reasons specified in /// this contract /// @param _from The address to transfer tokens from /// @param _to The address to transfer tokens to /// @param _amount The number of tokens to transfer /// @param _token The address of the token to transfer /// @param _decreaseReason A reason code to emit in the `BalanceDecrease` event /// @param _increaseReason A reason code to emit in the `BalanceIncrease` event function spendFrom( address _from, address _to, uint256 _amount, address _token, uint8 _decreaseReason, uint8 _increaseReason ) external unusedReasonCode(_decreaseReason) unusedReasonCode(_increaseReason) { require( approvedSpenders[_from][msg.sender], "Spender has not been approved" ); _validateAddress(_to); balances[_from][_token] = balances[_from][_token].sub(_amount); emit BalanceDecrease(_from, _token, _amount, _decreaseReason); balances[_to][_token] = balances[_to][_token].add(_amount); emit BalanceIncrease(_to, _token, _amount, _increaseReason); } /// @dev Overrides ability to renounce ownership as this contract is /// meant to always have an owner. function renounceOwnership() public { require(false, "Cannot have no owner"); } /// @dev The actual withdraw logic that is used internally by multiple operations. function _withdraw( address _withdrawer, address _token, uint256 _amount, address _feeAsset, uint256 _feeAmount ) private { // SafeMath.sub checks that balance is sufficient already _decreaseBalanceAndPayFees( _withdrawer, _token, _amount, _feeAsset, _feeAmount, ReasonWithdraw, ReasonWithdrawFeeGive, ReasonWithdrawFeeReceive ); if (_token == etherAddr) // ether { _withdrawer.transfer(_amount); } else { ERC20(_token).transfer(_withdrawer, _amount); require( _getSanitizedReturnValue(), "transfer failed" ); } } /// @dev The actual fill logic that is used internally by multiple operations. function _fill( address _filler, bytes32 _offerHash, uint256 _amountToTake, address _feeAsset, uint256 _feeAmount ) private { require( _amountToTake > 0, "Invalid input" ); Offer storage offer = offers[_offerHash]; require( offer.maker != _filler, "Invalid filler" ); require( offer.availableAmount != 0, "Offer already filled" ); uint256 amountToFill = (_amountToTake.mul(offer.wantAmount)).div(offer.offerAmount); // transfer amountToFill in fillAsset from filler to maker balances[_filler][offer.wantAsset] = balances[_filler][offer.wantAsset].sub(amountToFill); emit BalanceDecrease(_filler, offer.wantAsset, amountToFill, ReasonFillerGive); balances[offer.maker][offer.wantAsset] = balances[offer.maker][offer.wantAsset].add(amountToFill); emit BalanceIncrease(offer.maker, offer.wantAsset, amountToFill, ReasonMakerReceive); // deduct amountToTake in takeAsset from offer offer.availableAmount = offer.availableAmount.sub(_amountToTake); _increaseBalanceAndPayFees( _filler, offer.offerAsset, _amountToTake, _feeAsset, _feeAmount, ReasonFillerReceive, ReasonFillerFeeGive, ReasonFillerFeeReceive ); emit Fill(_filler, _offerHash, amountToFill, _amountToTake, offer.maker); if (offer.availableAmount == 0) { delete offers[_offerHash]; } } /// @dev The actual cancellation logic that is used internally by multiple operations. function _cancel( bytes32 _offerHash, uint256 _expectedAvailableAmount, address _feeAsset, uint256 _feeAmount ) private { Offer memory offer = offers[_offerHash]; require( offer.availableAmount > 0, "Offer already cancelled" ); require( offer.availableAmount == _expectedAvailableAmount, "Invalid input" ); delete offers[_offerHash]; _increaseBalanceAndPayFees( offer.maker, offer.offerAsset, offer.availableAmount, _feeAsset, _feeAmount, ReasonCancel, ReasonCancelFeeGive, ReasonCancelFeeReceive ); emit Cancel(offer.maker, _offerHash); } /// @dev Performs an `ecrecover` operation for signed message hashes /// in accordance to EIP-191. function _recoverAddress(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) private pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hash)); return ecrecover(prefixedHash, _v, _r, _s); } /// @dev Decreases a user's balance while adding a cut from the decrement /// to be paid as fees to the operator. Reason codes should be provided /// to be emitted with events for tracking. function _decreaseBalanceAndPayFees( address _user, address _token, uint256 _amount, address _feeAsset, uint256 _feeAmount, uint8 _reason, uint8 _feeGiveReason, uint8 _feeReceiveReason ) private { uint256 totalAmount = _amount; if (_feeAsset == _token) { totalAmount = _amount.add(_feeAmount); } balances[_user][_token] = balances[_user][_token].sub(totalAmount); emit BalanceDecrease(_user, _token, totalAmount, _reason); _payFees(_user, _token, _feeAsset, _feeAmount, _feeGiveReason, _feeReceiveReason); } /// @dev Increases a user's balance while deducting a cut from the increment /// to be paid as fees to the operator. Reason codes should be provided /// to be emitted with events for tracking. function _increaseBalanceAndPayFees( address _user, address _token, uint256 _amount, address _feeAsset, uint256 _feeAmount, uint8 _reason, uint8 _feeGiveReason, uint8 _feeReceiveReason ) private { uint256 totalAmount = _amount; if (_feeAsset == _token) { totalAmount = _amount.sub(_feeAmount); } balances[_user][_token] = balances[_user][_token].add(totalAmount); emit BalanceIncrease(_user, _token, totalAmount, _reason); _payFees(_user, _token, _feeAsset, _feeAmount, _feeGiveReason, _feeReceiveReason); } /// @dev Pays fees to the operator, attaching the specified reason codes /// to the emitted event, only deducting from the `_user` balance if the /// `_token` does not match `_feeAsset`. /// IMPORTANT: In the event that the `_token` matches `_feeAsset`, /// there should a reduction in balance increment carried out separately, /// to ensure balance consistency. function _payFees( address _user, address _token, address _feeAsset, uint256 _feeAmount, uint8 _feeGiveReason, uint8 _feeReceiveReason ) private { if (_feeAmount == 0) { return; } // if the feeAsset does not match the token then the feeAmount needs to be separately deducted if (_feeAsset != _token) { balances[_user][_feeAsset] = balances[_user][_feeAsset].sub(_feeAmount); emit BalanceDecrease(_user, _feeAsset, _feeAmount, _feeGiveReason); } balances[operator][_feeAsset] = balances[operator][_feeAsset].add(_feeAmount); emit BalanceIncrease(operator, _feeAsset, _feeAmount, _feeReceiveReason); } /// @dev Pays fees to the operator, attaching the specified reason codes to the emitted event. function _paySeparateFees( address _user, address _feeAsset, uint256 _feeAmount, uint8 _feeGiveReason, uint8 _feeReceiveReason ) private { if (_feeAmount == 0) { return; } balances[_user][_feeAsset] = balances[_user][_feeAsset].sub(_feeAmount); emit BalanceDecrease(_user, _feeAsset, _feeAmount, _feeGiveReason); balances[operator][_feeAsset] = balances[operator][_feeAsset].add(_feeAmount); emit BalanceIncrease(operator, _feeAsset, _feeAmount, _feeReceiveReason); } /// @dev Ensures that the address is a valid user address. function _validateAddress(address _address) private pure { require( _address != address(0), 'Invalid address' ); } /// @dev Ensures a hash hasn't been already used, which would mean /// a repeated set of arguments and nonce was used. This prevents /// replay attacks. function _validateAndAddHash(bytes32 _hash) private { require( usedHashes[_hash] != true, "hash already used" ); usedHashes[_hash] = true; } /// @dev Fix for ERC-20 tokens that do not have proper return type /// See: https://github.com/ethereum/solidity/issues/4116 /// https://medium.com/loopring-protocol/an-incompatibility-in-smart-contract-threatening-dapp-ecosystem-72b8ca5db4da /// https://github.com/sec-bit/badERC20Fix/blob/master/badERC20Fix.sol function _getSanitizedReturnValue() private pure returns (bool) { uint256 result = 0; assembly { switch returndatasize case 0 { // this is an non-standard ERC-20 token result := 1 // assume success on no revert } case 32 { // this is a standard ERC-20 token returndatacopy(0, 0, 32) result := mload(0) } default { // this is not an ERC-20 token revert(0, 0) // revert for safety } } return result != 0; } }
The actual fill logic that is used internally by multiple operations. transfer amountToFill in fillAsset from filler to maker deduct amountToTake in takeAsset from offer
function _fill( address _filler, bytes32 _offerHash, uint256 _amountToTake, address _feeAsset, uint256 _feeAmount ) private { require( _amountToTake > 0, "Invalid input" ); Offer storage offer = offers[_offerHash]; require( offer.maker != _filler, "Invalid filler" ); require( offer.availableAmount != 0, "Offer already filled" ); uint256 amountToFill = (_amountToTake.mul(offer.wantAmount)).div(offer.offerAmount); balances[_filler][offer.wantAsset] = balances[_filler][offer.wantAsset].sub(amountToFill); emit BalanceDecrease(_filler, offer.wantAsset, amountToFill, ReasonFillerGive); balances[offer.maker][offer.wantAsset] = balances[offer.maker][offer.wantAsset].add(amountToFill); emit BalanceIncrease(offer.maker, offer.wantAsset, amountToFill, ReasonMakerReceive); offer.availableAmount = offer.availableAmount.sub(_amountToTake); _increaseBalanceAndPayFees( _filler, offer.offerAsset, _amountToTake, _feeAsset, _feeAmount, ReasonFillerReceive, ReasonFillerFeeGive, ReasonFillerFeeReceive ); emit Fill(_filler, _offerHash, amountToFill, _amountToTake, offer.maker); if (offer.availableAmount == 0) { delete offers[_offerHash]; } }
956,526
./full_match/8453/0x5Ba641A1Fa1E6A7D033c9f6A8108d52B92b78257/sources/contracts/HATVaultsRegistry.sol
See {IHATVaultsRegistry-swapAndSend}. / Needed to avoid a "stack too deep" error hacker gets her reward via vesting contract solhint-disable-next-line not-rely-on-time solhint-disable-next-line not-rely-on-time
function swapAndSend( address _asset, address[] calldata _beneficiaries, uint256 _amountOutMinimum, address _routingContract, bytes calldata _routingPayload ) external onlyOwner { SwapData memory _swapData; _swapData.hackerRewards = new uint256[](_beneficiaries.length); _swapData.governanceHatReward = governanceHatReward[_asset]; _swapData.amount = _swapData.governanceHatReward; for (uint256 i = 0; i < _beneficiaries.length;) { _swapData.hackerRewards[i] = hackersHatReward[_asset][_beneficiaries[i]]; hackersHatReward[_asset][_beneficiaries[i]] = 0; _swapData.amount += _swapData.hackerRewards[i]; } if (_swapData.amount == 0) revert AmountToSwapIsZero(); IERC20 _HAT = HAT; (_swapData.hatsReceived, _swapData.amountUnused) = _swapTokenForHAT(IERC20(_asset), _swapData.amount, _amountOutMinimum, _routingContract, _routingPayload); _swapData.usedPart = (_swapData.amount - _swapData.amountUnused); _swapData.governanceAmountSwapped = _swapData.usedPart.mulDiv(_swapData.governanceHatReward, _swapData.amount); governanceHatReward[_asset] = _swapData.amountUnused.mulDiv(_swapData.governanceHatReward, _swapData.amount); for (uint256 i = 0; i < _beneficiaries.length;) { uint256 _hackerReward = _swapData.hatsReceived.mulDiv(_swapData.hackerRewards[i], _swapData.amount); uint256 _hackerAmountSwapped = _swapData.usedPart.mulDiv(_swapData.hackerRewards[i], _swapData.amount); _swapData.totalHackerReward += _hackerReward; hackersHatReward[_asset][_beneficiaries[i]] = _swapData.amountUnused.mulDiv(_swapData.hackerRewards[i], _swapData.amount); address _tokenLock; if (_hackerReward > 0) { _tokenLock = tokenLockFactory.createTokenLock( address(_HAT), _beneficiaries[i], _hackerReward, generalParameters.hatVestingPeriods, ITokenLock.Revocability.Disabled, true ); _HAT.safeTransfer(_tokenLock, _hackerReward); } emit SwapAndSend(_beneficiaries[i], _hackerAmountSwapped, _hackerReward, _tokenLock); } address _owner = owner(); uint256 _amountToOwner = _swapData.hatsReceived - _swapData.totalHackerReward; _HAT.safeTransfer(_owner, _amountToOwner); emit SwapAndSend(_owner, _swapData.governanceAmountSwapped, _amountToOwner, address(0)); }
11,548,682
pragma solidity ^0.4.11; contract Pixel { /* This creates an array with all balances */ struct Section { address owner; uint256 price; bool for_sale; bool initial_purchase_done; uint image_id; string md5; uint last_update; address sell_only_to; uint16 index; //bytes32[10] image_data; } string public standard = "IPO 0.9"; string public constant name = "Initial Pixel Offering"; string public constant symbol = "IPO"; uint8 public constant decimals = 0; mapping (address => uint256) public balanceOf; mapping (address => uint256) public ethBalance; address owner; uint256 public ipo_price; Section[10000] public sections; uint256 public pool; uint public mapWidth; uint public mapHeight; uint256 tokenTotalSupply = 10000; event Buy(uint section_id); event NewListing(uint section_id, uint price); event Delisted(uint section_id); event NewImage(uint section_id); event AreaPrice(uint start_section_index, uint end_section_index, uint area_price); event SentValue(uint value); event PriceUpdate(uint256 price); event WithdrawEvent(string msg); function Pixel() { pool = tokenTotalSupply; //Number of token / spaces ipo_price = 100000000000000000; // 0.1 mapWidth = 1000; mapHeight = 1000; owner = msg.sender; } function totalSupply() constant returns (uint totalSupply) { totalSupply = tokenTotalSupply; } /// Updates a pixel section's index number /// Not to be called by anyone but the contract owner function updatePixelIndex( uint16 _start, uint16 _end ) { if(msg.sender != owner) throw; if(_end < _start) throw; while(_start < _end) { sections[_start].index = _start; _start++; } } /// Update the current IPO price function updateIPOPrice( uint256 _new_price ) { if(msg.sender != owner) throw; ipo_price = _new_price; PriceUpdate(ipo_price); } /* Get the index to access a section object from the provided raw x,y */ /// Convert from a pixel's x, y coordinates to its section index /// This is a helper function function getSectionIndexFromRaw( uint _x, uint _y ) returns (uint) { if (_x >= mapWidth) throw; if (_y >= mapHeight) throw; // Convert raw x, y to section identifer x y _x = _x / 10; _y = _y / 10; //Get section_identifier from coords return _x + (_y * 100); } /* Get the index to access a section object from its section identifier */ /// Get Section index based on its upper left x,y coordinates or "identifier" /// coordinates /// This is a helper function function getSectionIndexFromIdentifier ( uint _x_section_identifier, uint _y_section_identifier ) returns (uint) { if (_x_section_identifier >= (mapWidth / 10)) throw; if (_y_section_identifier >= (mapHeight / 10)) throw; uint index = _x_section_identifier + (_y_section_identifier * 100); return index; } /* Get x,y section_identifier from a section index */ /// Get Section upper left x,y coordinates or "identifier" coordinates /// based on its index number /// This is a helper function function getIdentifierFromSectionIndex( uint _index ) returns (uint x, uint y) { if (_index > (mapWidth * mapHeight)) throw; x = _index % 100; y = (_index - (_index % 100)) / 100; } /* Check to see if Section is available for first purchase */ /// Returns whether a section is available for purchase at IPO price function sectionAvailable( uint _section_index ) returns (bool) { if (_section_index >= sections.length) throw; Section s = sections[_section_index]; // The section has not been puchased previously return !s.initial_purchase_done; } /* Check to see if Section is available for purchase */ /// Returns whether a section is available for purchase as a market sale function sectionForSale( uint _section_index ) returns (bool) { if (_section_index >= sections.length) throw; Section s = sections[_section_index]; // Has the user set the section as for_sale if(s.for_sale) { // Has the owner set a "sell only to" address? if(s.sell_only_to == 0x0) return true; if(s.sell_only_to == msg.sender) return true; return false; } else { // Not for sale return false; } } /* Get the price of the Section */ /// Returns the price of a section at market price. /// This is a helper function, it is more efficient to just access the /// contract's sections attribute directly function sectionPrice( uint _section_index ) returns (uint) { if (_section_index >= sections.length) throw; Section s = sections[_section_index]; return s.price; } /* Check to see if a region is available provided the top-left (start) section and the bottom-right (end) section. */ /// Returns if a section is available for purchase, it returns the following: /// bool: if the region is available for purchase /// uint256: the extended price, sum of all of the market prices of the sections /// in the region /// uint256: the number of sections available in the region at the IPO price function regionAvailable( uint _start_section_index, uint _end_section_index ) returns (bool available, uint extended_price, uint ipo_count) { if (_end_section_index < _start_section_index) throw; var (start_x, start_y) = getIdentifierFromSectionIndex(_start_section_index); var (end_x, end_y) = getIdentifierFromSectionIndex(_end_section_index); if (start_x >= mapWidth) throw; if (start_y >= mapHeight) throw; if (end_x >= mapWidth) throw; if (end_y >= mapHeight) throw; uint y_pos = start_y; available = false; extended_price = 0; ipo_count = 0; while (y_pos <= end_y) { uint x_pos = start_x; while (x_pos <= end_x) { uint identifier = (x_pos + (y_pos * 100)); // Is this section available for first (IPO) purchase? if(sectionAvailable(identifier)) { // The section is available as an IPO ipo_count = ipo_count + 1; } else { // The section has been purchased, it can only be available // as a market sale. if(sectionForSale(identifier)) { extended_price = extended_price + sectionPrice(identifier); } else { available = false; //Don't return a price if there is an unavailable section //to reduce confusion extended_price = 0; ipo_count = 0; return; } } x_pos = x_pos + 1; } y_pos = y_pos + 1; } available = true; return; } /// Buy a section based on its index and set its cloud image_id and md5 /// This function is payable, any over payment will be withdraw-able function buySection ( uint _section_index, uint _image_id, string _md5 ) payable { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(!section.for_sale && section.initial_purchase_done) { //Section not for sale throw; } // Process payment // Is this Section on the open market? if(section.initial_purchase_done) { // Section sold, sell for market price if(msg.value < section.price) { // Not enough funds were sent throw; } else { // Calculate Fee // We only need to change the balance if the section price is non-zero if (section.price != 0) { uint fee = section.price / 100; // Pay contract owner the fee ethBalance[owner] += fee; // Pay the section owner the price minus the fee ethBalance[section.owner] += (msg.value - fee); } // Refund any overpayment //require(msg.value > (msg.value - section.price)); ethBalance[msg.sender] += (msg.value - section.price); // Owner loses a token balanceOf[section.owner]--; // Buyer gets a token balanceOf[msg.sender]++; } } else { // Initial sale, sell for IPO price if(msg.value < ipo_price) { // Not enough funds were sent throw; } else { // Pay the contract owner ethBalance[owner] += msg.value; // Refund any overpayment //require(msg.value > (msg.value - ipo_price)); ethBalance[msg.sender] += (msg.value - ipo_price); // Reduce token pool pool--; // Buyer gets a token balanceOf[msg.sender]++; } } //Payment and token transfer complete //Transfer ownership and set not for sale by default section.owner = msg.sender; section.md5 = _md5; section.image_id = _image_id; section.last_update = block.timestamp; section.for_sale = false; section.initial_purchase_done = true; // even if not the first, we can pretend it is } /* Buy an entire region */ /// Buy a region of sections starting and including the top left section index /// ending at and including the bottom left section index. And set its cloud /// image_id and md5. This function is payable, if the value sent is less /// than the price of the region, the function will throw. function buyRegion( uint _start_section_index, uint _end_section_index, uint _image_id, string _md5 ) payable returns (uint start_section_y, uint start_section_x, uint end_section_y, uint end_section_x){ if (_end_section_index < _start_section_index) throw; if (_start_section_index >= sections.length) throw; if (_end_section_index >= sections.length) throw; // ico_ammount reffers to the number of sections that are available // at ICO price var (available, ext_price, ico_amount) = regionAvailable(_start_section_index, _end_section_index); if (!available) throw; // Calculate price uint area_price = ico_amount * ipo_price; area_price = area_price + ext_price; AreaPrice(_start_section_index, _end_section_index, area_price); SentValue(msg.value); if (area_price > msg.value) throw; // ico_ammount reffers to the amount in wei that the contract owner // is owed ico_amount = 0; // ext_price reffers to the amount in wei that the contract owner is // owed in fees from market sales ext_price = 0; // User sent enough funds, let's go start_section_x = _start_section_index % 100; end_section_x = _end_section_index % 100; start_section_y = _start_section_index - (_start_section_index % 100); start_section_y = start_section_y / 100; end_section_y = _end_section_index - (_end_section_index % 100); end_section_y = end_section_y / 100; uint x_pos = start_section_x; while (x_pos <= end_section_x) { uint y_pos = start_section_y; while (y_pos <= end_section_y) { // Is this an IPO section? Section s = sections[x_pos + (y_pos * 100)]; if (s.initial_purchase_done) { // Sale, we need to transfer balance // We only need to modify balances if the section's price // is non-zero if(s.price != 0) { // Pay the contract owner the price ethBalance[owner] += (s.price / 100); // Pay the owner the price minus the fee ethBalance[s.owner] += (s.price - (s.price / 100)); } // Refund any overpayment //if(msg.value > (msg.value - s.price)) throw; ext_price += s.price; // Owner loses a token balanceOf[s.owner]--; // Buyer gets a token balanceOf[msg.sender]++; } else { // IPO we get to keep the value // Pay the contract owner ethBalance[owner] += ipo_price; // Refund any overpayment //if(msg.value > (msg.value - ipo_price)) throw; // TODO Decrease the value ico_amount += ipo_price; // Reduce token pool pool--; // Buyer gets a token balanceOf[msg.sender]++; } // Payment and token transfer complete // Transfer ownership and set not for sale by default s.owner = msg.sender; s.md5 = _md5; s.image_id = _image_id; //s.last_update = block.timestamp; s.for_sale = false; s.initial_purchase_done = true; // even if not the first, we can pretend it is Buy(x_pos + (y_pos * 100)); // Done y_pos = y_pos + 1; } x_pos = x_pos + 1; } ethBalance[msg.sender] += msg.value - (ext_price + ico_amount); return; } /* Set the for sale flag and a price for a section */ /// Set an inidividual section as for sale at the provided price in wei. /// The section will be available for purchase by any address. function setSectionForSale( uint _section_index, uint256 _price ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.price = _price; section.for_sale = true; section.sell_only_to = 0x0; NewListing(_section_index, _price); } /* Set the for sale flag and price for a region */ /// Set a section region for sale at the provided price in wei. /// The sections in the region will be available for purchase by any address. function setRegionForSale( uint _start_section_index, uint _end_section_index, uint _price ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.price = _price; section.for_sale = true; section.sell_only_to = 0x0; NewListing(x_pos + (y_pos * 100), _price); } y_pos++; } x_pos++; } } /* Set the for sale flag and price for a region */ /// Set a section region starting in the top left at the supplied start section /// index to and including the supplied bottom right end section index /// for sale at the provided price in wei, to the provided address. /// The sections in the region will be available for purchase only by the /// provided address. function setRegionForSaleToAddress( uint _start_section_index, uint _end_section_index, uint _price, address _only_sell_to ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.price = _price; section.for_sale = true; section.sell_only_to = _only_sell_to; NewListing(x_pos + (y_pos * 100), _price); } y_pos++; } x_pos++; } } /* Set an entire region's cloud image data */ /// Update a region of sections' cloud image_id and md5 to be redrawn on the /// map starting at the top left start section index to and including the /// bottom right section index. Fires a NewImage event with the top left /// section index. If any sections not owned by the sender are in the region /// they are ignored. function setRegionImageDataCloud( uint _start_section_index, uint _end_section_index, uint _image_id, string _md5 ) { if (_end_section_index < _start_section_index) throw; var (start_x, start_y) = getIdentifierFromSectionIndex(_start_section_index); var (end_x, end_y) = getIdentifierFromSectionIndex(_end_section_index); if (start_x >= mapWidth) throw; if (start_y >= mapHeight) throw; if (end_x >= mapWidth) throw; if (end_y >= mapHeight) throw; uint y_pos = start_y; while (y_pos <= end_y) { uint x_pos = start_x; while (x_pos <= end_x) { uint identifier = (x_pos + (y_pos * 100)); Section s = sections[identifier]; if(s.owner == msg.sender) { s.image_id = _image_id; s.md5 = _md5; } x_pos = x_pos + 1; } y_pos = y_pos + 1; } NewImage(_start_section_index); return; } /* Set the for sale flag and a price for a section to a specific address */ /// Set a single section as for sale at the provided price in wei only /// to the supplied address. function setSectionForSaleToAddress( uint _section_index, uint256 _price, address _to ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.price = _price; section.for_sale = true; section.sell_only_to = _to; NewListing(_section_index, _price); } /* Remove the for sale flag from a section */ /// Delist a section for sale. Making it no longer available on the market. function unsetSectionForSale( uint _section_index ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.for_sale = false; section.price = 0; section.sell_only_to = 0x0; Delisted(_section_index); } /* Set the for sale flag and price for a region */ /// Delist a region of sections for sale. Making the sections no longer /// no longer available on the market. function unsetRegionForSale( uint _start_section_index, uint _end_section_index ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.for_sale = false; section.price = 0; Delisted(x_pos + (y_pos * 100)); } y_pos++; } x_pos++; } } /// Depreciated. Store the raw image data in the contract. function setImageData( uint _section_index // bytes32 _row_zero, // bytes32 _row_one, // bytes32 _row_two, // bytes32 _row_three, // bytes32 _row_four, // bytes32 _row_five, // bytes32 _row_six, // bytes32 _row_seven, // bytes32 _row_eight, // bytes32 _row_nine ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; // section.image_data[0] = _row_zero; // section.image_data[1] = _row_one; // section.image_data[2] = _row_two; // section.image_data[3] = _row_three; // section.image_data[4] = _row_four; // section.image_data[5] = _row_five; // section.image_data[6] = _row_six; // section.image_data[7] = _row_seven; // section.image_data[8] = _row_eight; // section.image_data[9] = _row_nine; section.image_id = 0; section.md5 = ""; section.last_update = block.timestamp; NewImage(_section_index); } /// Set a section's image data to be redrawn on the map. Fires a NewImage /// event. function setImageDataCloud( uint _section_index, uint _image_id, string _md5 ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.image_id = _image_id; section.md5 = _md5; section.last_update = block.timestamp; NewImage(_section_index); } /// Withdraw ethereum from the sender's ethBalance. function withdraw() returns (bool) { var amount = ethBalance[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. ethBalance[msg.sender] = 0; WithdrawEvent("Reset Sender"); msg.sender.transfer(amount); } return true; } /// Deposit ethereum into the sender's ethBalance. Not recommended. function deposit() payable { ethBalance[msg.sender] += msg.value; } /// Transfer a section and an IPO token to the supplied address. function transfer( address _to, uint _section_index ) { if (_section_index > 9999) throw; if (sections[_section_index].owner != msg.sender) throw; if (balanceOf[_to] + 1 < balanceOf[_to]) throw; sections[_section_index].owner = _to; sections[_section_index].for_sale = false; balanceOf[msg.sender] -= 1; balanceOf[_to] += 1; } /// Transfer a region of sections and IPO tokens to the supplied address. function transferRegion( uint _start_section_index, uint _end_section_index, address _to ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { if (balanceOf[_to] + 1 < balanceOf[_to]) throw; section.owner = _to; section.for_sale = false; balanceOf[msg.sender] -= 1; balanceOf[_to] += 1; } y_pos++; } x_pos++; } } }
Set the for sale flag and a price for a section to a specific address / Set a single section as for sale at the provided price in wei only to the supplied address.
function setSectionForSaleToAddress( uint _section_index, uint256 _price, address _to ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.price = _price; section.for_sale = true; section.sell_only_to = _to; NewListing(_section_index, _price); }
12,839,874
./partial_match/1/0xa75Ee0A9A57B9f4badD3F8D64271A386d07d2B3b/sources/PositionTokenLogic.sol
reset approval to 0
function _tradeUserAsset( address sourceTokenAddress, address destTokenAddress, address receiver, uint256 sourceTokenAmount, bool throwOnError) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed) { address oracleAddress = IBZx(bZxContract).oracleAddresses(bZxOracle); uint256 tempAllowance = ERC20(sourceTokenAddress).allowance(address(this), oracleAddress); if (tempAllowance < sourceTokenAmount) { if (tempAllowance != 0) { require(ERC20(sourceTokenAddress).approve(oracleAddress, 0), "token approval reset failed"); } require(ERC20(sourceTokenAddress).approve(oracleAddress, MAX_UINT), "token approval failed"); } (bool success, bytes memory data) = oracleAddress.call( abi.encodeWithSignature( "tradeUserAsset(address,address,address,address,uint256,uint256,uint256)", sourceTokenAddress, destTokenAddress, sourceTokenAmount, ) ); require(!throwOnError || success, "trade error"); assembly { if eq(success, 1) { destTokenAmountReceived := mload(add(data, 32)) sourceTokenAmountUsed := mload(add(data, 64)) } } }
2,863,097
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _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; 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` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value;//交易发起者允许地址是——spender的用户对他自己的代币可以转移的数量 return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply 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 Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract MyAdvancedToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint) public lockedAmount; mapping (address => uint) public lockedTime; /* public event about locking */ event LockToken(address target, uint256 amount, uint256 unlockTime); event OwnerUnlock(address target, uint256 amount); event UserUnlock(uint256 amount); /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function MyAdvancedToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } //pay violator's debt by send coin function punish(address violator,address victim,uint amount) public onlyOwner { _transfer(violator,victim,amount); } function rename(string newTokenName,string newSymbolName) public onlyOwner { name = newTokenName; // Set the name for display purposes symbol = newSymbolName; } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value *(10**18)/ buyPrice; // calculates the amount///最小单位 _transfer(owner, msg.sender, amount); // makes the transfers //向合约的拥有者转移以太币 if(!owner.send(msg.value) ){ revert(); } } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } /// @notice lock some amount token /// @param target address which will be locked some token /// @param lockAmount token amount /// @param lockPeriod time until unlock function lockToken (address target, uint256 lockAmount, uint256 lockPeriod) onlyOwner public returns(bool res) { require(balanceOf[msg.sender] >= lockAmount); // make sure owner has enough balance require(lockedAmount[target] == 0); // cannot lock unless lockedAmount is 0 balanceOf[msg.sender] -= lockAmount; lockedAmount[target] = lockAmount; lockedTime[target] = now + lockPeriod; LockToken(target, lockAmount, now + lockPeriod); return true; } /// @notice cotnract owner unlock some token for target address despite of time /// @param target address to receive unlocked token /// @param amount unlock token amount, no more than locked of this address function ownerUnlock (address target, uint256 amount) onlyOwner public returns(bool res) { require(lockedAmount[target] >= amount); balanceOf[target] += amount; lockedAmount[target] -= amount; OwnerUnlock(target, amount); return true; } /// @notice user unlock his/her own token /// @param amount token that user wish to unlock function userUnlockToken (uint256 amount) public returns(bool res) { require(lockedAmount[msg.sender] >= amount); // make sure no more token user could unlock require(now >= lockedTime[msg.sender]); // make sure won't unlock too soon lockedAmount[msg.sender] -= amount; balanceOf[msg.sender] += amount; UserUnlock(amount); return true; } /// @notice multisend token to many address /// @param addrs addresses to receive token /// @param _value token each addrs will receive function multisend (address[] addrs, uint256 _value) public returns(bool res) { uint length = addrs.length; require(_value * length <= balanceOf[msg.sender]); uint i = 0; while (i < length) { transfer(addrs[i], _value); i ++; } return true; } }
Buy tokens from contract by sending ether向合约的拥有者转移以太币
function buy() payable public { if(!owner.send(msg.value) ){ revert(); } }
5,764,845
./partial_match/56/0xBE1e0536D99053ca046773B54E429996cBF81E02/sources/MasterChef.sol
See {BEP20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {BEP20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./
function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].BBNO(amount, 'BEP20: transfer amount exceeds allowance') ); return true; }
11,112,797
pragma solidity 0.7.5; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import "@openzeppelin/contracts/access/AccessControl.sol"; import './Node.sol'; contract HeadNode is AccessControl { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); address[] public nodes; mapping (address => bool) public isNode; IERC20 public tokenEFD; string private _name; address private _headNode; //headNode é ElFederal constructor(address tokenEFDAddress_, address admin_, string memory name_) public { _name = name_; tokenEFD = IERC20(tokenEFDAddress_); _headNode = msg.sender; _setupRole(ADMIN_ROLE, admin_); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "only Admin"); _; } function name() public view returns (string memory) { return _name; } function headNode() public view returns (address) { return _headNode; } function tokenBalance() public view returns (uint256) { return tokenEFD.balanceOf(address(this)); } //grantRole(WHITELIST_ROLE, _account); //Only who are in ADMIN_ROLE event CreateNode (address indexed _address, address indexed _headAddress, address indexed _admin, string _name); function createNode (address admin_, string memory name_) public onlyAdmin returns (address) { Node node = new Node(address(tokenEFD), admin_, name_); nodes.push(address(node)); isNode[address(node)] = true; emit CreateNode(address(node), address(this), admin_, name_); //tokenEFD.transfer (address(node), 50); return address(node); } function listNodes () public view returns (address[] memory) { return nodes; } function addAdminNode (address _node, address _admin) public returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE Node node = Node(_node); node.grantRole(ADMIN_ROLE, _admin); return true; } function removeAdminNode (address _node, address _admin) public returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE Node node = Node(_node); node.revokeRole(ADMIN_ROLE, _admin); return true; } //Send token from HeadNode to Node function send(address _to, uint256 _value) public onlyAdmin returns (bool) { require(isNode[_to], "To is not a node"); require (tokenEFD.transfer (_to, _value), "error sending"); return true; } }
Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
function removeAdminNode (address _node, address _admin) public returns (bool) { Node node = Node(_node); node.revokeRole(ADMIN_ROLE, _admin); return true; }
1,003,690
//"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "./GoldFeverNativeGold.sol"; // import "./GoldFeverItem.sol"; contract GoldFeverAuction is ReentrancyGuard, IERC721Receiver, ERC721Holder { bytes32 public constant CREATED = keccak256("CREATED"); bytes32 public constant BID = keccak256("BID"); bytes32 public constant FINISHED = keccak256("FINISHED"); using Counters for Counters.Counter; Counters.Counter private _auctionIds; IERC20 ngl; uint256 public constant build = 3; constructor(address ngl_) public { ngl = IERC20(ngl_); } enum Status { active, finished } event AuctionCreated( uint256 auctionId, address nftContract, uint256 nftId, address owner, uint256 startingPrice, uint256 startTime, uint256 duration, uint256 biddingStep ); event AuctionBid(uint256 auctionId, address bidder, uint256 price); event Claim(uint256 auctionId, address winner); struct Auction { uint256 auctionId; address nftContract; uint256 nftId; address owner; uint256 startTime; uint256 startingPrice; uint256 biddingStep; uint256 duration; uint256 highestBidAmount; address highestBidder; bytes32 status; } mapping(uint256 => Auction) public idToAuction; function createAuction( address nftContract, uint256 nftId, uint256 startingPrice, uint256 startTime, uint256 duration, uint256 biddingStep ) public nonReentrant returns (uint256) { _auctionIds.increment(); uint256 auctionId = _auctionIds.current(); idToAuction[auctionId] = Auction( auctionId, nftContract, nftId, msg.sender, startTime, startingPrice, biddingStep, duration, startingPrice, address(0), CREATED ); IERC721(nftContract).safeTransferFrom(msg.sender, address(this), nftId); emit AuctionCreated( auctionId, nftContract, nftId, msg.sender, startingPrice, startTime, duration, biddingStep ); return auctionId; } function bid(uint256 auctionId, uint256 price) public nonReentrant returns (bool) { uint256 startDate = idToAuction[auctionId].startTime; uint256 endDate = idToAuction[auctionId].startTime + idToAuction[auctionId].duration; require( block.timestamp >= startDate && block.timestamp < endDate, "Auction is finished or not started yet" ); if (idToAuction[auctionId].status == CREATED) { require( price >= idToAuction[auctionId].startingPrice, "Must bid equal or higher than current startingPrice" ); ngl.transferFrom(msg.sender, address(this), price); idToAuction[auctionId].highestBidAmount = price; idToAuction[auctionId].highestBidder = msg.sender; idToAuction[auctionId].status = BID; emit AuctionBid(auctionId, msg.sender, price); return true; } if (idToAuction[auctionId].status == BID) { require( price >= idToAuction[auctionId].highestBidAmount + idToAuction[auctionId].biddingStep, "Must bid higher than current highest bid" ); ngl.transferFrom(msg.sender, address(this), price); if (idToAuction[auctionId].highestBidder != address(0)) { // return ngl to the previuos bidder ngl.transfer( idToAuction[auctionId].highestBidder, idToAuction[auctionId].highestBidAmount ); } // register new bidder idToAuction[auctionId].highestBidder = msg.sender; idToAuction[auctionId].highestBidAmount = price; emit AuctionBid(auctionId, msg.sender, price); return true; } return false; } function getCurrentBidOwner(uint256 auctionId) public view returns (address) { return idToAuction[auctionId].highestBidder; } function getCurrentBidAmount(uint256 auctionId) public view returns (uint256) { return idToAuction[auctionId].highestBidAmount; } function isFinished(uint256 auctionId) public view returns (bool) { return getStatus(auctionId) == Status.finished; } function getStatus(uint256 auctionId) public view returns (Status) { uint256 expiry = idToAuction[auctionId].startTime + idToAuction[auctionId].duration; if (block.timestamp >= expiry) { return Status.finished; } else { return Status.active; } } function getWinner(uint256 auctionId) public view returns (address) { require(isFinished(auctionId), "Auction is not finished"); return idToAuction[auctionId].highestBidder; } function claimItem(uint256 auctionId) private { address winner = getWinner(auctionId); require(winner != address(0), "There is no winner"); address nftContract = idToAuction[auctionId].nftContract; IERC721(nftContract).safeTransferFrom( address(this), winner, idToAuction[auctionId].nftId ); emit Claim(auctionId, winner); } function finalizeAuction(uint256 auctionId) public nonReentrant { require(isFinished(auctionId), "Auction is not finished"); require( idToAuction[auctionId].status != FINISHED, "Auction is already finalized" ); if (idToAuction[auctionId].highestBidder == address(0)) { IERC721(idToAuction[auctionId].nftContract).safeTransferFrom( address(this), idToAuction[auctionId].owner, idToAuction[auctionId].nftId ); idToAuction[auctionId].status == FINISHED; } else { ngl.transfer( idToAuction[auctionId].owner, idToAuction[auctionId].highestBidAmount ); claimItem(auctionId); idToAuction[auctionId].status == FINISHED; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import {IChildToken} from "@maticnetwork/pos-portal/contracts/child/ChildToken/IChildToken.sol"; import {NativeMetaTransaction} from "@maticnetwork/pos-portal/contracts/common/NativeMetaTransaction.sol"; import {ContextMixin} from "@maticnetwork/pos-portal/contracts/common/ContextMixin.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract GoldFeverNativeGold is ERC20, ERC20Burnable, IChildToken, AccessControlMixin, NativeMetaTransaction, ContextMixin { bytes32 public constant DEPOSITOR_ROLE = keccak256("DEPOSITOR_ROLE"); constructor( address childChainManager ) public ERC20("Gold Fever Native Gold", "NGL") { _setupContractId("GoldFeverNativeGold"); _setupRole(DEPOSITOR_ROLE, childChainManager); _initializeEIP712("Gold Fever Native Gold"); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal view override returns (address payable sender) { return ContextMixin.msgSender(); } /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required amount for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded amount */ function deposit(address user, bytes calldata depositData) external override only(DEPOSITOR_ROLE) { uint256 amount = abi.decode(depositData, (uint256)); _mint(user, amount); } /** * @notice called when user wants to withdraw tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param amount amount of tokens to withdraw */ function withdraw(uint256 amount) external { _burn(_msgSender(), amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.6.6; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } pragma solidity 0.6.6; interface IChildToken { function deposit(address user, bytes calldata depositData) external; } pragma solidity 0.6.6; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @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()); } } } pragma solidity 0.6.6; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "./GoldFeverNativeGold.sol"; contract GoldFeverRight is ReentrancyGuard, IERC721Receiver, ERC721Holder { bytes32 public constant CREATED = keccak256("CREATED"); bytes32 public constant STAKED = keccak256("STAKED"); bytes32 public constant BURNED = keccak256("BURNED"); bytes32 public constant FINALIZED = keccak256("FINALIZED"); using Counters for Counters.Counter; Counters.Counter private _rightOptionIds; Counters.Counter private _rightPurchaseIds; GoldFeverNativeGold ngl; constructor(address ngl_) public { ngl = GoldFeverNativeGold(ngl_); } struct RightOption { uint256 rightId; uint256 rightOptionId; uint256 rightType; uint256 price; uint256 duration; } struct RightPurchase { uint256 rightOptionId; uint256 rightPurchaseId; address buyer; bytes32 status; uint256 expiry; uint256 price; uint256 duration; } mapping(uint256 => RightOption) public idToRightOption; mapping(uint256 => mapping(uint256 => RightPurchase)) public rightIdToRightPurchase; event RightOptionCreated( uint256 indexed rightId, uint256 indexed rightOptionId, uint256 rightType, uint256 price, uint256 duration ); event RightOptionPurchased( uint256 indexed rightOptionId, uint256 indexed rightPurchaseId, address buyer, string status, uint256 expiry, uint256 price, uint256 duration ); event RightOptionPurchaseFinished(uint256 indexed rightPurchaseId); function createRightOption( uint256 rightId, uint256 rightType, uint256 price, uint256 duration ) public nonReentrant { require(price > 0, "Price must be at least 1 wei"); _rightOptionIds.increment(); uint256 rightOptionId = _rightOptionIds.current(); idToRightOption[rightOptionId] = RightOption( rightId, rightOptionId, rightType, price, duration ); emit RightOptionCreated( rightId, rightOptionId, rightType, price, duration ); } function purchaseRight(uint256 rightOptionId) public nonReentrant { uint256 price = idToRightOption[rightOptionId].price; uint256 duration = idToRightOption[rightOptionId].duration; uint256 rightType = idToRightOption[rightOptionId].rightType; uint256 expiry = block.timestamp + duration; _rightPurchaseIds.increment(); uint256 rightPurchaseId = _rightPurchaseIds.current(); if (rightType == 0) { ngl.transferFrom(msg.sender, address(this), price); rightIdToRightPurchase[rightOptionId][ rightPurchaseId ] = RightPurchase( rightOptionId, rightPurchaseId, msg.sender, STAKED, expiry, price, duration ); emit RightOptionPurchased( rightOptionId, rightPurchaseId, msg.sender, "STAKED", expiry, price, duration ); } else if (rightType == 1) { ngl.burnFrom(msg.sender, price); rightIdToRightPurchase[rightOptionId][ rightPurchaseId ] = RightPurchase( rightOptionId, rightPurchaseId, msg.sender, BURNED, expiry, price, duration ); emit RightOptionPurchased( rightOptionId, rightPurchaseId, msg.sender, "BURNED", expiry, price, duration ); } } function finalizeRightPurchase( uint256 rightOptionId, uint256 rightPurchaseId ) public nonReentrant { require( rightIdToRightPurchase[rightOptionId][rightPurchaseId].status == STAKED, "Error" ); require( rightIdToRightPurchase[rightOptionId][rightPurchaseId].expiry <= block.timestamp, "Not expired" ); uint256 price = idToRightOption[rightOptionId].price; ngl.transfer( rightIdToRightPurchase[rightOptionId][rightPurchaseId].buyer, price ); rightIdToRightPurchase[rightOptionId][rightPurchaseId] .status = FINALIZED; emit RightOptionPurchaseFinished(rightPurchaseId); } function getRightPurchase(uint256 rightOptionId, uint256 rightPurchaseId) public view returns ( address buyer, string memory status, uint256 expiry ) { RightPurchase memory rightPurchase = rightIdToRightPurchase[ rightOptionId ][rightPurchaseId]; if (rightPurchase.status == keccak256("STAKED")) { status = "STAKED"; } else if (rightPurchase.status == keccak256("BURNED")) { status = "BURNED"; } else if (rightPurchase.status == keccak256("FINALIZED")) { status = "FINALIZED"; } buyer = rightPurchase.buyer; expiry = rightPurchase.expiry; } function getRightOption(uint256 rightOptionId) public view returns ( uint256 rightId, uint256 rightType, uint256 price, uint256 duration ) { RightOption memory rightOption = idToRightOption[rightOptionId]; rightId = rightOption.rightId; rightType = rightOption.rightType; price = rightOption.price; duration = rightOption.duration; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; contract GoldFeverSwap is IERC721Receiver, ERC721Holder, ReentrancyGuard { bytes32 public constant STATUS_CREATED = keccak256("STATUS_CREATED"); bytes32 public constant STATUS_SWAPPED = keccak256("STATUS_SWAPPED"); bytes32 public constant STATUS_CANCELED = keccak256("STATUS_CANCELED"); bytes32 public constant STATUS_REJECTED = keccak256("STATUS_REJECTED"); uint256 public constant build = 3; using Counters for Counters.Counter; Counters.Counter private _offerIds; IERC20 ngl; constructor(address ngl_) public { ngl = IERC20(ngl_); } struct Offer { uint256 offerId; address nftContract; address fromAddress; uint256[] fromNftIds; uint256 fromNglAmount; address toAddress; uint256[] toNftIds; uint256 toNglAmount; bytes32 status; } mapping(uint256 => Offer) public idToOffer; event OfferCreated( uint256 indexed OfferId, address nftContract, address fromAddress, uint256[] fromNftIds, uint256 fromNglAmount, address toAddress, uint256[] toNftIds, uint256 toNglAmount ); event OfferCanceled(uint256 indexed offerId); event OfferRejected(uint256 indexed offerId); event OfferSwapped(uint256 indexed offerId, address indexed buyer); function createOffer( address nftContract, uint256[] memory fromNftIds, uint256 fromNglAmount, uint256[] memory toNftIds, uint256 toNglAmount, address toAddress ) public nonReentrant { _offerIds.increment(); uint256 offerId = _offerIds.current(); idToOffer[offerId] = Offer( offerId, nftContract, msg.sender, fromNftIds, fromNglAmount, toAddress, toNftIds, toNglAmount, STATUS_CREATED ); ngl.transferFrom(msg.sender, address(this), fromNglAmount); for (uint256 i = 0; i < fromNftIds.length; i++) { IERC721(nftContract).safeTransferFrom( msg.sender, address(this), fromNftIds[i] ); } emit OfferCreated( offerId, nftContract, msg.sender, fromNftIds, fromNglAmount, toAddress, toNftIds, toNglAmount ); } function cancelOffer(uint256 offerId) public nonReentrant { require(idToOffer[offerId].fromAddress == msg.sender, "Not seller"); require( idToOffer[offerId].status == STATUS_CREATED, "Offer is not for swap" ); address fromAddress = idToOffer[offerId].fromAddress; uint256[] memory fromNftIds = idToOffer[offerId].fromNftIds; uint256 fromNglAmount = idToOffer[offerId].fromNglAmount; address nftContract = idToOffer[offerId].nftContract; ngl.transfer(fromAddress, fromNglAmount); for (uint256 i = 0; i < fromNftIds.length; i++) { IERC721(nftContract).safeTransferFrom( address(this), fromAddress, fromNftIds[i] ); } idToOffer[offerId].status = STATUS_CANCELED; emit OfferCanceled(offerId); } function rejectOffer(uint256 offerId) public nonReentrant { require(idToOffer[offerId].toAddress == msg.sender, "Not buyer"); require( idToOffer[offerId].status == STATUS_CREATED, "Offer is not for swap" ); address fromAddress = idToOffer[offerId].fromAddress; uint256[] memory fromNftIds = idToOffer[offerId].fromNftIds; uint256 fromNglAmount = idToOffer[offerId].fromNglAmount; address nftContract = idToOffer[offerId].nftContract; ngl.transfer(fromAddress, fromNglAmount); for (uint256 i = 0; i < fromNftIds.length; i++) { IERC721(nftContract).safeTransferFrom( address(this), fromAddress, fromNftIds[i] ); } idToOffer[offerId].status = STATUS_REJECTED; emit OfferRejected(offerId); } function acceptOffer(uint256 offerId) public nonReentrant { require( idToOffer[offerId].status == STATUS_CREATED, "Offer is not for swap" ); require( idToOffer[offerId].toAddress == msg.sender, "You are not the offered address" ); address fromAddress = idToOffer[offerId].fromAddress; uint256[] memory fromNftIds = idToOffer[offerId].fromNftIds; uint256 fromNglAmount = idToOffer[offerId].fromNglAmount; uint256[] memory toNftIds = idToOffer[offerId].toNftIds; uint256 toNglAmount = idToOffer[offerId].toNglAmount; address nftContract = idToOffer[offerId].nftContract; ngl.transferFrom(msg.sender, fromAddress, toNglAmount); for (uint256 i = 0; i < toNftIds.length; i++) { IERC721(nftContract).safeTransferFrom( msg.sender, fromAddress, toNftIds[i] ); } ngl.transfer(msg.sender, fromNglAmount); for (uint256 i = 0; i < fromNftIds.length; i++) { IERC721(nftContract).safeTransferFrom( address(this), msg.sender, fromNftIds[i] ); } idToOffer[offerId].status = STATUS_SWAPPED; emit OfferSwapped(offerId, msg.sender); } function getOffer(uint256 offerId) public view returns ( address fromAddress, uint256[] memory fromNftIds, uint256 fromNglAmount, uint256[] memory toNftIds, uint256 toNglAmount, address toAddress, string memory status ) { Offer memory offer = idToOffer[offerId]; if (offer.status == keccak256("STATUS_CREATED")) { status = "CREATED"; } else if (offer.status == keccak256("STATUS_CANCELED")) { status = "CANCELED"; } else if (offer.status == keccak256("STATUS_REJECTED")) { status = "REJECTED"; } else { status = "SWAPPED"; } fromAddress = offer.fromAddress; fromNftIds = offer.fromNftIds; fromNglAmount = offer.fromNglAmount; toNftIds = offer.toNftIds; toNglAmount = offer.toNglAmount; toAddress = offer.toAddress; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import "./GoldFeverItemTier.sol"; import "./GoldFeverNativeGold.sol"; import "hardhat/console.sol"; contract GoldFeverNpc is AccessControlMixin, IERC721Receiver, ERC721Holder, ReentrancyGuard { using Counters for Counters.Counter; Counters.Counter private _hiringIds; uint256 private npcFee = 10 * (10**3); uint256 private npcEarning = 0; uint256 private rentPercentageLimit = 20 * (10**3); uint256 private ticketPercentageLimit = 20 * (10**3); bytes32 public constant STATUS_REQUESTED = keccak256("REQUESTED"); bytes32 public constant STATUS_CREATED = keccak256("CREATED"); bytes32 public constant STATUS_CANCELED = keccak256("CANCELED"); bytes32 public constant OWNER_SLOTS = keccak256("OWNER_SLOTS"); bytes32 public constant GUEST_SLOTS = keccak256("GUEST_SLOTS"); bytes32 public constant TYPE_RENT = keccak256("TYPE_RENT"); bytes32 public constant TYPE_TICKET = keccak256("TYPE_TICKET"); IERC20 ngl; GoldFeverItemTier gfiTier; constructor( address admin, address ngl_, address gfiTier_ ) public { _setupRole(DEFAULT_ADMIN_ROLE, admin); ngl = GoldFeverNativeGold(ngl_); gfiTier = GoldFeverItemTier(gfiTier_); } struct Hiring { uint256 hiringId; address nftContract; uint256 rentPercentage; uint256 ticketPercentage; uint256 buildingItem; address buildingOwner; bytes32 status; } struct RentableItem { uint256 hiringId; address itemOwner; uint256 hiringIdToItemsIndex; bytes32 status; } mapping(uint256 => Hiring) public idToHiring; mapping(uint256 => uint256[]) public hiringIdToItems; mapping(uint256 => mapping(uint256 => RentableItem)) public hiringIdToRentableItem; mapping(address => uint256) public addressToPendingEarning; mapping(uint256 => uint256) public hiringIdToOwnerSlotsCount; mapping(uint256 => uint256) public hiringIdToGuestSlotsCount; event HiringCreated( uint256 indexed hiringId, address nftContract, uint256 rentPercentage, uint256 ticketPercentage, uint256 buildingItem, address buildingOwner ); event ItemDeposited( uint256 indexed hiringId, address nftContract, address itemOwner, uint256 itemId ); event HiringCanceled(uint256 indexed hiringId); event TicketFeeUpdated(uint256 hiringId, uint256 percentage); event RentFeeUpdated(uint256 hiringId, uint256 percentage); event EarningWithdrawn(address itemOwner, uint256 earning); event WithdrawRequested( uint256 hiringId, uint256 itemId, address itemOwner ); event WithdrawApproved(uint256 hiringId, uint256 itemId, address itemOwner); event RentPaid( address renter, uint256 itemId, uint256 hiringId, uint256 amount ); event TicketPaid( address renter, uint256 itemId, uint256 hiringId, uint256 amount ); event BuildingServicePaid(address payer, uint256 hiringId, uint256 amount); function createHiring(address nftContract, uint256 buildingItem) public nonReentrant { _hiringIds.increment(); uint256 hiringId = _hiringIds.current(); //create new hiring with default percentage for both renting and tiketing limit idToHiring[hiringId] = Hiring( hiringId, nftContract, rentPercentageLimit, ticketPercentageLimit, buildingItem, msg.sender, STATUS_CREATED ); IERC721(nftContract).safeTransferFrom( msg.sender, address(this), buildingItem ); emit HiringCreated( hiringId, nftContract, rentPercentageLimit, ticketPercentageLimit, buildingItem, msg.sender ); } function depositItem( uint256 hiringId, address nftContract, uint256 itemId ) public nonReentrant { require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); uint256 slots; bool isBuildingOwner; if (idToHiring[hiringId].buildingOwner == msg.sender) { slots = gfiTier.getItemAttribute( idToHiring[hiringId].buildingItem, OWNER_SLOTS ); isBuildingOwner = true; } else { slots = gfiTier.getItemAttribute( idToHiring[hiringId].buildingItem, GUEST_SLOTS ); isBuildingOwner = false; } uint256 count; if (isBuildingOwner) { count = hiringIdToOwnerSlotsCount[hiringId]; } else { count = hiringIdToGuestSlotsCount[hiringId]; } require(count < slots, "The building is at full capacity !"); hiringIdToRentableItem[hiringId][itemId] = RentableItem( hiringId, msg.sender, hiringIdToItems[hiringId].length, STATUS_CREATED ); if (isBuildingOwner) { hiringIdToOwnerSlotsCount[hiringId]++; } else { hiringIdToGuestSlotsCount[hiringId]++; } hiringIdToItems[hiringId].push(itemId); IERC721(nftContract).safeTransferFrom( msg.sender, address(this), itemId ); emit ItemDeposited(hiringId, nftContract, msg.sender, itemId); } function requestWithdrawal(uint256 hiringId, uint256 itemId) public nonReentrant { require( idToHiring[hiringId].status != STATUS_CANCELED, "The building is already canceled !" ); require( hiringIdToRentableItem[hiringId][itemId].status == STATUS_CREATED, "Can not re-request withdrawal" ); require( hiringIdToRentableItem[hiringId][itemId].itemOwner == msg.sender, "You are not the item owner" ); hiringIdToRentableItem[hiringId][itemId].status = STATUS_REQUESTED; emit WithdrawRequested( hiringId, itemId, hiringIdToRentableItem[hiringId][itemId].itemOwner ); } function approveWithdrawal( uint256 hiringId, uint256 itemId, address nftContract ) public only(DEFAULT_ADMIN_ROLE) { require( idToHiring[hiringId].status != STATUS_CANCELED, "The building is already canceled !" ); require( hiringIdToRentableItem[hiringId][itemId].status == STATUS_REQUESTED, "Can not approve withdrawal on non-requested item" ); address itemOwner = hiringIdToRentableItem[hiringId][itemId].itemOwner; uint256 currentItemIndex = hiringIdToRentableItem[hiringId][itemId] .hiringIdToItemsIndex; uint256 lastItemIndex = hiringIdToItems[hiringId].length - 1; if (addressToPendingEarning[itemOwner] > 0) { ngl.transfer(itemOwner, addressToPendingEarning[itemOwner]); addressToPendingEarning[itemOwner] = 0; } IERC721(nftContract).safeTransferFrom(address(this), itemOwner, itemId); if (idToHiring[hiringId].buildingOwner == itemOwner) { hiringIdToOwnerSlotsCount[hiringId]--; } else { hiringIdToGuestSlotsCount[hiringId]--; } if (currentItemIndex < lastItemIndex) { uint256 lastItemId = hiringIdToItems[hiringId][lastItemIndex]; hiringIdToItems[hiringId][currentItemIndex] = lastItemId; hiringIdToRentableItem[hiringId][lastItemId] .hiringIdToItemsIndex = currentItemIndex; } hiringIdToItems[hiringId].pop(); delete hiringIdToRentableItem[hiringId][itemId]; emit WithdrawApproved(hiringId, itemId, itemOwner); } function withdrawEarning() public nonReentrant { ngl.transfer(msg.sender, addressToPendingEarning[msg.sender]); emit EarningWithdrawn(msg.sender, addressToPendingEarning[msg.sender]); addressToPendingEarning[msg.sender] = 0; } function payFee( address renter, uint256 itemId, uint256 hiringId, uint256 amount, bytes32 feeType ) public nonReentrant { require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); require( feeType == TYPE_RENT || feeType == TYPE_TICKET, "Incorrect fee type" ); uint256 decimal = 10**uint256(feeDecimals()); uint256 percentage = feeType == TYPE_RENT ? idToHiring[hiringId].rentPercentage : idToHiring[hiringId].ticketPercentage; //Calculate contract and item owner earning uint256 npcEarn = (amount * npcFee) / decimal / 100; uint256 itemEarn = ((amount - npcEarn) * 100 * decimal) / (100 * decimal + percentage); //Add earning to array addressToPendingEarning[ hiringIdToRentableItem[hiringId][itemId].itemOwner ] += itemEarn; addressToPendingEarning[idToHiring[hiringId].buildingOwner] += (amount - npcEarn - itemEarn); npcEarning += npcEarn; ngl.transferFrom(msg.sender, address(this), amount); if (feeType == TYPE_RENT) emit RentPaid(renter, itemId, hiringId, amount); else emit TicketPaid(renter, itemId, hiringId, amount); } function payBuildingServiceFee( address payer, uint256 hiringId, uint256 amount ) public nonReentrant { require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); uint256 decimal = 10**uint256(feeDecimals()); uint256 npcEarn = (amount * npcFee) / decimal / 100; addressToPendingEarning[idToHiring[hiringId].buildingOwner] += (amount - npcEarn); npcEarning += npcEarn; ngl.transferFrom(msg.sender, address(this), amount); emit BuildingServicePaid(payer, hiringId, amount); } function setTicketFee(uint256 hiringId, uint256 percentage) public nonReentrant { require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); require( msg.sender == idToHiring[hiringId].buildingOwner, "You are not the building owner" ); require( percentage <= ticketPercentageLimit, "The fee can't be set more than the limit !" ); idToHiring[hiringId].ticketPercentage = percentage; emit TicketFeeUpdated(hiringId, percentage); } function setRentFee(uint256 hiringId, uint256 percentage) public nonReentrant { require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); require( msg.sender == idToHiring[hiringId].buildingOwner, "You are not the building owner" ); require( percentage <= rentPercentageLimit, "The fee can't be set more than the limit !" ); idToHiring[hiringId].rentPercentage = percentage; emit RentFeeUpdated(hiringId, percentage); } function cancelHiring(uint256 hiringId, address nftContract) public nonReentrant { require( idToHiring[hiringId].buildingOwner == msg.sender, "You are not the building owner !" ); require( idToHiring[hiringId].status == STATUS_CREATED, "The building is already canceled !" ); ngl.transfer(msg.sender, addressToPendingEarning[msg.sender]); addressToPendingEarning[msg.sender] = 0; IERC721(nftContract).safeTransferFrom( address(this), msg.sender, idToHiring[hiringId].buildingItem ); idToHiring[hiringId].status = STATUS_CANCELED; for (uint256 i = 0; i < hiringIdToItems[hiringId].length; i++) { address itemOwner = hiringIdToRentableItem[hiringId][ hiringIdToItems[hiringId][i] ].itemOwner; ngl.transfer(itemOwner, addressToPendingEarning[itemOwner]); addressToPendingEarning[itemOwner] = 0; IERC721(nftContract).safeTransferFrom( address(this), itemOwner, hiringIdToItems[hiringId][i] ); if ( hiringIdToRentableItem[hiringId][hiringIdToItems[hiringId][i]] .status == STATUS_REQUESTED ) emit WithdrawApproved( hiringId, hiringIdToItems[hiringId][i], itemOwner ); } emit HiringCanceled(hiringId); } function getPendingEarning() public view returns (uint256 earning) { earning = addressToPendingEarning[msg.sender]; } function getPercentageLimit() public view returns (uint256 rentLimit, uint256 ticketLimit) { rentLimit = rentPercentageLimit; ticketLimit = ticketPercentageLimit; } function setNpcFee(uint256 percentage) public only(DEFAULT_ADMIN_ROLE) { npcFee = percentage; } function setRentPercentageLimit(uint256 percentage) public only(DEFAULT_ADMIN_ROLE) { rentPercentageLimit = percentage; } function setTicketPercentageLimit(uint256 percentage) public only(DEFAULT_ADMIN_ROLE) { ticketPercentageLimit = percentage; } function withdrawNpcFee(address receivedAddress) public only(DEFAULT_ADMIN_ROLE) { ngl.transfer(receivedAddress, npcEarning); npcEarning = 0; } function setGoldFeverItemTierContract(address gfiTierAddress) public only(DEFAULT_ADMIN_ROLE) { gfiTier = GoldFeverItemTier(gfiTierAddress); } function feeDecimals() public pure returns (uint8) { return 3; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import {IGoldFeverItemType} from "./GoldFeverItemType.sol"; contract GoldFeverItemTier is ReentrancyGuard, AccessControlMixin { IERC721 nftContract; IERC20 ngl; address public itemTypeContract; constructor( address admin, address nftContract_, address nglContract_, address itemType_ ) public { _setupRole(DEFAULT_ADMIN_ROLE, admin); nftContract = IERC721(nftContract_); ngl = IERC20(nglContract_); itemTypeContract = itemType_; } mapping(uint256 => uint256) public _tier; mapping(uint256 => mapping(uint256 => uint256)) public itemTypeIdToTierUpgradePrice; mapping(uint256 => mapping(uint256 => mapping(bytes32 => uint256))) public itemTypeIdToTierAttribute; event TierAdded( uint256 indexed itemTypeId, uint256 tierId, uint256 upgradePrice ); event ItemTierUpgraded(uint256 indexed itemId, uint256 tierId); event ItemUpgraded(uint256 indexed itemId, uint256 tierId); event TierAttributeUpdated( uint256 indexed itemTypeId, uint256 tierId, bytes32 attribute, uint256 value ); function addTier( uint256 itemTypeId, uint256 tierId, uint256 upgradePrice ) public only(DEFAULT_ADMIN_ROLE) { require(tierId >= 2, "Tier must be greater than or equal to 2"); itemTypeIdToTierUpgradePrice[itemTypeId][tierId] = upgradePrice; emit TierAdded(itemTypeId, tierId, upgradePrice); } function setItemTypeContract(address itemType_) public only(DEFAULT_ADMIN_ROLE) { itemTypeContract = itemType_; } function setItemTier(uint256 itemId, uint256 tierId) public only(DEFAULT_ADMIN_ROLE) { require(tierId >= 1, "Tier must be greater than or equal to 1"); _tier[itemId] = tierId; emit ItemTierUpgraded(itemId, tierId); } function getItemTier(uint256 itemId) public view returns (uint256 tierId) { if (_tier[itemId] > 0) tierId = _tier[itemId]; else tierId = 1; } function upgradeItem(uint256 itemId) public nonReentrant { require( IERC721(nftContract).ownerOf(itemId) == msg.sender, "You are not the item owner" ); uint256 currentTier = getItemTier(itemId); uint256 itemTypeId = IGoldFeverItemType(itemTypeContract).getItemType( itemId ); ngl.transferFrom( msg.sender, address(this), itemTypeIdToTierUpgradePrice[itemTypeId][currentTier + 1] ); _tier[itemId] = currentTier + 1; emit ItemTierUpgraded(itemId, _tier[itemId]); } function setTierAttribute( uint256 itemTypeId, uint256 tierId, bytes32 attribute, uint256 value ) public only(DEFAULT_ADMIN_ROLE) { require(tierId >= 1, "Tier must be greater than or equal to 1"); itemTypeIdToTierAttribute[itemTypeId][tierId][attribute] = value; emit TierAttributeUpdated(itemTypeId, tierId, attribute, value); } function getTierAttribute( uint256 itemTypeId, uint256 tierId, bytes32 attribute ) public view returns (uint256 value) { require(tierId >= 1, "Tier must be greater than or equal to 1"); value = itemTypeIdToTierAttribute[itemTypeId][tierId][attribute]; } function getItemAttribute(uint256 itemId, bytes32 attribute) public view returns (uint256 value) { uint256 itemTypeId = IGoldFeverItemType(itemTypeContract).getItemType( itemId ); uint256 tierId = getItemTier(itemId); value = itemTypeIdToTierAttribute[itemTypeId][tierId][attribute]; } function collectFee(address receivedAddress) public only(DEFAULT_ADMIN_ROLE) { ngl.transfer(receivedAddress, ngl.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; interface IGoldFeverItemType { function getItemType(uint256 itemId) external view returns (uint256 typeId); } contract GoldFeverItemTypeV1 is IGoldFeverItemType { function getItemType(uint256 itemId) external view override returns (uint256 typeId) { if (itemId & ((1 << 4) - 1) == 1) { // Version 1 typeId = (itemId >> 4) & ((1 << 20) - 1); } } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "./GoldFeverItem.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IGoldFeverItemType} from "./GoldFeverItemType.sol"; import "./GoldFeverNativeGold.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "hardhat/console.sol"; contract GoldFeverMask is ERC721, ReentrancyGuard, AccessControlMixin, IERC721Receiver, ERC721Holder { bytes32 public constant FORGED = keccak256("FORGED"); uint256 private forgeMaskFee; uint256 private unforgeMaskFee; uint256 private purchaseMaskCost; uint256 private commissionRate; uint256 private nglFromCollectedFee = 0; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _maskIds; GoldFeverItem gfi; GoldFeverNativeGold ngl; address public itemTypeContract; constructor( address admin, address gfiContract_, address nglContract_, address itemTypeContract_ ) public ERC721("GFMask", "GFM") { _setupRole(DEFAULT_ADMIN_ROLE, admin); gfi = GoldFeverItem(gfiContract_); itemTypeContract = itemTypeContract_; ngl = GoldFeverNativeGold(nglContract_); uint256 decimals = ngl.decimals(); forgeMaskFee = 3 * (10**decimals); unforgeMaskFee = 3 * (10**decimals); purchaseMaskCost = 10 * (10**decimals); commissionRate = 1; } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not admin"); _; } struct Mask { uint256 id; address owner; bytes32 status; uint256 maskShape; uint256 maskMaterial; uint256 topElement; uint256 frontElement; uint256 scratches; uint256 paintOver; } mapping(uint256 => Mask) public idToMask; event MaskForged( uint256 id, address owner, uint256 maskShapeTypeId, uint256 maskMaterialTypeId, uint256 topElementTypeId, uint256 frontElementTypeId, uint256 scratchesTypeId, uint256 paintOverTypeId ); event MaskUnforged(uint256 id); event MaskPurchased(uint256 id); function forgeMask( uint256 maskShape, uint256 maskMaterial, uint256 topElement, uint256 frontElement, uint256 scratches, uint256 paintOver ) public nonReentrant { require(maskShape > 0, "Need at least one shape"); require(maskMaterial > 0, "Need at least one material"); require( IGoldFeverItemType(itemTypeContract).getItemType(maskShape) >= 231010 && IGoldFeverItemType(itemTypeContract).getItemType(maskShape) <= 231024, "Invalid mask shape" ); require( IGoldFeverItemType(itemTypeContract).getItemType(maskMaterial) >= 231110 && IGoldFeverItemType(itemTypeContract).getItemType( maskMaterial ) <= 231124, "Invalid mask material" ); require( (IGoldFeverItemType(itemTypeContract).getItemType(topElement) >= 231210 && IGoldFeverItemType(itemTypeContract).getItemType(topElement) <= 231224) || IGoldFeverItemType(itemTypeContract).getItemType(topElement) == 0, "Invalid top element" ); require( (IGoldFeverItemType(itemTypeContract).getItemType(frontElement) >= 231310 && IGoldFeverItemType(itemTypeContract).getItemType( frontElement ) <= 231325) || IGoldFeverItemType(itemTypeContract).getItemType( frontElement ) == 0, "Invalid front element" ); require( (IGoldFeverItemType(itemTypeContract).getItemType(scratches) >= 231410 && IGoldFeverItemType(itemTypeContract).getItemType(scratches) <= 231424) || IGoldFeverItemType(itemTypeContract).getItemType(scratches) == 0, "Invalid scratches" ); require( (IGoldFeverItemType(itemTypeContract).getItemType(paintOver) >= 231510 && IGoldFeverItemType(itemTypeContract).getItemType(paintOver) <= 231526) || IGoldFeverItemType(itemTypeContract).getItemType(paintOver) == 0, "Invalid paintOver" ); uint256 maskId = parseInt( string( abi.encodePacked( zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( maskShape ) ) % 10000 ), zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( maskMaterial ) ) % 10000 ), zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( topElement ) ) % 10000 ), zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( frontElement ) ) % 10000 ), zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( scratches ) ) % 10000 ), zeroPadNumber( ( IGoldFeverItemType(itemTypeContract).getItemType( paintOver ) ) % 10000 ) ) ) ); require( idToMask[maskId].status != FORGED, "This Mask Type Is Already Forged By Other User" ); gfi.safeTransferFrom(msg.sender, address(this), maskShape); gfi.safeTransferFrom(msg.sender, address(this), maskMaterial); if (IGoldFeverItemType(itemTypeContract).getItemType(topElement) != 0) { gfi.safeTransferFrom(msg.sender, address(this), topElement); } if ( IGoldFeverItemType(itemTypeContract).getItemType(frontElement) != 0 ) { gfi.safeTransferFrom(msg.sender, address(this), frontElement); } if (IGoldFeverItemType(itemTypeContract).getItemType(scratches) != 0) { gfi.safeTransferFrom(msg.sender, address(this), scratches); } if (IGoldFeverItemType(itemTypeContract).getItemType(paintOver) != 0) { gfi.safeTransferFrom(msg.sender, address(this), paintOver); } _mint(msg.sender, maskId); idToMask[maskId] = Mask( maskId, msg.sender, FORGED, maskShape, maskMaterial, topElement, frontElement, scratches, paintOver ); uint256 adminEarn = (forgeMaskFee * commissionRate) / 100; ngl.transferFrom(msg.sender, address(this), adminEarn); ngl.burnFrom(msg.sender, forgeMaskFee - adminEarn); nglFromCollectedFee += adminEarn; emit MaskForged( maskId, msg.sender, IGoldFeverItemType(itemTypeContract).getItemType(maskShape), IGoldFeverItemType(itemTypeContract).getItemType(maskMaterial), IGoldFeverItemType(itemTypeContract).getItemType(topElement), IGoldFeverItemType(itemTypeContract).getItemType(frontElement), IGoldFeverItemType(itemTypeContract).getItemType(scratches), IGoldFeverItemType(itemTypeContract).getItemType(paintOver) ); } function unforgeMask(uint256 maskId) public nonReentrant { require(idToMask[maskId].status == FORGED, "Mask is not forged"); address owner = ownerOf(maskId); require(msg.sender == owner, "Only owner can unforge"); gfi.safeTransferFrom(address(this), owner, idToMask[maskId].maskShape); gfi.safeTransferFrom( address(this), owner, idToMask[maskId].maskMaterial ); if (idToMask[maskId].topElement != 0) { gfi.safeTransferFrom( address(this), owner, idToMask[maskId].topElement ); } if (idToMask[maskId].frontElement != 0) { gfi.safeTransferFrom( address(this), owner, idToMask[maskId].frontElement ); } if (idToMask[maskId].scratches != 0) { gfi.safeTransferFrom( address(this), owner, idToMask[maskId].scratches ); } if (idToMask[maskId].paintOver != 0) { gfi.safeTransferFrom( address(this), owner, idToMask[maskId].paintOver ); } delete idToMask[maskId]; _burn(maskId); uint256 adminEarn = (unforgeMaskFee * commissionRate) / 100; ngl.transferFrom(msg.sender, address(this), adminEarn); ngl.burnFrom(msg.sender, unforgeMaskFee - adminEarn); nglFromCollectedFee += adminEarn; emit MaskUnforged(maskId); } function parseInt(string memory _value) public pure returns (uint256 _ret) { bytes memory _bytesValue = bytes(_value); uint256 j = 1; for ( uint256 i = _bytesValue.length - 1; i >= 0 && i < _bytesValue.length; i-- ) { assert(uint8(_bytesValue[i]) >= 48 && uint8(_bytesValue[i]) <= 57); _ret += (uint8(_bytesValue[i]) - 48) * j; j *= 10; } } function zeroPadNumber(uint256 value) public pure returns (string memory) { if (value < 10) { return string(abi.encodePacked("000", value.toString())); } else if (value < 100) { return string(abi.encodePacked("00", value.toString())); } else if (value < 1000) { return string(abi.encodePacked("0", value.toString())); } else { return value.toString(); } } function updateForgeMaskFee(uint256 _fee) public nonReentrant onlyAdmin { require(_fee > 0, "Fee must be greater than 0"); forgeMaskFee = _fee; } function updateUnforgeMaskFee(uint256 _fee) public nonReentrant onlyAdmin { require(_fee > 0, "Fee must be greater than 0"); unforgeMaskFee = _fee; } function updatePurchaseMaskCost(uint256 _cost) public nonReentrant onlyAdmin { require(_cost > 0, "Purchase cost must be greater than 0"); purchaseMaskCost = _cost; } function withdrawCollectedFee() public nonReentrant onlyAdmin { ngl.transfer(msg.sender, nglFromCollectedFee); nglFromCollectedFee = 0; } function getForgeMaskFee() public view returns (uint256) { return forgeMaskFee; } function getUnforgeMaskFee() public view returns (uint256) { return unforgeMaskFee; } function getPurchaseMaskCost() public view returns (uint256) { return purchaseMaskCost; } function purchaseMask(uint256 maskId) public nonReentrant { address owner = ownerOf(maskId); require(msg.sender == owner, "Only owner can purchase"); require( idToMask[maskId].status == FORGED, "Mask is not forged or already purchased" ); uint256 adminEarn = (purchaseMaskCost * commissionRate) / 100; ngl.transferFrom(owner, address(this), adminEarn); ngl.burnFrom(owner, purchaseMaskCost - adminEarn); nglFromCollectedFee += adminEarn; emit MaskPurchased(maskId); } function setCommissionRate(uint256 _rate) public nonReentrant onlyAdmin { require(_rate > 0, "Commission rate must be greater than 0"); commissionRate = _rate; } function getCommissionRate() public view returns (uint256) { return commissionRate; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import {IChildToken} from "@maticnetwork/pos-portal/contracts/child/ChildToken/IChildToken.sol"; import {NativeMetaTransaction} from "@maticnetwork/pos-portal/contracts/common/NativeMetaTransaction.sol"; import {ContextMixin} from "@maticnetwork/pos-portal/contracts/common/ContextMixin.sol"; contract GoldFeverItem is ERC721, IChildToken, AccessControlMixin, NativeMetaTransaction, ContextMixin { bytes32 public constant DEPOSITOR_ROLE = keccak256("DEPOSITOR_ROLE"); mapping(uint256 => bool) public withdrawnTokens; // limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; uint256 public constant build = 1; event WithdrawnBatch(address indexed user, uint256[] tokenIds); event TransferWithMetadata( address indexed from, address indexed to, uint256 indexed tokenId, bytes metaData ); constructor( string memory baseURI, address admin, address childChainManager ) public ERC721("Gold Fever Item", "GFI") { _setBaseURI(baseURI); _setupContractId("GoldFeverItem"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(DEPOSITOR_ROLE, childChainManager); _initializeEIP712("Gold Fever Item"); } // This is to support Native metatransactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal view override returns (address payable sender) { return ContextMixin.msgSender(); } /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokenId(s) for user * Should set `withdrawnTokens` mapping to `false` for the tokenId being deposited * Minting can also be done by other functions * @param user user address for whom deposit is being done * @param depositData abi encoded tokenIds. Batch deposit also supported. */ function deposit(address user, bytes calldata depositData) external override only(DEPOSITOR_ROLE) { // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); withdrawnTokens[tokenId] = false; _mint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { withdrawnTokens[tokenIds[i]] = false; _mint(user, tokenIds[i]); } } } /** * @notice called when user wants to withdraw token back to root chain * @dev Should handle withraw by burning user's token. * Should set `withdrawnTokens` mapping to `true` for the tokenId being withdrawn * This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdraw(uint256 tokenId) external { require( _msgSender() == ownerOf(tokenId), "GoldFeverItem: INVALID_TOKEN_OWNER" ); withdrawnTokens[tokenId] = true; _burn(tokenId); } /** * @notice called when user wants to withdraw multiple tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds tokenId list to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "GoldFeverItem: EXCEEDS_BATCH_LIMIT"); // Iteratively burn ERC721 tokens, for performing // batch withdraw for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; require( _msgSender() == ownerOf(tokenId), string( abi.encodePacked( "GoldFeverItem: INVALID_TOKEN_OWNER ", tokenId ) ) ); withdrawnTokens[tokenId] = true; _burn(tokenId); } // At last emit this event, which will be used // in MintableERC721 predicate contract on L1 // while verifying burn proof emit WithdrawnBatch(_msgSender(), tokenIds); } /** * @notice called when user wants to withdraw token back to root chain with token URI * @dev Should handle withraw by burning user's token. * Should set `withdrawnTokens` mapping to `true` for the tokenId being withdrawn * This transaction will be verified when exiting on root chain * * @param tokenId tokenId to withdraw */ function withdrawWithMetadata(uint256 tokenId) external { require( _msgSender() == ownerOf(tokenId), "GoldFeverItem: INVALID_TOKEN_OWNER" ); withdrawnTokens[tokenId] = true; // Encoding metadata associated with tokenId & emitting event emit TransferWithMetadata( ownerOf(tokenId), address(0), tokenId, this.encodeTokenMetadata(tokenId) ); _burn(tokenId); } /** * @notice This method is supposed to be called by client when withdrawing token with metadata * and pass return value of this function as second paramter of `withdrawWithMetadata` method * * It can be overridden by clients to encode data in a different form, which needs to * be decoded back by them correctly during exiting * * @param tokenId Token for which URI to be fetched */ function encodeTokenMetadata(uint256 tokenId) external view virtual returns (bytes memory) { // You're always free to change this default implementation // and pack more data in byte array which can be decoded back // in L1 return abi.encode(tokenURI(tokenId)); } /** * @notice Example function to handle minting tokens on matic chain * @dev Minting can be done as per requirement, * This implementation allows only admin to mint tokens but it can be changed as per requirement * Should verify if token is withdrawn by checking `withdrawnTokens` mapping * @param user user for whom tokens are being minted * @param tokenId tokenId to mint */ function mint(address user, uint256 tokenId) public only(DEFAULT_ADMIN_ROLE) { require( !withdrawnTokens[tokenId], "GoldFeverItem: TOKEN_EXISTS_ON_ROOT_CHAIN" ); _mint(user, tokenId); } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "./GoldFeverItem.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract GoldFeverMaskBox is ERC721, ReentrancyGuard, AccessControlMixin, IERC721Receiver, ERC721Holder { GoldFeverItem gfi; using Counters for Counters.Counter; Counters.Counter private _boxIds; constructor(address admin, address gfiContract_) public ERC721("GFMaskBox", "GFMB") { _setupRole(DEFAULT_ADMIN_ROLE, admin); gfi = GoldFeverItem(gfiContract_); } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not admin"); _; } uint256[] private maskShapesPool; uint256[] private maskMaterialsPool; uint256[] private otherMaskElementsPool; event MaskBoxCreated(uint256 indexed boxId, address owner); event MaskBoxOpened(uint256 indexed boxId, uint256[] allMaskPartIds); function createBoxes( uint256[] memory maskShapes, uint256[] memory maskMaterials, uint256[] memory otherMaskElements ) public onlyAdmin { require(maskShapes.length > 0, "Must have at least 1 mask blueprint"); require( maskMaterials.length == maskShapes.length, "Must have same number of mask materials as mask blueprints" ); require( maskShapes.length * 4 == otherMaskElements.length, "Must have 4 other mask parts for each mask" ); uint256 numBoxes = maskShapes.length; for (uint256 i = 0; i < numBoxes; i++) { _boxIds.increment(); uint256 boxId = _boxIds.current(); _mint(msg.sender, boxId); emit MaskBoxCreated(boxId, msg.sender); } // transfer ownership of mask blueprints to the mask box for (uint256 i = 0; i < maskShapes.length; i++) { gfi.safeTransferFrom(msg.sender, address(this), maskShapes[i]); maskShapesPool.push(maskShapes[i]); } // transfer ownership of mask materials to the mask box for (uint256 i = 0; i < maskMaterials.length; i++) { gfi.safeTransferFrom(msg.sender, address(this), maskMaterials[i]); maskMaterialsPool.push(maskMaterials[i]); } // transfer ownership of other mask parts to the mask box for (uint256 i = 0; i < otherMaskElements.length; i++) { gfi.safeTransferFrom( msg.sender, address(this), otherMaskElements[i] ); otherMaskElementsPool.push(otherMaskElements[i]); } } // open and burn box function openBox(uint256 boxId) public { require(msg.sender == ownerOf(boxId), "Only owner can open box"); uint256[] memory allMaskPartIds = new uint256[](6); uint256 rnd_shape = _random(maskShapesPool.length); gfi.safeTransferFrom( address(this), msg.sender, maskShapesPool[rnd_shape] ); allMaskPartIds[0] = maskShapesPool[rnd_shape]; maskShapesPool[rnd_shape] = maskShapesPool[maskShapesPool.length - 1]; maskShapesPool.pop(); uint256 rnd_material = _random(maskMaterialsPool.length); gfi.safeTransferFrom( address(this), msg.sender, maskMaterialsPool[rnd_material] ); allMaskPartIds[1] = maskMaterialsPool[rnd_material]; maskMaterialsPool[rnd_material] = maskMaterialsPool[ maskMaterialsPool.length - 1 ]; maskMaterialsPool.pop(); for (uint256 i = 0; i < 4; i++) { uint256 rnd_element = _random(otherMaskElementsPool.length); gfi.safeTransferFrom( address(this), msg.sender, otherMaskElementsPool[rnd_element] ); allMaskPartIds[i + 2] = otherMaskElementsPool[rnd_element]; otherMaskElementsPool[rnd_element] = otherMaskElementsPool[ otherMaskElementsPool.length - 1 ]; otherMaskElementsPool.pop(); } _burn(boxId); emit MaskBoxOpened(boxId, allMaskPartIds); } function _random(uint256 number) private view returns (uint256) { return uint256( keccak256(abi.encodePacked(block.difficulty, block.timestamp)) ) % number; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./GoldFeverNativeGold.sol"; import "./GoldFeverItem.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; contract GoldFeverMiningClaim is ReentrancyGuard, AccessControlMixin, IERC721Receiver, ERC721Holder { bytes32 public constant ARENA_STARTED = keccak256("ARENA_STARTED"); bytes32 public constant ARENA_CLOSED = keccak256("ARENA_CLOSED"); bytes32 public constant MINER_REGISTERED = keccak256("MINER_REGISTERED"); bytes32 public constant MINER_UNREGISTERED = keccak256("MINER_UNREGISTERED"); bytes32 public constant MINER_ENTERED = keccak256("MINER_ENTERED"); bytes32 public constant MINER_LEFT = keccak256("MINER_LEFT"); bytes32 public constant MINING_CLAIM_CREATED = keccak256("MINING_CLAIM_CREATED"); using Counters for Counters.Counter; Counters.Counter private _arenaIds; GoldFeverNativeGold ngl; GoldFeverItem gfi; address nftContract; uint256 private nglFromSellingHour = 0; uint256 private miningSpeed = 100; uint256 public arenaHourPrice; constructor( address admin, address gfiContract_, address nglContract_ ) public { _setupRole(DEFAULT_ADMIN_ROLE, admin); gfi = GoldFeverItem(gfiContract_); ngl = GoldFeverNativeGold(nglContract_); nftContract = gfiContract_; uint256 decimals = ngl.decimals(); arenaHourPrice = 200 * (10**decimals); } struct MiningClaim { uint256 miningClaimId; uint256 arenaHour; uint256 nglAmount; uint256 maxMiners; bytes32 status; } struct Arena { uint256 arenaId; address owner; uint256 miningClaimId; uint256 numMinersInArena; bytes32 status; uint256 duration; uint256 upfrontFee; uint256 commissionRate; } struct Miner { uint256 arenaId; address minerAddress; bytes32 status; } mapping(uint256 => MiningClaim) public idToMiningClaim; mapping(uint256 => Arena) public idToArena; mapping(uint256 => uint256) public arenaIdToExpiry; mapping(uint256 => mapping(address => Miner)) public idToMinerByArena; event MiningClaimCreated( uint256 indexed miningClaimId, uint256 arenaHour, uint256 nglAmount, uint256 maxMiners, address nftContract ); event ArenaStarted( uint256 indexed arenaId, address indexed owner, uint256 indexed miningClaimId, uint256 numMinersInArena, bytes32 status, uint256 duration, uint256 expiry, uint256 upfrontFee, uint256 commissionRate ); event ArenaClosed(uint256 arenaId); event MinerRegistered( uint256 arenaId, address minerAddress, bytes32 status ); event MinerCanceledRegistration( uint256 arenaId, address minerAddress, bytes32 status ); event MinerEnteredArena( uint256 arenaId, address minerAddress, bytes32 status ); event MinerLeftArena(uint256 arenaId, address minerAddress, bytes32 status); event MinerWithdrawn( uint256 arenaId, address minerAddress, uint256 nglAmount ); event Supplied(uint256 miningClaimId, uint256 nglAmount); event AddArenaHour(uint256 miningClaimId, uint256 arenaHour); event SetArenaHour(uint256 miningClaimId, uint256 arenaHour); event BuyArenaHour(uint256 miningClaimId, uint256 arenaHour); event SetMaxMiners(uint256 miningClaimId, uint256 maxMiners); modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not admin"); _; } function createMiningClaim( uint256 miningClaimId, uint256 nglAmount, uint256 arenaHour, uint256 maxMiners ) public nonReentrant onlyAdmin { require( gfi.ownerOf(miningClaimId) != address(0), "Mining claim id does not exist" ); require( idToMiningClaim[miningClaimId].status != MINING_CLAIM_CREATED, "Mining claim already created" ); ngl.transferFrom(msg.sender, address(this), nglAmount); idToMiningClaim[miningClaimId] = MiningClaim( miningClaimId, arenaHour, nglAmount, maxMiners, MINING_CLAIM_CREATED ); emit MiningClaimCreated( miningClaimId, arenaHour, nglAmount, maxMiners, nftContract ); } function supply(uint256 miningClaimId, uint256 nglAmount) public onlyAdmin { require( idToMiningClaim[miningClaimId].status == MINING_CLAIM_CREATED, "Mining claim id does not exist" ); ngl.transferFrom(msg.sender, address(this), nglAmount); idToMiningClaim[miningClaimId].nglAmount += nglAmount; emit Supplied(miningClaimId, nglAmount); } function addArenaHour(uint256 miningClaimId, uint256 arenaHour) public onlyAdmin { idToMiningClaim[miningClaimId].arenaHour += arenaHour; emit AddArenaHour(miningClaimId, arenaHour); } function setArenaHour(uint256 miningClaimId, uint256 arenaHour) public onlyAdmin { idToMiningClaim[miningClaimId].arenaHour = arenaHour; emit SetArenaHour(miningClaimId, arenaHour); } function getArenaHour(uint256 miningClaimId) public view returns (uint256) { return idToMiningClaim[miningClaimId].arenaHour; } function setArenaHourPrice(uint256 _arenaHourPrice) public only(DEFAULT_ADMIN_ROLE) { arenaHourPrice = _arenaHourPrice; } function getArenaHourPrice() public view returns (uint256) { uint256 decimals = ngl.decimals(); return arenaHourPrice / (10**decimals); } function buyArenaHour(uint256 miningClaimId, uint256 arenaHour) public nonReentrant { require( gfi.ownerOf(miningClaimId) == msg.sender, "Only owner of mining claim can buy arena hour" ); uint256 price = arenaHour * arenaHourPrice; nglFromSellingHour += price; ngl.transferFrom(msg.sender, address(this), price); idToMiningClaim[miningClaimId].arenaHour += arenaHour; emit BuyArenaHour(miningClaimId, arenaHour); } function getMiningSpeed() public view onlyAdmin returns (uint256) { return miningSpeed; } function setMiningSpeed(uint256 _miningSpeed) public onlyAdmin { miningSpeed = _miningSpeed; } function getMaxMiners(uint256 miningClaimId) public view onlyAdmin returns (uint256 maxMiners) { maxMiners = idToMiningClaim[miningClaimId].maxMiners; } function setMaxMiners(uint256 miningClaimId, uint256 maxMiners) public onlyAdmin { idToMiningClaim[miningClaimId].maxMiners = maxMiners; emit SetMaxMiners(miningClaimId, maxMiners); } function startArena( uint256 miningClaimId, uint256 duration, uint256 upfrontFee, uint256 commissionRate ) public nonReentrant { require( gfi.ownerOf(miningClaimId) == msg.sender, "Only owner of mining claim can start arena" ); require( duration <= idToMiningClaim[miningClaimId].arenaHour, "Arena open duration must be less than or equal to arena total hour" ); require(duration > 0, "Arena open duration must be greater than 0"); _arenaIds.increment(); uint256 arenaId = _arenaIds.current(); uint256 expiry = (duration * 3600) + block.timestamp; arenaIdToExpiry[arenaId] = expiry; idToArena[arenaId] = Arena( arenaId, msg.sender, miningClaimId, 0, ARENA_STARTED, duration, upfrontFee, commissionRate ); idToMiningClaim[miningClaimId].arenaHour -= duration; gfi.safeTransferFrom(msg.sender, address(this), miningClaimId); emit ArenaStarted( arenaId, msg.sender, miningClaimId, 0, ARENA_STARTED, duration, expiry, upfrontFee, commissionRate ); } function closeArena(uint256 arenaId) public nonReentrant onlyAdmin { require( arenaIdToExpiry[arenaId] <= block.timestamp, "Arena is not finished" ); uint256 miningClaimId = idToArena[arenaId].miningClaimId; idToArena[arenaId].status = ARENA_CLOSED; gfi.safeTransferFrom( address(this), idToArena[arenaId].owner, miningClaimId ); emit ArenaClosed(arenaId); } function registerAtArena(uint256 arenaId) public nonReentrant { uint256 miningClaimId = idToArena[arenaId].miningClaimId; require( idToArena[arenaId].status == ARENA_STARTED, "Arena is not started" ); require( idToArena[arenaId].numMinersInArena < idToMiningClaim[miningClaimId].maxMiners, "Arena is full" ); uint256 upfrontFee = idToArena[arenaId].upfrontFee; idToMinerByArena[arenaId][msg.sender] = Miner( arenaId, msg.sender, MINER_REGISTERED ); ngl.transferFrom(msg.sender, address(this), upfrontFee); emit MinerRegistered(arenaId, msg.sender, MINER_REGISTERED); } function cancelArenaRegistration(uint256 arenaId) public nonReentrant { require( idToMinerByArena[arenaId][msg.sender].status == MINER_REGISTERED, "Miner already entered arena" ); uint256 upfrontFee = idToArena[arenaId].upfrontFee; delete idToMinerByArena[arenaId][msg.sender]; ngl.transfer(msg.sender, upfrontFee); emit MinerCanceledRegistration(arenaId, msg.sender, MINER_UNREGISTERED); } function enterArena(uint256 arenaId, address minerAddress) public nonReentrant onlyAdmin { require( idToMinerByArena[arenaId][minerAddress].status == MINER_REGISTERED, "Miner not registered" ); require( idToArena[arenaId].status == ARENA_STARTED, "Arena is not started" ); uint256 upfrontFee = idToArena[arenaId].upfrontFee; address owner = idToArena[arenaId].owner; ngl.transfer(owner, upfrontFee); idToArena[arenaId].numMinersInArena++; idToMinerByArena[arenaId][minerAddress].status = MINER_ENTERED; emit MinerEnteredArena(arenaId, minerAddress, MINER_ENTERED); } function leaveArena(uint256 arenaId, address minerAddress) public nonReentrant onlyAdmin { require( idToMinerByArena[arenaId][minerAddress].status == MINER_ENTERED, "Miner not entered arena" ); delete idToMinerByArena[arenaId][minerAddress]; idToArena[arenaId].numMinersInArena--; emit MinerLeftArena(arenaId, minerAddress, MINER_LEFT); } function bankWithdraw( uint256 arenaId, address minerAddress, uint256 nglAmount ) public nonReentrant onlyAdmin { uint256 miningClaimId = idToArena[arenaId].miningClaimId; uint256 arenaDuration = idToArena[arenaId].duration; uint256 maxMiners = idToMiningClaim[miningClaimId].maxMiners; uint256 maxNglAmountCanWithdraw = arenaDuration * maxMiners * miningSpeed; uint256 totalNglAmount = idToMiningClaim[miningClaimId].nglAmount; require(nglAmount > 0, "Amount must be greater than 0"); require( nglAmount <= maxNglAmountCanWithdraw, "Amount must be less than or equal to max amount" ); require( nglAmount <= totalNglAmount, "Amount must be less than or equal to total amount" ); uint256 decimal = 10**uint256(feeDecimals()); uint256 commissionRate = idToArena[arenaId].commissionRate; uint256 ownerEarn = (nglAmount * commissionRate) / decimal / 100; ngl.transfer(idToArena[arenaId].owner, ownerEarn); ngl.transfer(minerAddress, nglAmount - ownerEarn); emit MinerWithdrawn(arenaId, minerAddress, nglAmount - ownerEarn); } function feeDecimals() public pure returns (uint8) { return 3; } function withdrawNglFromSellingHour() public nonReentrant onlyAdmin { ngl.transfer(msg.sender, nglFromSellingHour); nglFromSellingHour = 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract GoldFeverVesting is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct Reward { address user; uint256 amount; } // period of time in seconds user must be rewarded proportionally uint256 public periodStart; uint256 public periodFinish; uint256 _term; // rewards of users mapping(address => uint256) public rewards; uint256 public totalRewards; // rewards that have been paid to each address mapping(address => uint256) public payouts; IERC20 ngl; event RewardPaid(address indexed user, uint256 reward); event RewardUpdated(address indexed account, uint256 amount); constructor(address ngl_, uint256 periodFinish_) public { ngl = IERC20(ngl_); periodStart = block.timestamp; periodFinish = periodFinish_; _term = periodFinish - periodStart; require(_term > 0, "RewardPayout: term must be greater than 0!"); } /* ========== VIEWS ========== */ function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } /** * @dev returns total amount has been rewarded to the user to the current time */ function earned(address account) public view returns (uint256) { return rewards[account].mul(lastTimeRewardApplicable() - periodStart).div( _term ); } /* ========== MUTATIVE FUNCTIONS ========== */ function setPeriodFinish(uint256 periodFinish_) external onlyOwner { periodFinish = periodFinish_; _term = periodFinish.sub(periodStart); require(_term > 0, "RewardList: term must be greater than 0!"); } function addUsersRewards(Reward[] memory rewards_) public onlyOwner { for (uint256 i = 0; i < rewards_.length; i++) { Reward memory r = rewards_[i]; totalRewards = totalRewards.add(r.amount).sub(rewards[r.user]); rewards[r.user] = r.amount; } } function emergencyAssetWithdrawal(address asset) external onlyOwner { IERC20 token = IERC20(asset); token.safeTransfer(Ownable.owner(), token.balanceOf(address(this))); } /** * @dev calculates total amounts must be rewarded and transfers to the address */ function getReward() public { uint256 _earned = earned(msg.sender); require( _earned <= rewards[msg.sender], "RewardPayout: earned is more than reward!" ); require( _earned > payouts[msg.sender], "RewardPayout: earned is less or equal to already paid!" ); uint256 reward = _earned.sub(payouts[msg.sender]); if (reward > 0) { totalRewards = totalRewards.sub(reward); payouts[msg.sender] = _earned; ngl.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function getClaimAbleReward(address account) public view returns (uint256) { uint256 _earned = earned(account); return _earned.sub(payouts[account]); } function getTotalRewards(address account) public view returns (uint256) { return rewards[account]; } function getClaimedReward(address account) public view returns (uint256) { return payouts[account]; } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {AccessControlMixin} from "@maticnetwork/pos-portal/contracts/common/AccessControlMixin.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract GoldFeverNativeGoldRoot is ERC20, AccessControlMixin { uint256 private immutable _creationTimestamp; uint256 private _totalMinted; mapping(uint256 => uint256) private _yearTotalSupply; mapping(uint256 => uint256) private _yearMinted; constructor( address admin, uint256 totalSupply ) public ERC20("Gold Fever Native Gold", "NGL") { _setupContractId("GoldFeverNativeGoldRoot "); _setupRole(DEFAULT_ADMIN_ROLE, admin); _creationTimestamp = block.timestamp; _mint(admin, totalSupply); _totalMinted = totalSupply; } /** * @param user user for whom tokens are being minted * @param amount amount of token to mint */ function mint(address user, uint256 amount) public only(DEFAULT_ADMIN_ROLE) { require(block.timestamp - _creationTimestamp >= 2 * 365 days); uint256 year = ((block.timestamp - _creationTimestamp) - 2 * 365 days) / 365 days; if (_yearTotalSupply[year] == 0) { _yearTotalSupply[year] = _totalMinted; } require( amount <= ((_yearTotalSupply[year] * 30) / 100) - _yearMinted[year] ); _yearMinted[year] += amount; _totalMinted += amount; _mint(user, amount); } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; contract GoldFeverMarket is IERC721Receiver, ERC721Holder, ReentrancyGuard { bytes32 public constant STATUS_CREATED = keccak256("STATUS_CREATED"); bytes32 public constant STATUS_SOLD = keccak256("STATUS_SOLD"); bytes32 public constant STATUS_CANCELED = keccak256("STATUS_CANCELED"); uint256 public constant build = 3; using Counters for Counters.Counter; Counters.Counter private _listingIds; IERC20 ngl; constructor(address ngl_) public { ngl = IERC20(ngl_); } struct Listing { uint256 listingId; address nftContract; uint256 tokenId; address seller; uint256 price; bytes32 status; } mapping(uint256 => Listing) public idToListing; event ListingCreated( uint256 indexed listingId, address nftContract, uint256 tokenId, address seller, uint256 price ); event ListingCanceled(uint256 indexed listingId); event ListingSold(uint256 indexed listingId, address indexed buyer); function createListing( address nftContract, uint256 tokenId, uint256 price ) public nonReentrant { require(price > 0, "Price must be at least 1 wei"); _listingIds.increment(); uint256 listingId = _listingIds.current(); idToListing[listingId] = Listing( listingId, nftContract, tokenId, msg.sender, price, STATUS_CREATED ); IERC721(nftContract).safeTransferFrom( msg.sender, address(this), tokenId ); emit ListingCreated(listingId, nftContract, tokenId, msg.sender, price); } function cancelListing(uint256 listingId) public nonReentrant { require(idToListing[listingId].seller == msg.sender, "Not seller"); require( idToListing[listingId].status == STATUS_CREATED, "Item is not for sale" ); address seller = idToListing[listingId].seller; uint256 tokenId = idToListing[listingId].tokenId; address nftContract = idToListing[listingId].nftContract; IERC721(nftContract).safeTransferFrom(address(this), seller, tokenId); idToListing[listingId].status = STATUS_CANCELED; emit ListingCanceled(listingId); } function buyListing(uint256 listingId) public nonReentrant { require( idToListing[listingId].status == STATUS_CREATED, "Item is not for sale" ); uint256 price = idToListing[listingId].price; address seller = idToListing[listingId].seller; uint256 tokenId = idToListing[listingId].tokenId; address nftContract = idToListing[listingId].nftContract; ngl.transferFrom(msg.sender, seller, price); IERC721(nftContract).safeTransferFrom( address(this), msg.sender, tokenId ); idToListing[listingId].status = STATUS_SOLD; emit ListingSold(listingId, msg.sender); } } //"SPDX-License-Identifier: UNLICENSED" pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; contract GoldFeverLeasing is ReentrancyGuard, IERC721Receiver, ERC721Holder { bytes32 public constant STATUS_CREATED = keccak256("STATUS_CREATED"); bytes32 public constant STATUS_CANCELED = keccak256("STATUS_CANCELED"); bytes32 public constant STATUS_RENT = keccak256("STATUS_RENT"); bytes32 public constant STATUS_FINISHED = keccak256("STATUS_FINISHED"); uint256 public constant build = 3; using Counters for Counters.Counter; Counters.Counter private _leaseIds; IERC20 ngl; constructor(address ngl_) public { ngl = IERC20(ngl_); } struct Lease { uint256 leaseId; address nftContract; uint256 tokenId; address owner; uint256 price; bytes32 status; uint256 duration; } mapping(uint256 => Lease) public idToLeaseItem; mapping(uint256 => uint256) public idToExpiry; mapping(uint256 => address) public idToRenter; event LeaseCreated( uint256 indexed leaseId, address indexed nftContract, uint256 indexed tokenId, address owner, uint256 price, uint256 duration ); event LeaseCanceled(uint256 indexed leaseId); event LeaseFinished(uint256 indexed leaseId); event LeaseRent( uint256 indexed leaseId, address indexed renter, uint256 expiry ); function createItem( address nftContract, uint256 tokenId, uint256 price, uint256 duration ) public nonReentrant { require(price > 0, "Price must be at least 1 wei"); _leaseIds.increment(); uint256 leaseId = _leaseIds.current(); idToLeaseItem[leaseId] = Lease( leaseId, nftContract, tokenId, msg.sender, price, STATUS_CREATED, duration ); IERC721(nftContract).safeTransferFrom( msg.sender, address(this), tokenId ); emit LeaseCreated( leaseId, nftContract, tokenId, msg.sender, price, duration ); } function cancelItem(uint256 leaseId) public nonReentrant { require(idToLeaseItem[leaseId].owner == msg.sender, "Not leasor"); require( idToLeaseItem[leaseId].status == STATUS_CREATED, "Item is not for sale" ); address owner = idToLeaseItem[leaseId].owner; uint256 tokenId = idToLeaseItem[leaseId].tokenId; address nftContract = idToLeaseItem[leaseId].nftContract; IERC721(nftContract).safeTransferFrom(address(this), owner, tokenId); emit LeaseCanceled(leaseId); idToLeaseItem[leaseId].status = STATUS_CANCELED; } function rentItem(uint256 leaseId) public nonReentrant { require( idToLeaseItem[leaseId].status == STATUS_CREATED, "Item is not for sale" ); uint256 price = idToLeaseItem[leaseId].price; address owner = idToLeaseItem[leaseId].owner; uint256 duration = idToLeaseItem[leaseId].duration; uint256 expiry = block.timestamp + duration; idToRenter[leaseId] = msg.sender; idToExpiry[leaseId] = expiry; ngl.transferFrom(msg.sender, owner, price); emit LeaseRent(leaseId, msg.sender, expiry); idToLeaseItem[leaseId].status = STATUS_RENT; } function finalizeLeaseItem(uint256 leaseId) public nonReentrant { require( idToLeaseItem[leaseId].status == STATUS_RENT, "Item is not on lease" ); require( idToExpiry[leaseId] <= block.timestamp, "Lease is not finished" ); require(idToLeaseItem[leaseId].owner == msg.sender, "Not leaser"); address owner = idToLeaseItem[leaseId].owner; uint256 tokenId = idToLeaseItem[leaseId].tokenId; address nftContract = idToLeaseItem[leaseId].nftContract; IERC721(nftContract).safeTransferFrom(address(this), owner, tokenId); emit LeaseFinished(leaseId); idToLeaseItem[leaseId].status = STATUS_FINISHED; } }
create new hiring with default percentage for both renting and tiketing limit
function createHiring(address nftContract, uint256 buildingItem) public nonReentrant { _hiringIds.increment(); uint256 hiringId = _hiringIds.current(); idToHiring[hiringId] = Hiring( hiringId, nftContract, rentPercentageLimit, ticketPercentageLimit, buildingItem, msg.sender, STATUS_CREATED ); IERC721(nftContract).safeTransferFrom( msg.sender, address(this), buildingItem ); emit HiringCreated( hiringId, nftContract, rentPercentageLimit, ticketPercentageLimit, buildingItem, msg.sender ); }
13,552,316
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IERC677 is IERC20, IERC20Metadata { function transferAndCall(address recipient, uint amount, bytes memory data) external returns (bool success); event Transfer(address indexed from, address indexed to, uint value, bytes data); } interface IERC677Receiver { function onTokenTransfer(address sender, uint value, bytes memory data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; pragma experimental ABIEncoderV2; import "./IERC677.sol"; interface IyVaren { // Event emitted when a new proposal is created event ProposalCreated( uint256 id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); // Event emitted when a vote has been cast on a proposal event VoteCast( address indexed voter, uint256 proposalId, bool support, uint256 votes ); // Event emitted when a proposal has been executed // Success=true if all actions were executed successfully // Success=false if not all actions were executed successfully (executeProposal will not revert) event ProposalExecuted(uint256 id, bool success); // Maximum number of actions that can be included in a proposal function MAX_OPERATIONS() external pure returns (uint256); // https://etherscan.io/token/0x72377f31e30a405282b522d588aebbea202b4f23 function VAREN() external returns (IERC677); struct Proposal { // Address that created the proposal address proposer; // Number of votes in support of the proposal by a particular address mapping(address => uint256) forVotes; // Number of votes against the proposal by a particular address mapping(address => uint256) againstVotes; // Total number of votes in support of the proposal uint256 totalForVotes; // Total number of votes against the proposal uint256 totalAgainstVotes; // Number of votes in support of a proposal required for a quorum to be reached and for a vote to succeed uint256 quorumVotes; // Block at which voting ends: votes must be cast prior to this block uint256 endBlock; // Ordered list of target addresses for calls to be made on address[] targets; // Ordered list of ETH values (i.e. msg.value) to be passed to the calls to be made uint256[] values; // Ordered list of function signatures to be called string[] signatures; // Ordered list of calldata to be passed to each call bytes[] calldatas; // Flag marking whether the proposal has been executed bool executed; } // Number of blocks after staking when the early withdrawal fee stops applying function blocksForNoWithdrawalFee() external view returns (uint256); // Fee for withdrawing before blocksForNoWithdrawalFee have passed, divide by 1,000,000 to get decimal form function earlyWithdrawalFeePercent() external view returns (uint256); function earlyWithdrawalFeeExpiry(address) external view returns (uint256); function treasury() external view returns (address); // Share of early withdrawal fee that goes to treasury (remainder goes to governance), // divide by 1,000,000 to get decimal form function treasuryEarlyWithdrawalFeeShare() external view returns (uint256); // Amount of an address's stake that is locked for voting function voteLockAmount(address) external view returns (uint256); // Block number when an address's vote-locked amount will be unlock function voteLockExpiry(address) external view returns (uint256); function hasActiveProposal(address) external view returns (bool); function proposals(uint256 id) external view returns ( address proposer, uint256 totalForVotes, uint256 totalAgainstVotes, uint256 quorumVotes, uint256 endBlock, bool executed ); // Number of proposals created, used as the id for the next proposal function proposalCount() external view returns (uint256); // Length of voting period in blocks function votingPeriodBlocks() external view returns (uint256); function minVarenForProposal() external view returns (uint256); // Need to divide by 1,000,000 function quorumPercent() external view returns (uint256); // Need to divide by 1,000,000 function voteThresholdPercent() external view returns (uint256); // Number of blocks after voting ends where proposals are allowed to be executed function executionPeriodBlocks() external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 shares) external; function getPricePerFullShare() external view returns (uint256); function getStakeVarenValue(address staker) external view returns (uint256); function propose( address[] calldata targets, uint256[] calldata values, string[] calldata signatures, bytes[] calldata calldatas, string calldata description ) external returns (uint256 id); function vote( uint256 id, bool support, uint256 voteAmount ) external; function executeProposal(uint256 id) external payable; function getVotes(uint256 proposalId, address voter) external view returns (bool support, uint256 voteAmount); function getProposalCalls(uint256 proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ); function setTreasury(address) external; function setTreasuryEarlyWithdrawalFeeShare(uint256) external; function setBlocksForNoWithdrawalFee(uint256) external; function setEarlyWithdrawalFeePercent(uint256) external; function setVotingPeriodBlocks(uint256) external; function setMinVarenForProposal(uint256) external; function setQuorumPercent(uint256) external; function setVoteThresholdPercent(uint256) external; function setExecutionPeriodBlocks(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IyVaren.sol"; import "./interfaces/IERC677.sol"; contract yVaren is IyVaren, IERC677Receiver, ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant override MAX_OPERATIONS = 10; IERC677 public immutable override VAREN; uint256 public override blocksForNoWithdrawalFee; uint256 public override earlyWithdrawalFeePercent = 5000; // 0.5% mapping(address => uint256) public override earlyWithdrawalFeeExpiry; address public override treasury; uint256 public override treasuryEarlyWithdrawalFeeShare = 1000000; // 100% mapping(address => uint256) public override voteLockAmount; mapping(address => uint256) public override voteLockExpiry; mapping(address => bool) public override hasActiveProposal; mapping(uint256 => Proposal) public override proposals; uint256 public override proposalCount; uint256 public override votingPeriodBlocks; uint256 public override minVarenForProposal = 1e17; // 0.1 Varen uint256 public override quorumPercent = 150000; // 15% uint256 public override voteThresholdPercent = 500000; // 50% uint256 public override executionPeriodBlocks; modifier onlyThis() { require(msg.sender == address(this), "yVRN: FORBIDDEN"); _; } constructor( address _varen, address _treasury, uint256 _blocksForNoWithdrawalFee, uint256 _votingPeriodBlocks, uint256 _executionPeriodBlocks ) ERC20("Varen Staking Share", "yVRN") { require( _varen != address(0) && _treasury != address(0), "yVRN: ZERO_ADDRESS" ); VAREN = IERC677(_varen); treasury = _treasury; blocksForNoWithdrawalFee = _blocksForNoWithdrawalFee; votingPeriodBlocks = _votingPeriodBlocks; executionPeriodBlocks = _executionPeriodBlocks; } function stake(uint256 amount) external override nonReentrant { require(amount > 0, "yVRN: ZERO"); require(VAREN.transferFrom(msg.sender, address(this), amount), 'yVRN: transferFrom failed'); _stake(msg.sender, amount); } function _stake(address sender, uint256 amount) internal virtual { uint256 shares = totalSupply() == 0 ? amount : (amount.mul(totalSupply())).div(VAREN.balanceOf(address(this)).sub(amount)); _mint(sender, shares); earlyWithdrawalFeeExpiry[sender] = blocksForNoWithdrawalFee.add( block.number ); } function onTokenTransfer(address sender, uint value, bytes memory) external override nonReentrant { require(value > 0, "yVRN: ZERO"); require(msg.sender == address(VAREN), 'yVRN: access denied'); _stake(sender, value); } function withdraw(uint256 shares) external override nonReentrant { require(shares > 0, "yVRN: ZERO"); _updateVoteExpiry(); require(_checkVoteExpiry(msg.sender, shares), "voteLockExpiry"); uint256 varenAmount = (VAREN.balanceOf(address(this))).mul(shares).div( totalSupply() ); _burn(msg.sender, shares); if (block.number < earlyWithdrawalFeeExpiry[msg.sender]) { uint256 feeAmount = varenAmount.mul(earlyWithdrawalFeePercent) / 1000000; VAREN.transfer( treasury, feeAmount.mul(treasuryEarlyWithdrawalFeeShare) / 1000000 ); varenAmount = varenAmount.sub(feeAmount); } VAREN.transfer(msg.sender, varenAmount); } function getPricePerFullShare() external view override returns (uint256) { return totalSupply() == 0 ? 0 : VAREN.balanceOf(address(this)).mul(1e18).div(totalSupply()); } function getStakeVarenValue(address staker) external view override returns (uint256) { return (VAREN.balanceOf(address(this)).mul(balanceOf(staker))).div( totalSupply() ); } function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public override nonReentrant returns (uint256 id) { require(!hasActiveProposal[msg.sender], "yVRN: HAS_ACTIVE_PROPOSAL"); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "yVRN: PARITY_MISMATCH" ); require(targets.length != 0, "yVRN: NO_ACTIONS"); require(targets.length <= MAX_OPERATIONS, "yVRN: TOO_MANY_ACTIONS"); require( (VAREN.balanceOf(address(this)).mul(balanceOf(msg.sender))).div( totalSupply() ) >= minVarenForProposal, "yVRN: INSUFFICIENT_VAREN_FOR_PROPOSAL" ); uint256 endBlock = votingPeriodBlocks.add(block.number); Proposal storage newProposal = proposals[proposalCount]; newProposal.proposer = msg.sender; newProposal.endBlock = endBlock; newProposal.targets = targets; newProposal.values = values; newProposal.signatures = signatures; newProposal.calldatas = calldatas; newProposal.totalForVotes = 0; newProposal.totalAgainstVotes = 0; newProposal.quorumVotes = VAREN.balanceOf(address(this)).mul(quorumPercent) / 1000000; newProposal.executed = false; hasActiveProposal[msg.sender] = true; proposalCount = proposalCount.add(1); emit ProposalCreated( id, msg.sender, targets, values, signatures, calldatas, block.number, endBlock, description ); } function _checkVoteExpiry(address _sender, uint256 _shares) private view returns (bool) { // ????? return _shares <= balanceOf(_sender).sub(voteLockAmount[_sender]); } function _updateVoteExpiry() private { if (block.number >= voteLockExpiry[msg.sender]) { voteLockExpiry[msg.sender] = 0; voteLockAmount[msg.sender] = 0; } } function vote( uint256 id, bool support, uint256 voteAmount ) external override nonReentrant { Proposal storage proposal = proposals[id]; require(proposal.proposer != address(0), "yVRN: INVALID_PROPOSAL_ID"); require(block.number < proposal.endBlock, "yVRN: VOTING_ENDED"); require(voteAmount > 0, "yVRN: ZERO"); require( voteAmount <= balanceOf(msg.sender), "yVRN: INSUFFICIENT_BALANCE" ); _updateVoteExpiry(); require( voteAmount >= voteLockAmount[msg.sender], "yVRN: SMALLER_VOTE" ); if ( (support && voteAmount == proposal.forVotes[msg.sender]) || (!support && voteAmount == proposal.againstVotes[msg.sender]) ) { revert("yVRN: SAME_VOTE"); } if (voteAmount > voteLockAmount[msg.sender]) { voteLockAmount[msg.sender] = voteAmount; } voteLockExpiry[msg.sender] = proposal.endBlock > voteLockExpiry[msg.sender] ? proposal.endBlock : voteLockExpiry[msg.sender]; if (support) { proposal.totalForVotes = proposal.totalForVotes.add(voteAmount).sub( proposal.forVotes[msg.sender] ); proposal.forVotes[msg.sender] = voteAmount; // remove opposite votes proposal.totalAgainstVotes = proposal.totalAgainstVotes.sub( proposal.againstVotes[msg.sender] ); proposal.againstVotes[msg.sender] = 0; } else { proposal.totalAgainstVotes = proposal .totalAgainstVotes .add(voteAmount) .sub(proposal.againstVotes[msg.sender]); proposal.againstVotes[msg.sender] = voteAmount; // remove opposite votes proposal.totalForVotes = proposal.totalForVotes.sub( proposal.forVotes[msg.sender] ); proposal.forVotes[msg.sender] = 0; } emit VoteCast(msg.sender, id, support, voteAmount); } function executeProposal(uint256 id) external payable override nonReentrant { Proposal storage proposal = proposals[id]; require(!proposal.executed, "yVRN: PROPOSAL_ALREADY_EXECUTED"); { // check if proposal passed require( proposal.proposer != address(0), "yVRN: INVALID_PROPOSAL_ID" ); require( block.number >= proposal.endBlock, "yVRN: PROPOSAL_IN_VOTING" ); hasActiveProposal[proposal.proposer] = false; uint256 totalVotes = proposal.totalForVotes.add( proposal.totalAgainstVotes ); if ( totalVotes < proposal.quorumVotes || proposal.totalForVotes < totalVotes.mul(voteThresholdPercent) / 1000000 || block.number >= proposal.endBlock.add(executionPeriodBlocks) // execution period ended ) { return; } } bool success = true; uint256 remainingValue = msg.value; for (uint256 i = 0; i < proposal.targets.length; i++) { if (proposal.values[i] > 0) { require( remainingValue >= proposal.values[i], "yVRN: INSUFFICIENT_ETH" ); remainingValue = remainingValue - proposal.values[i]; } (success, ) = proposal.targets[i].call{value: proposal.values[i]}( abi.encodePacked( bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i] ) ); if (!success) break; } proposal.executed = true; emit ProposalExecuted(id, success); } function getVotes(uint256 proposalId, address voter) external view override returns (bool support, uint256 voteAmount) { support = proposals[proposalId].forVotes[voter] > 0; voteAmount = support ? proposals[proposalId].forVotes[voter] : proposals[proposalId].againstVotes[voter]; } function getProposalCalls(uint256 proposalId) external view override returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { targets = proposals[proposalId].targets; values = proposals[proposalId].values; signatures = proposals[proposalId].signatures; calldatas = proposals[proposalId].calldatas; } // SETTERS function setTreasury(address _treasury) external override onlyThis { treasury = _treasury; } function setTreasuryEarlyWithdrawalFeeShare( uint256 _treasuryEarlyWithdrawalFeeShare ) external override onlyThis { require(_treasuryEarlyWithdrawalFeeShare <= 1000000); treasuryEarlyWithdrawalFeeShare = _treasuryEarlyWithdrawalFeeShare; } function setBlocksForNoWithdrawalFee(uint256 _blocksForNoWithdrawalFee) external override onlyThis { // max 60 days require(_blocksForNoWithdrawalFee <= 345600); blocksForNoWithdrawalFee = _blocksForNoWithdrawalFee; } function setEarlyWithdrawalFeePercent(uint256 _earlyWithdrawalFeePercent) external override onlyThis { // max 100% require(_earlyWithdrawalFeePercent <= 1000000); earlyWithdrawalFeePercent = _earlyWithdrawalFeePercent; } function setVotingPeriodBlocks(uint256 _votingPeriodBlocks) external override onlyThis { // min 8 hours, max 2 weeks require(_votingPeriodBlocks >= 1920 && _votingPeriodBlocks <= 80640); votingPeriodBlocks = _votingPeriodBlocks; } function setMinVarenForProposal(uint256 _minVarenForProposal) external override onlyThis { // min 0.01 Varen, max 520 Varen (1% of total supply) require( _minVarenForProposal >= 1e16 && _minVarenForProposal <= 520 * (1e18) ); minVarenForProposal = _minVarenForProposal; } function setQuorumPercent(uint256 _quorumPercent) external override onlyThis { // min 10%, max 33% require(_quorumPercent >= 100000 && _quorumPercent <= 330000); quorumPercent = _quorumPercent; } function setVoteThresholdPercent(uint256 _voteThresholdPercent) external override onlyThis { // min 50%, max 66% require( _voteThresholdPercent >= 500000 && _voteThresholdPercent <= 660000 ); voteThresholdPercent = _voteThresholdPercent; } function setExecutionPeriodBlocks(uint256 _executionPeriodBlocks) external override onlyThis { // min 8 hours, max 30 days require( _executionPeriodBlocks >= 1920 && _executionPeriodBlocks <= 172800 ); executionPeriodBlocks = _executionPeriodBlocks; } // ERC20 functions (overridden to add modifiers) function transfer(address recipient, uint256 amount) public override nonReentrant returns (bool) { _updateVoteExpiry(); require(_checkVoteExpiry(msg.sender, amount), "voteLockExpiry"); super.transfer(recipient, amount); } function approve(address spender, uint256 amount) public override nonReentrant returns (bool) { super.approve(spender, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override nonReentrant returns (bool) { _updateVoteExpiry(); require(_checkVoteExpiry(sender, amount), "voteLockExpiry"); super.transferFrom(sender, recipient, amount); } function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { super.decreaseAllowance(spender, subtractedValue); } function decimals() public view virtual override returns (uint8) { return VAREN.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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 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, 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 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 "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
min 8 hours, max 30 days
function setExecutionPeriodBlocks(uint256 _executionPeriodBlocks) external override onlyThis { require( _executionPeriodBlocks >= 1920 && _executionPeriodBlocks <= 172800 ); executionPeriodBlocks = _executionPeriodBlocks; }
14,059,755
contract RobinHoodPonzi { // Robin Hood Ponzi // // Payout from 1 Finney to 10 Finney 300% // Payout from 10 Finney to 100 Finney 200% // Payout from 100 Finney to 1 Ether 180% // Payout from 1 Ether to 10 Ether 150% // Payout from 10 Ether to 100 Ether 125% // Payout from 100 Ether to 500 Ether 110% // Payout from 500 Ether to 1000 Ether 105% struct Participant { address etherAddress; uint payin; uint payout; } Participant[] private participants; uint private payoutIdx = 0; uint private collectedFees; uint private balance = 0; uint private fee = 1; // 1% uint private factor = 200; address private owner; // simple single-sig function modifier modifier onlyowner { if (msg.sender == owner) _ } // this function is executed at initialization and sets the owner of the contract function RobinHoodPonzi() { owner = msg.sender; } // fallback function - simple transactions trigger this function() { enter(); } function enter() private { if (msg.value < 1 finney) { msg.sender.send(msg.value); return; } uint amount; if (msg.value > 1000 ether) { msg.sender.send(msg.value - 1000 ether); amount = 1000 ether; } else { amount = msg.value; } // add a new participant to array uint idx = participants.length; participants.length += 1; participants[idx].etherAddress = msg.sender; participants[idx].payin = amount; if(amount>= 1 finney){factor=300;} if(amount>= 10 finney){factor=200;} if(amount>= 100 finney){factor=180;} if(amount>= 1 ether) {factor=150;} if(amount>= 10 ether) {factor=125;} if(amount>= 100 ether) {factor=110;} if(amount>= 500 ether) {factor=105;} participants[idx].payout = amount *factor/100; // collect fees and update contract balance collectedFees += amount *fee/100; balance += amount - amount *fee/100; // while there are enough ether on the balance we can pay out to an earlier participant while (balance > participants[payoutIdx].payout) { uint transactionAmount = participants[payoutIdx].payout; participants[payoutIdx].etherAddress.send(transactionAmount); balance -= transactionAmount; payoutIdx += 1; } if (collectedFees >1 ether) { owner.send(collectedFees); collectedFees = 0; } } // function collectFees() onlyowner { // if (collectedFees == 0) return; // owner.send(collectedFees); // collectedFees = 0; // } // function setOwner(address _owner) onlyowner { // owner = _owner; // } function Infos() constant returns (address Owner, uint BalanceInFinney, uint Participants, uint PayOutIndex,uint NextPayout, string info) { Owner=owner; BalanceInFinney = balance / 1 finney; PayOutIndex=payoutIdx; Participants=participants.length; NextPayout =participants[payoutIdx].payout / 1 finney; info = 'All amounts in Finney (1 Ether = 1000 Finney)'; } function participantDetails(uint nr) constant returns (address Address, uint PayinInFinney, uint PayoutInFinney, string PaidOut) { PaidOut='N.A.'; Address=0; PayinInFinney=0; PayoutInFinney=0; if (nr < participants.length) { Address = participants[nr].etherAddress; PayinInFinney = participants[nr].payin / 1 finney; PayoutInFinney= participants[nr].payout / 1 finney; PaidOut='no'; if (nr<payoutIdx){PaidOut='yes';} } } }
this function is executed at initialization and sets the owner of the contract
function RobinHoodPonzi() { owner = msg.sender; }
5,528,610
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
Reads the bytes31 at `rdPtr` in returndata.
function readBytes31( ReturndataPointer rdPtr ) internal pure returns (bytes31 value) { assembly { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
4,300,405
// 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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 () { 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 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 { 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal 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"); _balances[account] = accountBalance - amount; _totalSupply -= 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 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 { } } //##################################################### //# START AUDIT HERE, VANILLA OPENZEPPELIN CODE ABOVE # //##################################################### contract LockedQARK is ERC20, Ownable { // THE CONTRACT ADDRESS OF QARK IERC20 private _qark; // THIS REPRESENTS AN OFFER'S PROPERTIES GIVEN TO A BUYER struct Offer { uint256 tokenAmount; // HOW MANY TOKENS ARE OFFERED FOR SALE uint256 purchasePrice; // HOW MUCH WEI TO SEND TO CLAIM THE OFFERED TOKENS uint32 claimableUntil; // THE OFFER EXPIRES AT THIS TIME (UNIX TIMESTAMP) uint32 lockedUntil; // THE PURCHASED TOKENS CAN BE WITHDRAWN AFTER THIS TIME (UNIX) } // THIS MAPS THE BUYER ADDRESSES TO THE OFFERS GIVEN TO THEM mapping (address => Offer) public offers; // INITIALIZE AN ERC20 TOKEN BASED ON THE OPENZEPPELIN VERSION constructor() ERC20("Locked QARK", "LQARK") { } // PERMIT OWNER TO SET QARK CONTRACT ADDRESS function setQarkAddr(IERC20 qark_) public onlyOwner { // CONTRACT ADDRESS CAN ONLY BE SET ONCE require(_qark == IERC20(address(0)), "QARK address can be set once!"); _qark = qark_; } // MAKE AN OFFER TO A BUYER function makeOffer(address _toBuyer, uint256 _tokenAmount, uint256 _atPrice, uint32 _claimableUntil, uint32 _lockedUntil) public onlyOwner { // IF BUYER HAS AN OFFER ALREADY, MAKE SURE IT IS NOT CLAIMED YET if(offers[_toBuyer].purchasePrice > 0){ require(offers[_toBuyer].tokenAmount > 0 && offers[_toBuyer].claimableUntil > 0, "Buyer already claimed the offer!"); } // MAKE SURE THAT THIS CONTRACT HAS ENOUGH QARK TOKENS AS DEPOSIT TO FULFILL THE OFFER require(_qark.balanceOf(address(this)) - totalSupply() >= _tokenAmount, "Not enough QARK deposit provided to make offer!"); // IF ABOVE CONDITIONS WERE MET, REGISTER OFFER offers[_toBuyer] = Offer({ tokenAmount: _tokenAmount, purchasePrice: _atPrice, claimableUntil: _claimableUntil, lockedUntil: _lockedUntil }); // MINT THE LOCKED TOKENS TO THE SELLER WHICH WILL BE TRANSFERRED TO BUYER UPON CLAIMING THE OFFER _mint(owner(), _tokenAmount); } // NON-CLAIMED OFFERS CAN BE CANCELLED function cancelOffer(address _ofBuyer) public onlyOwner { // ONLY EXISTING, NON-CLAIMED OFFERS CAN BE CANCELLED (tokenAmount FIELD IS SET TO ZERO UPON CLAIM) require(offers[_ofBuyer].tokenAmount > 0, "Buyer does not have an offer or claimed it already!"); // TRANSFER THE OFFERED QARK AMOUNT BACK TO CONTRACT OWNER _qark.transfer(owner(), offers[_ofBuyer].tokenAmount); // BURN THE LOCKED TOKENS _burn(owner(), offers[_ofBuyer].tokenAmount); // REMOVE BUYER'S OFFER FROM MAPPING delete offers[_ofBuyer]; } // THE RECEIVE FUNCTION ACCEPTS PAYMENT FROM A BUYER TO CLAIM THEIR OFFER receive() external payable { // REQUIRE THAT BUYER DIDN'T SEND A ZERO-ETH TX require(msg.value > 0, "No ETH received!"); // AND HAS SENT CORRECT PURCHASE PRICE require(offers[_msgSender()].purchasePrice == msg.value, "Incorrect purchase price sent"); // OFFER MUST BE STILL CLAIMABLE require(offers[_msgSender()].claimableUntil > block.timestamp, "Offer expired!"); // PURCHASE SUCCESSFUL REGISTER BUYER'S BALANCE _transfer(owner(), _msgSender(), offers[_msgSender()].tokenAmount); // UPDATE OFFER offers[_msgSender()].claimableUntil = 0; offers[_msgSender()].tokenAmount = 0; } // SELLER CAN CLAIM THE AMOUNT PAID BY THE BUYER function claimPurchasePrice(address payable _beneficiary) public onlyOwner { _beneficiary.transfer(address(this).balance); } // OVERRIDE OPENZEPPELIN'S ERC20 transfer() METHOD function transfer(address recipient, uint256 amount) public virtual override returns (bool) { // REQUIRE THAT THE TRANSFERRED AMOUNT IS LESS OR EQUALS THE LOCKED AMOUNT require(amount <= balanceOf(_msgSender()), "Not enough tokens to transfer!"); // REQUIRE THAT SENDER HAS A CLAIMED OFFER, AND LOCK TIME IS OVER require(offers[_msgSender()].lockedUntil < block.timestamp, "Tokens are still locked!"); // BURN THE TRANSFERRED LOCKED TOKENS _burn(_msgSender(), amount); // TRANSFER THE REAL QARKS FROM THIS CONTRACT TO RECIPIENT return _qark.transfer(recipient, amount); } }
MAKE AN OFFER TO A BUYER IF BUYER HAS AN OFFER ALREADY, MAKE SURE IT IS NOT CLAIMED YET IF ABOVE CONDITIONS WERE MET, REGISTER OFFER
function makeOffer(address _toBuyer, uint256 _tokenAmount, uint256 _atPrice, uint32 _claimableUntil, uint32 _lockedUntil) public onlyOwner { if(offers[_toBuyer].purchasePrice > 0){ require(offers[_toBuyer].tokenAmount > 0 && offers[_toBuyer].claimableUntil > 0, "Buyer already claimed the offer!"); } offers[_toBuyer] = Offer({ tokenAmount: _tokenAmount, purchasePrice: _atPrice, claimableUntil: _claimableUntil, lockedUntil: _lockedUntil }); }
14,828,522
// contracts/mocks/TestStrategy.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../mocks/interfaces/IMMintableERC20.sol"; contract TestStrategy is Ownable { using SafeERC20 for IERC20; address public balleMaster; address public depositToken; address public govAddress; uint256 public depositTotal = 0; uint256 public sharesTotal = 0; // Not needed variables, only for this testing strategy to work bool public paused = false; bool public retired = false; /** * @dev Implementation of strategy for testing. * The strategy will "mine" TEST_LP tokens to simulate a working farm for testing purpouses. * It's very simple to facilitate testing. Every time it's harvested, it will add 1% to TEST_LP balance. * Will be improved to test fee distribution, etc. */ constructor(address _balleMaster, address _depositToken) { balleMaster = _balleMaster; depositToken = _depositToken; govAddress = msg.sender; transferOwnership(_balleMaster); } /** * @dev Function to harvest benefits and implement strategy steps. * It will increase deposited tokens by 1% every time it's called. */ function harvest() external { require(msg.sender == govAddress, "!gov"); if (depositTotal == 0) { return; } uint256 earned = IERC20(depositToken).balanceOf(address(this)) / 100; // autocompounding strategy depositTotal = depositTotal + earned; IMMintableERC20(depositToken).mint(address(this), earned); } /** * @dev Function to transfer tokens BalleMaster -> strategy and put it to work. * It will leave the tokens here, strategy only for testing purpouses. */ function deposit(address _user, uint256 _amount) public onlyOwner returns (uint256) { require(_user != address(0), "!user"); require(_amount > 0, "!amount"); IERC20(depositToken).safeTransferFrom(address(msg.sender), address(this), _amount); uint256 sharesAdded = _amount; if (depositTotal > 0) { sharesAdded = (_amount * sharesTotal) / depositTotal; } sharesTotal = sharesTotal + sharesAdded; depositTotal = depositTotal + _amount; return sharesAdded; } /** * @dev Function to transfer tokens strategy -> BalleMaster. */ function withdraw(address _user, uint256 _amount) public onlyOwner returns (uint256, uint256) { require(_user != address(0), "!user"); require(_amount > 0, "!amount"); uint256 depositAmt = IERC20(depositToken).balanceOf(address(this)); if (_amount > depositAmt) { _amount = depositAmt; } if (depositTotal < _amount) { _amount = depositTotal; } uint256 sharesRemoved = (_amount * sharesTotal) / depositTotal; if (sharesRemoved > sharesTotal) { sharesRemoved = sharesTotal; } sharesTotal = sharesTotal - sharesRemoved; depositTotal = depositTotal - _amount; IERC20(depositToken).safeTransfer(msg.sender, _amount); return (sharesRemoved, _amount); } function upgradeTo(address _strat) external onlyOwner returns ( uint256, uint256, uint256 ) { require(_strat != address(0), "!strat"); // A real strategy would prepare to upgrade (remove tokens from farm) // Set allowance for new strat contract uint256 depositAmt = IERC20(depositToken).balanceOf(address(this)); IERC20(depositToken).safeIncreaseAllowance(_strat, depositAmt); return (sharesTotal, depositAmt, 0); } function upgradeFrom( address _strat, uint256 _sharesTotal, uint256 _depositAmt, uint256 _earnedAmt ) external onlyOwner { require(_strat != address(0), "!strat"); // A real strategy would prepare to upgrade (remove tokens from farm) // Transfer tokens IERC20(depositToken).safeTransferFrom(_strat, address(this), _depositAmt); depositTotal = IERC20(depositToken).balanceOf(address(this)); _earnedAmt = 0; // Test strategy does not have earnedToken, this is only to use the argument sharesTotal = _sharesTotal; // A real strategy would finish to upgrade (send tokens to farm) } function pause() external onlyOwner { // A real strategy would enter pause mode: // - Remove tokens from farm // - Clear allowances of third party contracts // Updating state, not needed on a real one paused = true; } function unpause() external onlyOwner { // A real strategy would enter active mode: // - Set allowances to third party contracts // - Send tokens to farm // Updating state, not needed on a real one paused = false; } function panic() external onlyOwner { // A real strategy would panic exit farm: // - Remove tokens from farm with emergencyWithdraw // - Clear allowances of third party contracts // Updating state, not needed on a real one paused = true; } function retire() external onlyOwner { // A real strategy would enter retired mode: // - Remove tokens from farm // - Clear allowances of third party contracts // Updating state, not needed on a real one paused = true; } function setGov(address _govAddress) public { require(msg.sender == govAddress, "!gov"); govAddress = _govAddress; } function inCaseTokensGetStuck( address _token, uint256 _amount, address _to ) public { require(msg.sender == govAddress, "!gov"); require(_token != depositToken, "!safe"); IERC20(_token).safeTransfer(_to, _amount); } }
A real strategy would prepare to upgrade (remove tokens from farm) Transfer tokens A real strategy would finish to upgrade (send tokens to farm)
function upgradeFrom( address _strat, uint256 _sharesTotal, uint256 _depositAmt, uint256 _earnedAmt ) external onlyOwner { require(_strat != address(0), "!strat"); IERC20(depositToken).safeTransferFrom(_strat, address(this), _depositAmt); depositTotal = IERC20(depositToken).balanceOf(address(this)); sharesTotal = _sharesTotal; }
12,776,738
/** *Submitted for verification at Etherscan.io on 2022-02-05 */ // SPDX-License-Identifier: MIT // # Runes.sol // This is a ERC-20 token that is ONLY meant to be used as a extension for the Mysterious World NFT Project // The only use case for this token is to be used to interact with The Mysterious World. // This token has no monetary value associated to it. // Read more at https://www.themysterious.world/utility pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override 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); 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); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); } 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); } 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); } 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 _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } } // The interface is used so we can get the balance of each holder interface TheMysteriousWorld { function balanceOf(address inhabitant) external view returns(uint256); function ritualWallet() external view returns(address); } /* * 888d888888 88888888b. .d88b. .d8888b * 888P" 888 888888 "88bd8P Y8b88K * 888 888 888888 88888888888"Y8888b. * 888 Y88b 888888 888Y8b. X88 * 888 "Y88888888 888 "Y8888 88888P' */ contract Runes is ERC20, Ownable { TheMysteriousWorld public mysteriousworld; uint256 public deployedStamp = 0; // this is used to calculate the amount of $RUNES a user has from the current block.timestamp uint256 public runesPerDay = 10 ether; // this ends up being 25 $RUNES per day. this might change in the future depending on how the collection grows overtime. bool public allowRuneCollecting = false; // this lets you claim your $RUNES from the contract to the wallet mapping(address => uint256) public runesObtained; // this tracks how much $RUNES each address earned mapping(address => uint256) public lastTimeCollectedRunes; // this sets the block.timestamp to the address so it subtracts the timestamp from the pending rewards mapping(address => bool) public contractWallets; // these are used to interact with the burning mechanisms of the contract - these will only be set to contracts related to The Mysterious World constructor() ERC20("Runes", "Runes") { deployedStamp = block.timestamp; } /* * # onlyContractWallets * blocks anyone from accessing it but contract wallets */ modifier onlyContractWallets() { require(contractWallets[msg.sender], "You angered the gods!"); _; } /* * # onlyWhenCollectingIsEnabled * blocks anyone from accessing functions that require allowRuneCollecting */ modifier onlyWhenCollectingIsEnabled() { require(allowRuneCollecting, "You angered the gods!"); _; } /* * # setRuneCollecting * enables or disables users to withdraw their runes - should only be called once unless the gods intended otherwise */ function setRuneCollecting(bool newState) public payable onlyOwner { allowRuneCollecting = newState; } /* * # setDeployedStamp * sets the timestamp for when the $RUNES should start being generated */ function setDeployedStamp(bool forced, uint256 stamp) public payable onlyOwner { if (forced) { deployedStamp = stamp; } else { deployedStamp = block.timestamp; } } /* * # setRunesPerDay * incase we want to change the amount gained per day, the gods can set it here */ function setRunesPerDay(uint256 newRunesPerDay) public payable onlyOwner { runesPerDay = newRunesPerDay; } /* * # setMysteriousWorldContract * sets the address to the deployed Mysterious World contract */ function setMysteriousWorldContract(address contractAddress) public payable onlyOwner { mysteriousworld = TheMysteriousWorld(contractAddress); } /* * # setContractWallets * enables or disables a contract wallet from interacting with the burn mechanics of the contract */ function setContractWallets(address contractAddress, bool newState) public payable onlyOwner { contractWallets[contractAddress] = newState; } /* * # getPendingRunes * calculates the runes a inhabitant has from the last time they claimed and the deployedStamp time */ function getPendingRunes(address inhabitant) internal view returns(uint256) { uint256 sumOfRunes = mysteriousworld.balanceOf(inhabitant) * runesPerDay; if (lastTimeCollectedRunes[inhabitant] >= deployedStamp) { return sumOfRunes * ((block.timestamp - lastTimeCollectedRunes[inhabitant])) / 86400; } else { return sumOfRunes * ((block.timestamp - deployedStamp)) / 86400; } } /* * # getUnclaimedRunes * returns the total amount of unclaimed runes a wallet has */ function getUnclaimedRunes(address inhabitant) external view returns(uint256) { return getPendingRunes(inhabitant); } /* * # getTotalRunes * returns the runesObtained and getPendingRunes for the inhabitant passed */ function getTotalRunes(address inhabitant) external view returns(uint256) { return runesObtained[inhabitant] + getPendingRunes(inhabitant); } /* * # burn * removes the withdrawn $RUNES from the wallet provided for the amount provided */ function burn(address inhabitant, uint256 cost) external payable onlyContractWallets { _burn(inhabitant, cost); } /* * # claimRunes * takes the pending $RUNES and puts it into your wallet... you earned these, the gods aren't angry */ function claimRunes() external payable onlyWhenCollectingIsEnabled { _mint(msg.sender, runesObtained[msg.sender] + getPendingRunes(msg.sender)); runesObtained[msg.sender] = 0; lastTimeCollectedRunes[msg.sender] = block.timestamp; } /* * # updateRunes * updates the pending balance for both of the wallets associated to the transfer so they don't lose the $RUNES generated */ function updateRunes(address from, address to) external onlyContractWallets { if (from != address(0) && from != mysteriousworld.ritualWallet()) { runesObtained[from] += getPendingRunes(from); lastTimeCollectedRunes[from] = block.timestamp; } if (to != address(0) && to != mysteriousworld.ritualWallet()) { runesObtained[to] += getPendingRunes(to); lastTimeCollectedRunes[to] = block.timestamp; } } }
getUnclaimedRunes returns the total amount of unclaimed runes a wallet has/
function getUnclaimedRunes(address inhabitant) external view returns(uint256) { return getPendingRunes(inhabitant); }
7,739,791
./full_match/1/0x341AFE99daB6566E4bFe9fAcB6cf258Aa5619912/sources/contracts/rebase_engine/RebaseEngine.sol
This method calculates the user reward generated till now based on current accumulated pool weight and user staked amount/
function _rebaseStake(address user) internal { Stake memory stake = database.getUserStake(user); uint currentAccumulatedWeight = database.getAccumulatedPoolWeight(); uint lastAccumulatedWeight = stake.lastStakingAccumulatedWeight; uint256 distributedAmount = ((currentAccumulatedWeight - lastAccumulatedWeight) * (stake.amount)) / EIGHT_DECIMALS; database.updateUserStake(user, distributedAmount, database.getDemandFactorLastest().value, currentAccumulatedWeight); }
17,038,662
/** *Submitted for verification at Etherscan.io on 2021-09-28 */ /** *Submitted for verification at Etherscan.io on 2021-09-28 *By @Thrasher66099 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol /** * @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 /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/CryptoKaijus.sol /** * @title CryptoKaiju contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract CryptoKaijus is ERC721, Ownable { using SafeMath for uint256; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public mintPrice; uint256 public maxToMint; uint256 public presaleSupply; uint256 public MAX_CRYPTO_KAIJUS_SUPPLY; uint256 public REVEAL_TIMESTAMP; string public prerevealURI; string public PROVENANCE_HASH; bool public saleIsActive; bool public presaleEnded; address wallet1; address wallet2; constructor() ERC721("Kaiju Kombat", "KAIJUKOM") { MAX_CRYPTO_KAIJUS_SUPPLY = 10000; REVEAL_TIMESTAMP = block.timestamp + (86400 * 3); mintPrice = 78000000000000000; // 0.078 ETH presaleSupply = 500; maxToMint = 10; saleIsActive = false; presaleEnded = false; wallet1 = 0xB4Ef935Ed1c0667aEA2c6b2c838e71071aD046b9; wallet2 = 0x569f6323107b7800950F8c5777684425e5C4bC61; } /** * Get the array of token for owner. */ function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 index; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } /** * MUST TURN INTO LIBRARY BEFORE LIVE DEPLOYMENT!!!!! */ function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** * Check if certain token id is exists. */ function exists(uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } /** * Set price to mint a Crypto Ultra. */ function setMintPrice(uint256 _price) external onlyOwner { mintPrice = _price; } /** * Set maximum count to mint per once. */ function setMaxToMint(uint256 _maxValue) external onlyOwner { maxToMint = _maxValue; } /** * Mint Crypto Kaijus by owner */ function reserveCryptoKaijus(address _to, uint256 _numberOfTokens) external onlyOwner { require(_to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; //Mint address, 0 on first mint //Supply is 1 so mint tokenId = 1 (which is the 2nd token) for (i = 0; i < _numberOfTokens; i++) { _safeMint(_to, supply + i); } } /** * Set reveal timestamp when finished the sale. */ function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner { REVEAL_TIMESTAMP = _revealTimeStamp; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory _provenanceHash) external onlyOwner { PROVENANCE_HASH = _provenanceHash; } function setBaseURI(string memory baseURI) external onlyOwner { _setBaseURI(baseURI); } /** * External function to set the prereveal URI for all token IDs. * This is the URI that is shown on each token until the REVEAL_TIMESTAMP * is surpassed. */ function setPrerevealURI(string memory prerevealURI_) external onlyOwner { prerevealURI = prerevealURI_; } /** * Returns the proper tokenURI only after the startingIndex is finalized. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP) { string memory base = baseURI(); string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_KAIJUS_SUPPLY)); return string(abi.encodePacked(base, tokenURIWithOffset)); } else { return prerevealURI; } } /* * Pause sale if active, make active if paused */ function setSaleState() external onlyOwner { saleIsActive = !saleIsActive; } /* * Setting presaleEnded state to true allows for minting beyond the * presale token count */ function setPresaleState() external onlyOwner { presaleEnded = !presaleEnded; } /* * Pause sale if active, make active if paused */ function setPresaleSupply(uint256 _presaleSupply) external onlyOwner { presaleSupply = _presaleSupply; } /** * Mints tokens */ function mintCryptoKaijus(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(presaleEnded, "The presale has not ended"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_KAIJUS_SUPPLY, "Purchase would exceed max supply"); require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CRYPTO_KAIJUS_SUPPLY) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either // 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_KAIJUS_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function presaleMintCryptoKaijus(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= presaleSupply, "Purchase would exceed max presale supply"); require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CRYPTO_KAIJUS_SUPPLY) { _safeMint(msg.sender, mintIndex); } } } /** * Set the starting index for the collection */ function setStartingIndex() external { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_CRYPTO_KAIJUS_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_CRYPTO_KAIJUS_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() external onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; uint256 walletBalance = balance.mul(85).div(100); payable(wallet1).transfer(walletBalance); payable(wallet2).transfer(balance.sub(walletBalance)); } }
Mint Crypto Kaijus by owner/Mint address, 0 on first mintSupply is 1 so mint tokenId = 1 (which is the 2nd token)
function reserveCryptoKaijus(address _to, uint256 _numberOfTokens) external onlyOwner { require(_to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; for (i = 0; i < _numberOfTokens; i++) { _safeMint(_to, supply + i); } }
2,447,385
./partial_match/1313161554/0x0A60Bef6b2d3ADDFDC6d9d0cf11CD702AED8B209/sources/AriesPriceOracle.sol
never overflows, and + overflow is desired
function getPriceCumulativeCurrent(address uniswapV2Pair) internal view returns (uint256 priceCumulative) { priceCumulative = IUniswapV2Pair(uniswapV2Pair).price0CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(uniswapV2Pair).getReserves(); uint224 priceLatest = UQ112x112.encode(reserve1).uqdiv(reserve0); priceCumulative += uint256(priceLatest) * timeElapsed; }
16,937,222
pragma solidity ^0.4.24; // 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/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 private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/CoinPledge.sol /// @title CoinPledge /// @author Igor Yalovoy /// @notice Reach your goals and have fun with friends /// @dev All function calls are currently implement without side effects /// @web: ylv.io /// @email: [email protected] /// @gitHub: https://github.com/ylv-io/coinpledge/tree/master /// @twitter: https://twitter.com/ylv_io // Proofs: // Public commitment as a motivator for weight loss (https://onlinelibrary.wiley.com/doi/pdf/10.1002/mar.20316) pragma solidity ^0.4.24; contract CoinPledge is Ownable { using SafeMath for uint256; uint constant daysToResolve = 7 days; uint constant bonusPercentage = 50; uint constant serviceFeePercentage = 10; uint constant minBonus = 1 finney; struct Challenge { address user; string name; uint value; address mentor; uint startDate; uint time; uint mentorFee; bool successed; bool resolved; } struct User { address addr; string name; } // Events event NewChallenge( uint indexed challengeId, address indexed user, string name, uint value, address indexed mentor, uint startDate, uint time, uint mentorFee ); event ChallengeResolved( uint indexed challengeId, address indexed user, address indexed mentor, bool decision ); event BonusFundChanged( address indexed user, uint value ); event NewUsername( address indexed addr, string name ); event Donation( string name, string url, uint value, uint timestamp ); /// @notice indicated is game over or not bool public isGameOver; /// @notice All Challenges Challenge[] public challenges; mapping(uint => address) public challengeToUser; mapping(address => uint) public userToChallengeCount; mapping(uint => address) public challengeToMentor; mapping(address => uint) public mentorToChallengeCount; /// @notice All Users mapping(address => User) public users; address[] public allUsers; mapping(string => address) private usernameToAddress; /// @notice User's bonuses mapping(address => uint) public bonusFund; /// @notice Can access only if game is not over modifier gameIsNotOver() { require(!isGameOver, "Game should be not over"); _; } /// @notice Can access only if game is over modifier gameIsOver() { require(isGameOver, "Game should be over"); _; } /// @notice Get Bonus Fund For User function getBonusFund(address user) external view returns(uint) { return bonusFund[user]; } /// @notice Get Users Lenght function getUsersCount() external view returns(uint) { return allUsers.length; } /// @notice Get Challenges For User function getChallengesForUser(address user) external view returns(uint[]) { require(userToChallengeCount[user] > 0, "Has zero challenges"); uint[] memory result = new uint[](userToChallengeCount[user]); uint counter = 0; for (uint i = 0; i < challenges.length; i++) { if (challengeToUser[i] == user) { result[counter] = i; counter++; } } return result; } /// @notice Get Challenges For Mentor function getChallengesForMentor(address mentor) external view returns(uint[]) { require(mentorToChallengeCount[mentor] > 0, "Has zero challenges"); uint[] memory result = new uint[](mentorToChallengeCount[mentor]); uint counter = 0; for (uint i = 0; i < challenges.length; i++) { if (challengeToMentor[i] == mentor) { result[counter] = i; counter++; } } return result; } /// @notice Ends game function gameOver() external gameIsNotOver onlyOwner { isGameOver = true; } /// @notice Set Username function setUsername(string name) external gameIsNotOver { require(bytes(name).length > 2, "Provide a name longer than 2 chars"); require(bytes(name).length <= 32, "Provide a name shorter than 33 chars"); require(users[msg.sender].addr == address(0x0), "You already have a name"); require(usernameToAddress[name] == address(0x0), "Name already taken"); users[msg.sender] = User(msg.sender, name); usernameToAddress[name] = msg.sender; allUsers.push(msg.sender); emit NewUsername(msg.sender, name); } /// @notice Creates Challenge function createChallenge(string name, string mentor, uint time, uint mentorFee) external payable gameIsNotOver returns (uint retId) { require(msg.value >= 0.01 ether, "Has to stake more than 0.01 ether"); require(mentorFee >= 0 ether, "Can't be negative"); require(mentorFee <= msg.value, "Can't be bigger than stake"); require(bytes(mentor).length > 0, "Has to be a mentor"); require(usernameToAddress[mentor] != address(0x0), "Mentor has to be registered"); require(time > 0, "Time has to be greater than zero"); address mentorAddr = usernameToAddress[mentor]; require(msg.sender != mentorAddr, "Can't be mentor to yourself"); uint startDate = block.timestamp; uint id = challenges.push(Challenge(msg.sender, name, msg.value, mentorAddr, startDate, time, mentorFee, false, false)) - 1; challengeToUser[id] = msg.sender; userToChallengeCount[msg.sender]++; challengeToMentor[id] = mentorAddr; mentorToChallengeCount[mentorAddr]++; emit NewChallenge(id, msg.sender, name, msg.value, mentorAddr, startDate, time, mentorFee); return id; } /// @notice Resolves Challenge function resolveChallenge(uint challengeId, bool decision) external gameIsNotOver { Challenge storage challenge = challenges[challengeId]; require(challenge.resolved == false, "Challenge already resolved."); // if more time passed than endDate + daysToResolve, then user can resolve himself if(block.timestamp < (challenge.startDate + challenge.time + daysToResolve)) require(challenge.mentor == msg.sender, "You are not the mentor for this challenge."); else require((challenge.user == msg.sender) || (challenge.mentor == msg.sender), "You are not the user or mentor for this challenge."); uint mentorFee; uint serviceFee; address user = challengeToUser[challengeId]; address mentor = challengeToMentor[challengeId]; // write decision challenge.successed = decision; challenge.resolved = true; uint remainingValue = challenge.value; // mentor & service fee if(challenge.mentorFee > 0) { serviceFee = challenge.mentorFee.div(100).mul(serviceFeePercentage); mentorFee = challenge.mentorFee.div(100).mul(100 - serviceFeePercentage); } if(challenge.mentorFee > 0) remainingValue = challenge.value.sub(challenge.mentorFee); uint valueToPay; if(decision) { // value to pay back to user valueToPay = remainingValue; // credit bouns if any uint currentBonus = bonusFund[user]; if(currentBonus > 0) { uint bonusValue = bonusFund[user].div(100).mul(bonusPercentage); if(currentBonus <= minBonus) bonusValue = currentBonus; bonusFund[user] -= bonusValue; emit BonusFundChanged(user, bonusFund[user]); valueToPay += bonusValue; } } else { bonusFund[user] += remainingValue; emit BonusFundChanged(user, bonusFund[user]); } // pay back to the challenger if(valueToPay > 0) user.transfer(valueToPay); if(mentorFee > 0) mentor.transfer(mentorFee); if(serviceFee > 0) owner().transfer(serviceFee); emit ChallengeResolved(challengeId, user, mentor, decision); } function withdraw() external gameIsOver { require(bonusFund[msg.sender] > 0, "You do not have any funds"); uint funds = bonusFund[msg.sender]; bonusFund[msg.sender] = 0; msg.sender.transfer(funds); } function donate(string name, string url) external payable gameIsNotOver { owner().transfer(msg.value); emit Donation(name, url, msg.value, block.timestamp); } }
Get Users Lenght
function getUsersCount() external view returns(uint) { return allUsers.length; }
12,785,230
./full_match/4/0x53F9d97EaA8dA97d85266fcd6d3b9013DcF57cD6/sources/contracts-v2/contracts/v2/ArtToken.sol
Creates a NFT _metaDataURI for the new token _metaData metadata JSONified string _marketplace address _encodedCallData of the create call in dst marketplace/ Create the new asset and allow marketplace to manage it Use this to override the msg.sender here. execute create order in destination marketplace
function createPub( string calldata _metaDataURI, string calldata _metaData, address _marketplace, bytes calldata _encodedCallData ) external { this.approve( _marketplace, _create(address(this), _metaDataURI, _metaData) ); (bool success, ) = _marketplace.call(_encodedCallData); require( success, "Marketplace: failed to execute publish order" ); }
12,290,711
./partial_match/1/0x46C9CFB32627B74F91e0B5ad575c247AEc7e7847/sources/contracts/NftfiBundler.sol
Override validation if it is a transfer from the airdropFlashLoan contract giving back the flashloan. Validates the data from a child transfer and receives it otherwise _from The owner of the child token _childContract The ERC721 contract of the child token _childTokenId The token that is being transferred to the parent _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId/
function _validateAndReceiveChild( address _from, address _childContract, uint256 _childTokenId, bytes memory _data ) internal virtual override { if (_from == airdropFlashLoan) { return; super._validateAndReceiveChild(_from, _childContract, _childTokenId, _data); } }
9,403,868
./full_match/43114/0x562BdcEff7aA89936e52E16EB52ABd1770e42cBE/sources/StratX2_Treasury.sol
Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function./
function updateMinDelay(uint256 newDelay) external virtual { require( msg.sender == address(this), "TimelockController: caller must be timelock" ); emit MinDelayChange(minDelay, newDelay); minDelay = newDelay; }
4,631,776
./partial_match/56/0x4A5a34212404f30C5aB7eB61b078fA4A55AdC5a5/sources/MilkyWaySmartToken.sol
Native MIlkyWay burn notation saved./
function burn(address _to, uint256 _amount) external onlyGovernanceContracts() returns (bool) { _burn(_to, _amount); _totalBurned = _totalBurned.add(_amount); return true; }
11,052,572
pragma solidity ^0.4.10; import '../common/Manageable.sol'; import './ERC20StandardToken.sol'; import './ReturnTokenAgent.sol'; ///Token that when sent to specified contract (returnAgent) invokes additional actions contract ReturnableToken is Manageable, ERC20StandardToken { /**@dev List of return agents */ mapping (address => bool) public returnAgents; function ReturnableToken() public {} /**@dev Sets new return agent */ function setReturnAgent(ReturnTokenAgent agent) public managerOnly { returnAgents[address(agent)] = true; } /**@dev Removes return agent from list */ function removeReturnAgent(ReturnTokenAgent agent) public managerOnly { returnAgents[address(agent)] = false; } function doTransfer(address _from, address _to, uint256 _value) internal { super.doTransfer(_from, _to, _value); if (returnAgents[_to]) { ReturnTokenAgent(_to).returnToken(_from, _value); } } }
Sets new return agent /
function setReturnAgent(ReturnTokenAgent agent) public managerOnly { returnAgents[address(agent)] = true; }
1,089,261
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import '../interface/IBTokenSwapper.sol'; import '../interface/IERC20.sol'; import '../interface/IUniswapV2Pair.sol'; import '../interface/IUniswapV2Router02.sol'; import '../lib/SafeMath.sol'; import '../utils/SafeERC20.sol'; abstract contract BTokenSwapper is IBTokenSwapper { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant UONE = 10**18; // address of the tokenBX, e.x. WETH address public immutable addressBX; // address of the tokenB0, this is the base0 token (settlement token) of PerpetualPool, e.x. USDT address public immutable addressB0; uint256 public immutable decimalsBX; uint256 public immutable decimalsB0; uint256 public immutable maxSlippageRatio; constructor (address addressBX_, address addressB0_, uint256 maxSlippageRatio_) { addressBX = addressBX_; addressB0 = addressB0_; decimalsBX = IERC20(addressBX_).decimals(); decimalsB0 = IERC20(addressB0_).decimals(); maxSlippageRatio = maxSlippageRatio_; } // swap exact `amountB0` amount of tokenB0 for tokenBX function swapExactB0ForBX(uint256 amountB0, uint256 referencePrice) external override returns (uint256 resultB0, uint256 resultBX) { address caller = msg.sender; IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); uint256 bx1 = tokenBX.balanceOf(caller); amountB0 = amountB0.rescale(18, decimalsB0); tokenB0.safeTransferFrom(caller, address(this), amountB0); _swapExactTokensForTokens(addressB0, addressBX, caller); uint256 bx2 = tokenBX.balanceOf(caller); resultB0 = amountB0.rescale(decimalsB0, 18); resultBX = (bx2 - bx1).rescale(decimalsBX, 18); require( resultBX >= resultB0 * (UONE - maxSlippageRatio) / referencePrice, 'BTokenSwapper.swapExactB0ForBX: slippage exceeds allowance' ); } // swap exact `amountBX` amount of tokenBX token for tokenB0 function swapExactBXForB0(uint256 amountBX, uint256 referencePrice) external override returns (uint256 resultB0, uint256 resultBX) { address caller = msg.sender; IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); uint256 b01 = tokenB0.balanceOf(caller); amountBX = amountBX.rescale(18, decimalsBX); tokenBX.safeTransferFrom(caller, address(this), amountBX); _swapExactTokensForTokens(addressBX, addressB0, caller); uint256 b02 = tokenB0.balanceOf(caller); resultB0 = (b02 - b01).rescale(decimalsB0, 18); resultBX = amountBX.rescale(decimalsBX, 18); require( resultB0 >= resultBX * referencePrice / UONE * (UONE - maxSlippageRatio) / UONE, 'BTokenSwapper.swapExactBXForB0: slippage exceeds allowance' ); } // swap max amount of tokenB0 `amountB0` for exact amount of tokenBX `amountBX` // in case `amountB0` is sufficient, the remains will be sent back // in case `amountB0` is insufficient, it will be used up to swap for tokenBX function swapB0ForExactBX(uint256 amountB0, uint256 amountBX, uint256 referencePrice) external override returns (uint256 resultB0, uint256 resultBX) { address caller = msg.sender; IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); uint256 b01 = tokenB0.balanceOf(caller); uint256 bx1 = tokenBX.balanceOf(caller); amountB0 = amountB0.rescale(18, decimalsB0); amountBX = amountBX.rescale(18, decimalsBX); tokenB0.safeTransferFrom(caller, address(this), amountB0); if (amountB0 >= _getAmountInB0(amountBX) * 11 / 10) { _swapTokensForExactTokens(addressB0, addressBX, amountBX, caller); } else { _swapExactTokensForTokens(addressB0, addressBX, caller); } uint256 remainB0 = tokenB0.balanceOf(address(this)); if (remainB0 != 0) tokenB0.safeTransfer(caller, remainB0); uint256 b02 = tokenB0.balanceOf(caller); uint256 bx2 = tokenBX.balanceOf(caller); resultB0 = (b01 - b02).rescale(decimalsB0, 18); resultBX = (bx2 - bx1).rescale(decimalsBX, 18); require( resultBX * referencePrice >= resultB0 * (UONE - maxSlippageRatio), 'BTokenSwapper.swapB0ForExactBX: slippage exceeds allowance' ); } // swap max amount of tokenBX `amountBX` for exact amount of tokenB0 `amountB0` // in case `amountBX` is sufficient, the remains will be sent back // in case `amountBX` is insufficient, it will be used up to swap for tokenB0 function swapBXForExactB0(uint256 amountB0, uint256 amountBX, uint256 referencePrice) external override returns (uint256 resultB0, uint256 resultBX) { address caller = msg.sender; IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); uint256 b01 = tokenB0.balanceOf(caller); uint256 bx1 = tokenBX.balanceOf(caller); amountB0 = amountB0.rescale(18, decimalsB0); amountBX = amountBX.rescale(18, decimalsBX); tokenBX.safeTransferFrom(caller, address(this), amountBX); if (amountBX >= _getAmountInBX(amountB0) * 11 / 10) { _swapTokensForExactTokens(addressBX, addressB0, amountB0, caller); } else { _swapExactTokensForTokens(addressBX, addressB0, caller); } uint256 remainBX = tokenBX.balanceOf(address(this)); if (remainBX != 0) tokenBX.safeTransfer(caller, remainBX); uint256 b02 = tokenB0.balanceOf(caller); uint256 bx2 = tokenBX.balanceOf(caller); resultB0 = (b02 - b01).rescale(decimalsB0, 18); resultBX = (bx1 - bx2).rescale(decimalsBX, 18); require( resultB0 >= resultBX * referencePrice / UONE * (UONE - maxSlippageRatio) / UONE, 'BTokenSwapper.swapBXForExactB0: slippage exceeds allowance' ); } // in case someone send tokenB0/tokenBX to this contract, // the previous functions might be blocked // anyone can call this function to withdraw any remaining tokenB0/tokenBX in this contract // idealy, this contract should have no balance for tokenB0/tokenBX function sync() external override { IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); if (tokenB0.balanceOf(address(this)) != 0) tokenB0.safeTransfer(msg.sender, tokenB0.balanceOf(address(this))); if (tokenBX.balanceOf(address(this)) != 0) tokenBX.safeTransfer(msg.sender, tokenBX.balanceOf(address(this))); } //================================================================================ // estimate the tokenB0 amount needed to swap for `amountOutBX` tokenBX function _getAmountInB0(uint256 amountOutBX) internal virtual view returns (uint256); // estimate the tokenBX amount needed to swap for `amountOutB0` tokenB0 function _getAmountInBX(uint256 amountOutB0) internal virtual view returns (uint256); // low-level swap function function _swapExactTokensForTokens(address a, address b, address to) internal virtual; // low-level swap function function _swapTokensForExactTokens(address a, address b, uint256 amount, address to) internal virtual; }
swap max amount of tokenBX `amountBX` for exact amount of tokenB0 `amountB0` in case `amountBX` is sufficient, the remains will be sent back in case `amountBX` is insufficient, it will be used up to swap for tokenB0
function swapBXForExactB0(uint256 amountB0, uint256 amountBX, uint256 referencePrice) external override returns (uint256 resultB0, uint256 resultBX) { address caller = msg.sender; IERC20 tokenB0 = IERC20(addressB0); IERC20 tokenBX = IERC20(addressBX); uint256 b01 = tokenB0.balanceOf(caller); uint256 bx1 = tokenBX.balanceOf(caller); amountB0 = amountB0.rescale(18, decimalsB0); amountBX = amountBX.rescale(18, decimalsBX); tokenBX.safeTransferFrom(caller, address(this), amountBX); if (amountBX >= _getAmountInBX(amountB0) * 11 / 10) { _swapTokensForExactTokens(addressBX, addressB0, amountB0, caller); _swapExactTokensForTokens(addressBX, addressB0, caller); } uint256 remainBX = tokenBX.balanceOf(address(this)); if (remainBX != 0) tokenBX.safeTransfer(caller, remainBX); uint256 b02 = tokenB0.balanceOf(caller); uint256 bx2 = tokenBX.balanceOf(caller); resultB0 = (b02 - b01).rescale(decimalsB0, 18); resultBX = (bx1 - bx2).rescale(decimalsBX, 18); require( resultB0 >= resultBX * referencePrice / UONE * (UONE - maxSlippageRatio) / UONE, 'BTokenSwapper.swapBXForExactB0: slippage exceeds allowance' ); }
926,901
./full_match/1/0x699C9b664f5196B02Dcf20A27c035749c6889FFb/sources/contracts/TxDaoCrowdsale.sol
Check if the signer is any of the contract valid signers
function verify(bytes memory signature, uint256 spots, uint256 voucherId) private view returns (bool) { bytes32 messageHash = getMessageHash(msg.sender, spots, voucherId); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); address signer = recoverSigner(ethSignedMessageHash, signature); for (uint i = 0; i < _signers.length; i++) { if (_signers[i] == signer) { return true; } } return false; }
4,875,900
./partial_match/1/0x1955D86f5b369Be4581Fb2D346B403d362883aC7/sources/EmployeeIDBadges.sol
_owner The address that owns the NFTs _operator The address that acts on behalf of the owner return Will always return false/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return approvalAll[_owner][_operator]; }
3,590,608
pragma solidity ^0.5.0; contract HalfRouletteEvents { event Commit(uint commit); // 배팅 event Payment(address indexed gambler, uint amount, uint8 betMask, uint8 l, uint8 r, uint betAmount); // 결과 처리 event Refund(address indexed gambler, uint amount); // 결과 처리 event JackpotPayment(address indexed gambler, uint amount); // 잭팟 event VIPBenefit(address indexed gambler, uint amount); // VIP 보상 event InviterBenefit(address indexed inviter, address gambler, uint betAmount, uint amount); // 초대자 보상 event LuckyCoinBenefit(address indexed gambler, uint amount, uint32 result); // 럭키코인 보상 event TodaysRankingPayment(address indexed gambler, uint amount); // 랭킹 보상 } contract HalfRouletteOwner { address payable owner; // 게시자 address payable nextOwner; address secretSigner = 0xcb91F80fC3dcC6D51b10b1a6E6D77C28DAf7ffE2; // 서명 관리자 mapping(address => bool) public croupierMap; // 하우스 운영 modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCroupier { bool isCroupier = croupierMap[msg.sender]; require(isCroupier, "OnlyCroupier methods called by non-croupier."); _; } constructor() public { owner = msg.sender; croupierMap[msg.sender] = true; } function approveNextOwner(address payable _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require(msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function addCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == false) { croupierMap[newCroupier] = true; } } function deleteCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == true) { croupierMap[newCroupier] = false; } } } contract HalfRouletteStruct { struct Bet { uint amount; // 배팅 금액 uint8 betMask; // 배팅 정보 uint40 placeBlockNumber; // Block number of placeBet tx. address payable gambler; // Address of a gambler, used to pay out winning bets. } struct LuckyCoin { bool coin; // 럭키 코인 활성화 uint16 result; // 마지막 결과 uint64 amount; // MAX 18.446744073709551615 ether < RECEIVE_LUCKY_COIN_BET(0.05 ether) uint64 timestamp; // 마지막 업데이트 시간 00:00 시 } struct DailyRankingPrize { uint128 prizeSize; // 지불 급액 uint64 timestamp; // 마지막 업데이트 시간 00:00 시 uint8 cnt; // 받은 횟수 } } contract HalfRouletteConstant { // constant // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions AceDice croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; uint constant JACKPOT_FEE_PERCENT = 1; // amount * 0.001 uint constant HOUSE_EDGE_PERCENT = 1; // amount * 0.01 uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; // 최소 houseEdge uint constant RANK_FUNDS_PERCENT = 12; // houseEdge * 0.12 uint constant INVITER_BENEFIT_PERCENT = 9; // houseEdge * 0.09 uint constant MAX_LUCKY_COIN_BENEFIT = 1.65 ether; // 최대 ether uint constant MIN_BET = 0.01 ether; // 최소 배팅 금액 uint constant MAX_BET = 300000 ether; // 최대 배팅 금액 uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant RECEIVE_LUCKY_COIN_BET = 0.05 ether; uint constant BASE_WIN_RATE = 100000; uint constant TODAY_RANKING_PRIZE_MODULUS = 10000; // not support constant uint16[10] TODAY_RANKING_PRIZE_RATE = [5000, 2500, 1200, 600, 300, 200, 100, 50, 35, 15]; } contract HalfRoulettePure is HalfRouletteConstant { function verifyBetMask(uint betMask) public pure { bool verify; assembly { switch betMask case 1 /* ODD */{verify := 1} case 2 /* EVEN */{verify := 1} case 4 /* LEFT */{verify := 1} case 8 /* RIGHT */{verify := 1} case 5 /* ODD | LEFT */{verify := 1} case 9 /* ODD | RIGHT */{verify := 1} case 6 /* EVEN | LEFT */{verify := 1} case 10 /* EVEN | RIGHT */{verify := 1} case 16 /* EQUAL */{verify := 1} } require(verify, "invalid betMask"); } function getRecoverSigner(uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes32 messageHash = keccak256(abi.encodePacked(commitLastBlock, commit)); return ecrecover(messageHash, v, r, s); } function getWinRate(uint betMask) public pure returns (uint rate) { // assembly 안에서는 constant 사용 불가 uint ODD_EVEN_RATE = 50000; uint LEFT_RIGHT_RATE = 45833; uint MIX_RATE = 22916; uint EQUAL_RATE = 8333; assembly { switch betMask case 1 /* ODD */{rate := ODD_EVEN_RATE} case 2 /* EVEN */{rate := ODD_EVEN_RATE} case 4 /* LEFT */{rate := LEFT_RIGHT_RATE} case 8 /* RIGHT */{rate := LEFT_RIGHT_RATE} case 5 /* ODD | LEFT */{rate := MIX_RATE} case 9 /* ODD | RIGHT */{rate := MIX_RATE} case 6 /* EVEN | LEFT */{rate := MIX_RATE} case 10 /* EVEN | RIGHT */{rate := MIX_RATE} case 16 /* EQUAL */{rate := EQUAL_RATE} } } function calcHouseEdge(uint amount) public pure returns (uint houseEdge) { // 0.02 houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } } function calcJackpotFee(uint amount) public pure returns (uint jackpotFee) { // 0.001 jackpotFee = amount * JACKPOT_FEE_PERCENT / 1000; } function calcRankFundsFee(uint houseEdge) public pure returns (uint rankFundsFee) { // 0.12 rankFundsFee = houseEdge * RANK_FUNDS_PERCENT / 100; } function calcInviterBenefit(uint houseEdge) public pure returns (uint invitationFee) { // 0.09 invitationFee = houseEdge * INVITER_BENEFIT_PERCENT / 100; } function calcVIPBenefit(uint amount, uint totalAmount) public pure returns (uint vipBenefit) { /* 0 0.00 % 없음 1 0.01 % 골드 2 0.02 % 토파즈 3 0.03 % 크리스탈 4 0.04 % 에메랄드 5 0.05 % 사파이어 6 0.07 % 오팔 7 0.09 % 다이아몬드 8 0.11 % 옐로_다이아몬드 9 0.13 % 블루_다이아몬드 10 0.15 % 레드_다이아몬드 */ uint rate; if (totalAmount < 25 ether) { return rate; } else if (totalAmount < 125 ether) { rate = 1; } else if (totalAmount < 250 ether) { rate = 2; } else if (totalAmount < 1250 ether) { rate = 3; } else if (totalAmount < 2500 ether) { rate = 4; } else if (totalAmount < 12500 ether) { rate = 5; } else if (totalAmount < 25000 ether) { rate = 7; } else if (totalAmount < 125000 ether) { rate = 9; } else if (totalAmount < 250000 ether) { rate = 11; } else if (totalAmount < 1250000 ether) { rate = 13; } else { rate = 15; } vipBenefit = amount * rate / 10000; } function calcLuckyCoinBenefit(uint num) public pure returns (uint luckCoinBenefit) { /* 1 - 9885 0.000015 ETH 9886 - 9985 0.00015 ETH 9986 - 9993 0.0015 ETH 9994 - 9997 0.015 ETH 9998 - 9999 0.15 ETH 10000 1.65 ETH */ if (num < 9886) { return 0.000015 ether; } else if (num < 9986) { return 0.00015 ether; } else if (num < 9994) { return 0.0015 ether; } else if (num < 9998) { return 0.015 ether; } else if (num < 10000) { return 0.15 ether; } else { return 1.65 ether; } } function getWinAmount(uint betMask, uint amount) public pure returns (uint) { uint houseEdge = calcHouseEdge(amount); uint jackpotFee = calcJackpotFee(amount); uint betAmount = amount - houseEdge - jackpotFee; uint rate = getWinRate(betMask); return betAmount * BASE_WIN_RATE / rate; } function calcBetResult(uint betMask, bytes32 entropy) public pure returns (bool isWin, uint l, uint r) { uint v = uint(entropy); l = (v % 12) + 1; r = ((v >> 4) % 12) + 1; uint mask = getResultMask(l, r); isWin = (betMask & mask) == betMask; } function getResultMask(uint l, uint r) public pure returns (uint mask) { uint v1 = (l + r) % 2; uint v2 = l - r; if (v1 == 0) { mask = mask | 2; } else { mask = mask | 1; } if (v2 == 0) { mask = mask | 16; } else if (v2 > 0) { mask = mask | 4; } else { mask = mask | 8; } return mask; } function isJackpot(bytes32 entropy, uint amount) public pure returns (bool jackpot) { return amount >= MIN_JACKPOT_BET && (uint(entropy) % 1000) == 0; } function verifyCommit(address signer, uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) internal pure { address recoverSigner = getRecoverSigner(commitLastBlock, commit, v, r, s); require(recoverSigner == signer, "failed different signer"); } function startOfDay(uint timestamp) internal pure returns (uint64) { return uint64(timestamp - (timestamp % 1 days)); } } contract HalfRoulette is HalfRouletteEvents, HalfRouletteOwner, HalfRouletteStruct, HalfRouletteConstant, HalfRoulettePure { uint128 public lockedInBets; uint128 public jackpotSize; // 잭팟 크기 uint128 public rankFunds; // 랭킹 보상 DailyRankingPrize dailyRankingPrize; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit = 10 ether; // global variable mapping(uint => Bet) public bets; mapping(address => LuckyCoin) public luckyCoins; mapping(address => address payable) public inviterMap; mapping(address => uint) public accuBetAmount; function() external payable {} function kill() external onlyOwner { require(lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(address(owner)); } function setMaxProfit(uint _maxProfit) external onlyOwner { require(_maxProfit < MAX_BET, "maxProfit should be a sane number."); maxProfit = _maxProfit; } function placeBet(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public payable { Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a 'clean' state."); // amount checked uint amount = msg.value; require(amount >= MIN_BET, 'failed amount >= MIN_BET'); require(amount <= MAX_BET, "failed amount <= MAX_BET"); // allow bet check verifyBetMask(betMask); // rand seed check verifyCommit(secretSigner, uint40(commitLastBlock), commit, v, r, s); // house balance check uint winAmount = getWinAmount(betMask, amount); require(winAmount <= amount + maxProfit, "maxProfit limit violation."); lockedInBets += uint128(winAmount); require(lockedInBets + jackpotSize + rankFunds + dailyRankingPrize.prizeSize <= address(this).balance, "Cannot afford to lose this bet."); // save emit Commit(commit); bet.gambler = msg.sender; bet.amount = amount; bet.betMask = betMask; bet.placeBlockNumber = uint40(block.number); // lucky coin 은 block.timestamp 에 의존하여 사전에 처리 incLuckyCoin(msg.sender, amount); } function placeBetWithInviter(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable { require(inviter != address(0), "inviter != address (0)"); address preInviter = inviterMap[msg.sender]; if (preInviter == address(0)) { inviterMap[msg.sender] = inviter; } placeBet(betMask, commitLastBlock, commit, v, r, s); } // block.timestamp 에 의존 합니다 function incLuckyCoin(address gambler, uint amount) internal { LuckyCoin storage luckyCoin = luckyCoins[gambler]; uint64 today = startOfDay(block.timestamp); uint beforeAmount; if (today == luckyCoin.timestamp) { beforeAmount = uint(luckyCoin.amount); } else { luckyCoin.timestamp = today; if (luckyCoin.coin) luckyCoin.coin = false; } if (beforeAmount == RECEIVE_LUCKY_COIN_BET) return; uint totalAmount = beforeAmount + amount; if (totalAmount >= RECEIVE_LUCKY_COIN_BET) { luckyCoin.amount = uint64(RECEIVE_LUCKY_COIN_BET); if (!luckyCoin.coin) { luckyCoin.coin = true; } } else { luckyCoin.amount = uint64(totalAmount); } } function revertLuckyCoin(address gambler) private { LuckyCoin storage luckyCoin = luckyCoins[gambler]; if (!luckyCoin.coin) return; if (startOfDay(block.timestamp) == luckyCoin.timestamp) { luckyCoin.coin = false; } } function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require(block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require(block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require(blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require(block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require(blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly {leafHeaderByte := byte(0, calldataload(offset))} require(leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly {pathHeaderByte := byte(0, calldataload(offset))} if (pathHeaderByte <= 0x7f) { offset += 1; } else { require(pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly {receiptStringHeaderByte := byte(0, calldataload(offset))} require(receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly {receiptHeaderByte := byte(0, calldataload(offset))} require(receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly {statusByte := byte(0, calldataload(offset))} require(statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly {cumGasHeaderByte := byte(0, calldataload(offset))} if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require(cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly {bloomHeaderByte := byte(0, calldataload(offset))} require(bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly {logsListHeaderByte := byte(0, calldataload(offset))} require(logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly {logEntryHeaderByte := byte(0, calldataload(offset))} require(logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly {addressHeaderByte := byte(0, calldataload(offset))} require(addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly {logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff)} require(logAddress == uint(address(this))); } /* *** Merkle 증명. 이 도우미는 삼촌 블록에 placeBet 포함을 증명하는 암호를 확인하는 데 사용됩니다. 스마트 계약의 보안을 손상시키지 않으면 서 Ethereum reorg에서 베팅 결과가 변경되는 것을 방지하기 위해 사용됩니다. 증명 자료는 간단한 접두사 길이 형식으로 입력 데이터에 추가되며 ABI를 따르지 않습니다. 불변량 검사 : - 영수증 트라이 엔트리는 페이로드로 커밋을 포함하는이 스마트 계약 (3)에 대한 (1) 성공적인 트랜잭션 (2)을 포함합니다. - 영수증 트 리 항목은 블록 헤더의 유효한 merkle 증명의 일부입니다 - 블록 헤더는 정식 체인에있는 블록의 삼촌 목록의 일부입니다. 구현은 가스 비용에 최적화되어 있으며 Ethereum 내부 데이터 구조의 특성에 의존합니다. 자세한 내용은 백서를 참조하십시오. 일부 seedHash (보통 커밋)에서 시작하여 완전한 merkle 증명을 확인하는 도우미. "offset"은 calldata에서 시작되는 증명의 위치입니다. */ function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly {scratchBuf1 := mload(0x40)} uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (;; offset += blobLength) { assembly {blobLength := and(calldataload(sub(offset, 30)), 0xffff)} if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly {shift := and(calldataload(sub(offset, 28)), 0xffff)} require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly {hashSlot := calldataload(add(offset, shift))} require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly {unclesLength := and(calldataload(sub(offset, 28)), 0xffff)} uint unclesShift; assembly {unclesShift := and(calldataload(sub(offset, 26)), 0xffff)} require(unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly {calldatacopy(scratchBuf2, offset, unclesLength)} memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly {seedHash := keccak256(scratchBuf2, unclesLength)} offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly {hashSlot := calldataload(add(offset, shift))} require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) } } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for (; len >= 32; len -= 32) { assembly {mstore(dest, mload(src))} dest += 32; src += 32; } // Remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function processVIPBenefit(address gambler, uint amount) internal returns (uint benefitAmount) { uint totalAmount = accuBetAmount[gambler]; accuBetAmount[gambler] += amount; benefitAmount = calcVIPBenefit(amount, totalAmount); } function processJackpot(address gambler, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { if (isJackpot(entropy, amount)) { benefitAmount = jackpotSize; jackpotSize -= jackpotSize; emit JackpotPayment(gambler, benefitAmount); } } function processRoulette(address gambler, uint betMask, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { uint houseEdge = calcHouseEdge(amount); uint jackpotFee = calcJackpotFee(amount); uint rankFundFee = calcRankFundsFee(houseEdge); uint rate = getWinRate(betMask); uint winAmount = (amount - houseEdge - jackpotFee) * BASE_WIN_RATE / rate; lockedInBets -= uint128(winAmount); rankFunds += uint128(rankFundFee); jackpotSize += uint128(jackpotFee); (bool isWin, uint l, uint r) = calcBetResult(betMask, entropy); benefitAmount = isWin ? winAmount : 0; emit Payment(gambler, benefitAmount, uint8(betMask), uint8(l), uint8(r), amount); } function processInviterBenefit(address gambler, uint amount) internal { address payable inviter = inviterMap[gambler]; if (inviter != address(0)) { uint houseEdge = calcHouseEdge(amount); uint inviterBenefit = calcInviterBenefit(houseEdge); inviter.transfer(inviterBenefit); emit InviterBenefit(inviter, gambler, inviterBenefit, amount); } } function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) internal { uint amount = bet.amount; // Check that bet is in 'active' state. require(amount != 0, "Bet should be in an 'active' state"); bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); uint payout = 0; payout += processVIPBenefit(bet.gambler, amount); payout += processJackpot(bet.gambler, entropy, amount); payout += processRoulette(bet.gambler, bet.betMask, entropy, amount); processInviterBenefit(bet.gambler, amount); bet.gambler.transfer(payout); } // Refund transaction - return the bet amount of a roll that was not processed in a due timeframe. // Processing such blocks is not possible due to EVM limitations (see BET_EXPIRATION_BLOCKS comment above for details). // In case you ever find yourself in a situation like this, just contact the {} support, however nothing precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require(amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require(block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Move bet into 'processed' state, release funds. bet.amount = 0; uint winAmount = getWinAmount(bet.betMask, amount); lockedInBets -= uint128(winAmount); revertLuckyCoin(bet.gambler); // Send the refund. bet.gambler.transfer(amount); emit Refund(bet.gambler, amount); } function useLuckyCoin(address payable gambler, uint reveal) external onlyCroupier { LuckyCoin storage luckyCoin = luckyCoins[gambler]; require(luckyCoin.coin == true, "luckyCoin.coin == true"); uint64 today = startOfDay(block.timestamp); require(luckyCoin.timestamp == today, "luckyCoin.timestamp == today"); luckyCoin.coin = false; bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(block.number))); luckyCoin.result = uint16((uint(entropy) % 10000) + 1); uint benefit = calcLuckyCoinBenefit(luckyCoin.result); if (gambler.send(benefit)) { emit LuckyCoinBenefit(gambler, benefit, luckyCoin.result); } } function payTodayReward(address payable gambler) external onlyCroupier { uint64 today = startOfDay(block.timestamp); if (dailyRankingPrize.timestamp != today) { dailyRankingPrize.timestamp = today; dailyRankingPrize.prizeSize = rankFunds; dailyRankingPrize.cnt = 0; rankFunds = 0; } require(dailyRankingPrize.cnt < TODAY_RANKING_PRIZE_RATE.length, "cnt < length"); uint prize = dailyRankingPrize.prizeSize * TODAY_RANKING_PRIZE_RATE[dailyRankingPrize.cnt] / TODAY_RANKING_PRIZE_MODULUS; dailyRankingPrize.cnt += 1; if (gambler.send(prize)) { emit TodaysRankingPayment(gambler, prize); } } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require(increaseAmount <= address(this).balance, "Increase amount larger than balance."); require(jackpotSize + lockedInBets + increaseAmount + dailyRankingPrize.prizeSize <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of HalfRoulette operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require(withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require(jackpotSize + lockedInBets + withdrawAmount + rankFunds + dailyRankingPrize.prizeSize <= address(this).balance, "Not enough funds."); beneficiary.transfer(withdrawAmount); } }
block.timestamp 에 의존 합니다
function incLuckyCoin(address gambler, uint amount) internal { LuckyCoin storage luckyCoin = luckyCoins[gambler]; uint64 today = startOfDay(block.timestamp); uint beforeAmount; if (today == luckyCoin.timestamp) { beforeAmount = uint(luckyCoin.amount); luckyCoin.timestamp = today; if (luckyCoin.coin) luckyCoin.coin = false; } if (beforeAmount == RECEIVE_LUCKY_COIN_BET) return; uint totalAmount = beforeAmount + amount; if (totalAmount >= RECEIVE_LUCKY_COIN_BET) { luckyCoin.amount = uint64(RECEIVE_LUCKY_COIN_BET); if (!luckyCoin.coin) { luckyCoin.coin = true; } luckyCoin.amount = uint64(totalAmount); } }
1,050,592
./full_match/1/0xb688801cadb4Ddb6980bb777d42972C24f920855/sources/solidity/contracts/core/VaultController.sol
Returns the latest interest factor return _interestFactor The latest interest factor
function interestFactor() external view override returns (uint192 _interestFactor) { _interestFactor = interest.factor; }
9,677,931
./full_match/44787/0x7Ee4006e2bDD272938ba2B867E7d85C9f9d3a3f8/sources/project_/contracts/CASRegistryManager.sol
exchange FCRU tokens on buffer for VCRU tokens on project projectInput ( projectAddress: bytes(address), bundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string), projectAddress: bytes(address) ) bufferInput ( bufferAddress: bytes(address), bundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string), projectAddress: bytes(address) ) projectOutput ( projectAddress: bytes(address), outputBundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string), projectAddress: bytes(address) ) bufferOutput ( bufferAddress: bytes(address), outputBundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string), projectAddress: bytes(address) )/ exchangeCheck(projectInput, bufferInput, projectOutput, bufferOutput);
function bufferFcruToProjectVcruExchange( bytes[] calldata projectInput, bytes[] calldata bufferInput, bytes[] calldata projectOutput, bytes[] calldata bufferOutput) public checkAccess { sameAmount(bufferInput[2], projectOutput[2]); sameAmount(projectInput[2], bufferOutput[2]); sameAmount(bufferInput[2], bufferOutput[2]); sameAddress(bufferInput[0], bufferOutput[0]); checkTokenType(bufferInput[3], "FCRU"); checkTokenType(projectOutput[3], "FCRU_Revoked"); checkTokenType(projectInput[3], "VCRU"); checkTokenType(bufferOutput[3], "VCRU"); sameAddress(projectInput[0], projectOutput[0]); IBundle(bufferContractAddress).subtractBundleVolume(bufferInput); IBundle(projectContractAddress).addBundleVolume(projectOutput); IBundle(projectContractAddress).subtractBundleVolume(projectInput); IBundle(bufferContractAddress).addBundleVolume(bufferOutput);
13,282,116
//SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Unicode.sol"; import "./UTF8Encoder.sol"; /// @title An API for the Unicode Character Database /// @author Devin Stein /// @notice The Unicode Character Database available on Ethereum and to Ethereum developers /// @dev This project is only possible because of many previous Unicode data implementations. A few to highlight are /// https://unicode-org.github.io/icu-docs/apidoc/dev/icu4c/index.html /// https://github.com/open-i18n/rust-unic /// For more information, review https://www.unicode.org/reports/tr44 contract UnicodeData is Ownable { using Unicode for string; using UTF8Encoder for uint32; // Unicode Data Version uint8 public constant MAJOR_VERSION = 14; uint8 public constant MINOR_VERSION = 0; uint8 public constant PATCH_VERSION = 0; /// @dev https://www.unicode.org/reports/tr44/#Bidi_Class_Values enum BidiClass { LEFT_TO_RIGHT, RIGHT_TO_LEFT, ARABIC_LETTER, ARABIC_NUMBER, EUROPEAN_NUMBER, EUROPEAN_SEPARATOR, EUROPEAN_TERMINATOR, COMMON_SEPARATOR, NONSPACING_MARK, BOUNDARY_NEUTRAL, PARAGRAPH_SEPARATOR, SEGMENT_SEPARATOR, WHITE_SPACE, OTHER_NEUTRAL, LEFT_TO_RIGHT_EMBEDDING, LEFT_TO_RIGHT_OVERRIDE, RIGHT_TO_LEFT_EMBEDDING, RIGHT_TO_LEFT_OVERRIDE, LEFT_TO_RIGHT_ISOLATE, RIGHT_TO_LEFT_ISOLATE, POP_DIRECTIONAL_FORMAT, POP_DIRECTIONAL_ISOLATE, FIRST_STRONG_ISOLATE } /// @dev https://www.unicode.org/reports/tr44/#Decomposition_Type enum DecompositionType { NONE, /*[none]*/ CANONICAL, /*[can]*/ COMPAT, /*[com]*/ CIRCLE, /*[enc]*/ FINAL, /*[fin]*/ FONT, /*[font]*/ FRACTION, /*[fra]*/ INITIAL, /*[init]*/ ISOLATED, /*[iso]*/ MEDIAL, /*[med]*/ NARROW, /*[nar]*/ NO_BREAK, /*[nb]*/ SMALL, /*[sml]*/ SQUARE, /*[sqr]*/ SUB, /*[sub]*/ SUPER, /*[sup]*/ VERTICAL, /*[vert]*/ WIDE /*[wide]*/ } /// @dev DECIMAL_DIGIT_NAN is the 'NaN' value for the decimal and digit properties uint8 public constant DECIMAL_DIGIT_NAN = type(uint8).max; function isNaN(uint8 _number) internal pure returns (bool) { // hardcode 1 and 0 to keep function pure (instead of view) return _number == DECIMAL_DIGIT_NAN; } /// @dev: RationalNumber is a naive representation of a rational number. /// It is meant to store information for the numeric value of unicode characters. /// int128 is sufficient for current and likely future unicode characters. /// signed ints are required for TIBETAN DIGIT HALF ZERO (0F33), which is negative. /// It is not meant to provide utilities for rational number math. /// For downstream computation, use other libraries like /// https://github.com/hifi-finance/prb-math/ /// https://github.com/abdk-consulting/abdk-libraries-solidity struct RationalNumber { int128 numerator; int128 denominator; } /// @dev RATIONAL_NUMBER_NAN is the 'NaN' value for the numeric property RationalNumber public RATIONAL_NUMBER_NAN = RationalNumber(1, 0); function isNaN(RationalNumber memory _number) internal pure returns (bool) { // hardcode 1 and 0 to keep function pure (instead of view) return _number.numerator == 1 && _number.denominator == 0; } /// @dev Character represents the Unicode database character properties: /// https://unicode.org/Public/UNIDATA/UnicodeData.txt // Order of Properties Matter: https://docs.soliditylang.org/en/v0.8.10/internals/layout_in_storage.html // name = 32 bytes // numeric = 32 bytes // decompositionMapping = 32 bytes // category + combining + bidirectional + decompositionType + decimal + digit + mirrored + lowercase + uppercase + titlecase = 20 bytes // 2 + 1 + 1 + 1 + 1 + 1 + 1 + 4 + 4 + 4 = 20 bytes struct Character { /// (1) When a string value not enclosed in &lt;angle brackets> occurs in this field, /// it specifies the character's Name property value, /// which matches exactly the name published in the code charts. /// The Name property value for most ideographic characters and for Hangul syllables /// is derived instead by various rules. /// See *Section 4.8, Name* in *[Unicode]* for a full specification of those rules. /// Strings enclosed in &lt;angle brackets> in this field either provide /// label information used in the name derivation rules, /// or—in the case of characters which have a null string as their Name property value, /// such as control characters—provide other information about their code point type. /// /// [Unicode]: http://unicode.org/reports/tr41/tr41-21.html#Unicode string name; /// (8) If the character has the property value `Numeric_Type=Numeric`, /// then the `Numeric_Value` of that character is represented with a positive or negative /// integer or rational number in this field, and fields 6 and 7 are null. /// This includes fractions such as, for example, "1/5" for U+2155 VULGAR FRACTION ONE FIFTH. /// /// Some characters have these properties based on values from the Unihan data files. /// See [`Numeric_Type`, Han]. /// /// [`Numeric_Type`, Han]: http://unicode.org/reports/tr44/#Numeric_Type_Han RationalNumber numeric; /// (5) This is one half of the field containing both the values /// [`Decomposition_Type` and `Decomposition_Mapping`], with the type in angle brackets. /// The decomposition mappings exactly match the decomposition mappings /// published with the character names in the Unicode Standard. /// For more information, see [Character Decomposition Mappings][Decomposition Mappings]. /// /// [Decomposition Mappings]: http://unicode.org/reports/tr44/#Character_Decomposition_Mappings // The default value of the Decomposition_Mapping property is the code point of the character itself uint32[] decompositionMapping; /// (2) This is a useful breakdown into various character types which /// can be used as a default categorization in implementations. /// For the property values, see [General_Category Values]. /// /// [General_Category Values]: http://unicode.org/reports/tr44/#General_Category_Values bytes2 category; /// (3) The classes used for the Canonical Ordering Algorithm in the Unicode Standard. /// This property could be considered either an enumerated property or a numeric property: /// the principal use of the property is in terms of the numeric values. /// For the property value names associated with different numeric values, /// see [DerivedCombiningClass.txt] and [Canonical_Combining_Class Values][CCC Values]. /// /// [DerivedCombiningClass.txt]: http://unicode.org/reports/tr44/#DerivedCombiningClass.txt /// [CCC Values]: http://unicode.org/reports/tr44/#Canonical_Combining_Class_Values uint8 combining; /// (4) These are the categories required by the Unicode Bidirectional Algorithm. /// For the property values, see [Bidirectional Class Values]. /// For more information, see Unicode Standard Annex #9, /// "Unicode Bidirectional Algorithm" *[UAX9]*. /// /// The default property values depend on the code point, /// and are explained in DerivedBidiClass.txt /// /// [Bidirectional Class Values]: http://unicode.org/reports/tr44/#Bidi_Class_Values /// [UAX9]: http://unicode.org/reports/tr41/tr41-21.html#UAX9 BidiClass bidirectional; /// (5) This is one half of the field containing both the values /// [`Decomposition_Type` and `Decomposition_Mapping`], with the type in angle brackets. /// The decomposition mappings exactly match the decomposition mappings /// published with the character names in the Unicode Standard. /// For more information, see [Character Decomposition Mappings][Decomposition Mappings]. /// /// [Decomposition Mappings]: http://unicode.org/reports/tr44/#Character_Decomposition_Mappings DecompositionType decompositionType; /// (6) If the character has the property value `Numeric_Type=Decimal`, /// then the `Numeric_Value` of that digit is represented with an integer value /// (limited to the range 0..9) in fields 6, 7, and 8. /// Characters with the property value `Numeric_Type=Decimal` are restricted to digits /// which can be used in a decimal radix positional numeral system and /// which are encoded in the standard in a contiguous ascending range 0..9. /// See the discussion of *decimal digits* in *Chapter 4, Character Properties* in *[Unicode]*. /// /// [Unicode]: http://unicode.org/reports/tr41/tr41-21.html#Unicode uint8 decimal; /// (7) If the character has the property value `Numeric_Type=Digit`, /// then the `Numeric_Value` of that digit is represented with an integer value /// (limited to the range 0..9) in fields 7 and 8, and field 6 is null. /// This covers digits that need special handling, such as the compatibility superscript digits. /// /// Starting with Unicode 6.3.0, /// no newly encoded numeric characters will be given `Numeric_Type=Digit`, /// nor will existing characters with `Numeric_Type=Numeric` be changed to `Numeric_Type=Digit`. /// The distinction between those two types is not considered useful. uint8 digit; /// (9) If the character is a "mirrored" character in bidirectional text, /// this field has the value "Y" [true]; otherwise "N" [false]. /// See *Section 4.7, Bidi Mirrored* of *[Unicode]*. /// *Do not confuse this with the [`Bidi_Mirroring_Glyph`] property*. /// /// [Unicode]: http://unicode.org/reports/tr41/tr41-21.html#Unicode /// [`Bidi_Mirroring_Glyph`]: http://unicode.org/reports/tr44/#Bidi_Mirroring_Glyph bool mirrored; /// (12) Simple uppercase mapping (single character result). /// If a character is part of an alphabet with case distinctions, /// and has a simple uppercase equivalent, then the uppercase equivalent is in this field. /// The simple mappings have a single character result, /// where the full mappings may have multi-character results. /// For more information, see [Case and Case Mapping]. /// /// [Case and Case Mapping]: http://unicode.org/reports/tr44/#Casemapping uint32 uppercase; /// (13) Simple lowercase mapping (single character result). uint32 lowercase; /// (14) Simple titlecase mapping (single character result). uint32 titlecase; } // Mapping from Unicode code point to character properties mapping(uint32 => Character) public characters; uint8 public constant MAX_BYTES = 4; // simple check if a string could be a valid character function canBeCharacter(string calldata _char) private pure { require( bytes(_char).length <= MAX_BYTES, "a character must be less than or equal to four bytes" ); } function _exists(string memory _name) private pure returns (bool) { return bytes(_name).length > 0; } function mustExist(Character memory _char) private pure { require(_exists(_char.name), "character does not exist"); } /// @notice Check if `_char` exists in the Unicode database /// @dev All getters will error if a character doesn't exist. /// exists allows you check before getting. /// @param _char The character to check /// @return True if character `_char` is valid and exists function exists(string calldata _char) external view returns (bool) { if (bytes(_char).length > MAX_BYTES) return false; Character memory char = characters[_char.toCodePoint()]; return _exists(char.name); } /// @dev Internal getter for characters and standard validation. It errors if the character doesn't exist. function get(string calldata _char) private view returns (Character memory) { canBeCharacter(_char); Character memory char = characters[_char.toCodePoint()]; // Require the character exists mustExist(char); return char; } /// @notice This is only used by the owner to initialize and update Unicode character database /// @param _codePoint The Unicode code point to set /// @param _data The character data function set(uint32 _codePoint, Character calldata _data) external onlyOwner { // Require name to be non-empty! require(bytes(_data.name).length > 0, "character name must not be empty"); characters[_codePoint] = _data; } /// @notice This is only used by the owner to initialize and update Unicode character database /// @param _codePoints The Unicode code points to set /// @param _data The list of character data to set /// @dev Order matters! Order of _data must match the order of _codePoints function setBatch(uint32[] calldata _codePoints, Character[] calldata _data) external onlyOwner { uint256 len = _codePoints.length; uint256 i; for (i = 0; i < len; i++) { uint32 codePoint = _codePoints[i]; // Require name to be non-empty! require( bytes(_data[i].name).length > 0, "character name must not be empty" ); characters[codePoint] = _data[i]; } } // ------- // Getters // ------- /// @notice Get the Unicode name of `_char` /// @dev All Unicode characters will have a non-empty name /// @param _char The character to get /// @return The Unicode name of `_char` function name(string calldata _char) external view returns (string memory) { return get(_char).name; } /// @notice Get the Unicode general category of `_char` /// @dev See https://www.unicode.org/reports/tr44/#General_Category_Values for possible values /// @param _char The character to get /// @return The Unicode general category of `_char` function category(string calldata _char) external view returns (bytes2) { return get(_char).category; } /// @notice Get the Unicode combining class of `_char` /// @dev See https://www.unicode.org/reports/tr44/#Canonical_Combining_Class_Values for possible values /// @param _char The character to get /// @return The Unicode combining class of `_char` function combining(string calldata _char) external view returns (uint8) { return get(_char).combining; } /// @notice Get the Unicode bidirectional (bidi) class of `_char` /// @dev See https://www.unicode.org/reports/tr44/#Bidi_Class_Values for possible values /// @param _char The character to get /// @return The Unicode bidirectional (bidi) class of `_char` function bidirectional(string calldata _char) external view returns (BidiClass) { return get(_char).bidirectional; } /// @notice Get the Unicode decomposition type of `_char` /// @dev See https://www.unicode.org/reports/tr44/#Decomposition_Type for possible values. /// This can be used to implement the Unicode decomposition algorithm /// @param _char The character to get /// @return The Unicode decomposition type of `_char` function decompositionType(string calldata _char) external view returns (DecompositionType) { return get(_char).decompositionType; } /// @notice Get the Unicode decomposition mapping of `_char` /// @dev This can be used to implement the Unicode decomposition algorithm. /// @param _char The character to get /// @return The Unicode decomposition mapping as an array of code points of `_char` function decompositionMapping(string calldata _char) external view returns (uint32[] memory) { return get(_char).decompositionMapping; } /// @notice Get the Unicode decimal property of `_char` /// @dev This raises an error for characters without a decimal property. Values can only be within 0-9. /// @param _char The character to get /// @return The decimal value of `_char` function decimal(string calldata _char) external view returns (uint8) { Character memory char = get(_char); require( !isNaN(char.decimal), "character does not have a decimal representation" ); return char.decimal; } /// @notice Get the Unicode digit property of `_char` /// @dev This raises an error for characters without a digit property. Values can only be within 0-9. /// @param _char The character to get /// @return The digit value of `_char` function digit(string calldata _char) external view returns (uint8) { Character memory char = get(_char); require( !isNaN(char.digit), "character does not have a digit representation" ); return char.digit; } /// @notice Get the Unicode numeric property of `_char` /// @dev This raises an error for characters without a numeric property. /// @param _char The character to get /// @return The RationalNumber struct for the numeric property of `_char` function numeric(string calldata _char) external view returns (RationalNumber memory) { Character memory char = get(_char); require( !isNaN(char.numeric), "character does not have a numeric representation" ); return char.numeric; } /// @notice If `_char` is a "mirrored" character in bidirectional text /// @dev Do not confuse this with the Bidi_Mirroring_Glyph property /// @param _char The character to get /// @return True if `_char` is a "mirrored" character in bidirectional text function mirrored(string calldata _char) external view returns (bool) { return get(_char).mirrored; } /// @notice Get the simple uppercase value for a character if it exists /// @dev This does not handle Special Casing. Contributions to fix this are welcome! /// @param _char the character to uppercase /// @return The corresponding uppercase character function uppercase(string calldata _char) public view returns (string memory) { uint32 codePoint = get(_char).uppercase; // default to same character if (codePoint == 0) return _char; return codePoint.UTF8Encode(); } /// @notice Get the simple lowercase value for a character if it exists /// @dev This does not handle Special Casing. Contributions to fix this are welcome! /// @param _char the character to lowercase /// @return The corresponding lowercase character function lowercase(string calldata _char) external view returns (string memory) { uint32 codePoint = get(_char).lowercase; // default to the same character if (codePoint == 0) return _char; return codePoint.UTF8Encode(); } /// @notice Get the simple titlecase value for a character if it exists /// @dev This does not handle Special Casing. Contributions to fix this are welcome! /// @param _char the character to titlecase /// @return The corresponding titlecase character function titlecase(string calldata _char) external view returns (string memory) { uint32 codePoint = get(_char).titlecase; // default to uppercase if (codePoint == 0) return uppercase(_char); return codePoint.UTF8Encode(); } // Derived Properties /** 6= decimal 7= digit 8= numeric Numeric_Type is extracted as follows. If fields 6, 7, and 8 in UnicodeData.txt are all non-empty, then Numeric_Type=Decimal. Otherwise, if fields 7 and 8 are both non-empty, then Numeric_Type=Digit. Otherwise, if field 8 is non-empty, then Numeric_Type=Numeric. For characters listed in the Unihan data files, Numeric_Type=Numeric for characters that have kPrimaryNumeric, kAccountingNumeric, or kOtherNumeric tags. The default value is Numeric_Type=None. */ enum NumericType { NONE, DECIMAL, DIGIT, NUMERIC } /// @notice Get the numeric type for `_char` /// @dev This does not handle derived numeric types from the Unicode Han Database. Contributions to fix this are welcome! /// https://www.unicode.org/Public/UNIDATA/extracted/DerivedNumericType.txt /// @param _char the character to get /// @return The numeric type for the character function numericType(string calldata _char) external view returns (NumericType) { Character memory char = get(_char); bool hasDecimal = !isNaN(char.decimal); bool hasDigit = !isNaN(char.digit); bool hasNumeric = !isNaN(char.numeric); if (hasDecimal && hasDigit && hasNumeric) return NumericType.DECIMAL; if (hasDigit && hasNumeric) return NumericType.DIGIT; if (hasNumeric) return NumericType.NUMERIC; return NumericType.NONE; } /// @notice Get the numeric value for `_char` /// @dev This does not handle derived numeric types from the Unicode Han Database and is currently identical to the numeric property. Contributions to fix this are welcome! /// https://www.unicode.org/Public/UNIDATA/extracted/DerivedNumericValues.txt /// @param _char the character to get /// @return The numeric value for the character function numericValue(string calldata _char) external view returns (RationalNumber memory) { Character memory char = get(_char); require(!isNaN(char.numeric), "character does not have a numeric value"); return char.numeric; } /// @notice Check if `_char` is lowercase /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is lowercase function isLowercase(string calldata _char) public view returns (bool) { Character memory char = get(_char); return char.category == "Ll"; } /// @notice Check if `_char` is uppercase /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is uppercase function isUppercase(string calldata _char) public view returns (bool) { Character memory char = get(_char); return char.category == "Lu"; } /// @notice Check if `_char` is titlecase /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is titlecase function isTitlecase(string calldata _char) public view returns (bool) { Character memory char = get(_char); return char.category == "Lt"; } /// @notice Check if `_char` is cased /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is cased function isCased(string calldata _char) public view returns (bool) { return isLowercase(_char) || isUppercase(_char) || isTitlecase(_char); } /// @notice Check if `_char` is a letter /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a letter function isLetter(string calldata _char) public view returns (bool) { Character memory char = get(_char); return char.category[0] == "L"; } /// @notice Check if `_char` is a alphabetic /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a alphabetic function isAlphabetic(string calldata _char) external view returns (bool) { Character memory char = get(_char); return isLetter(_char) || char.category == "Nl"; } /// @notice Check if `_char` is a number /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a number function isNumber(string calldata _char) public view returns (bool) { Character memory char = get(_char); return char.category[0] == "N"; } /// @notice Check if `_char` is a alphanumeric /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a alphanumeric function isAlphanumeric(string calldata _char) external view returns (bool) { return isLetter(_char) || isNumber(_char); } /// @notice Check if `_char` is a mathematic symbol /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a mathematic symbol function isMath(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category == "Sm"; } /// @notice Check if `_char` is a symbol /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a symbol function isSymbol(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category[0] == "S"; } /// @notice Check if `_char` is a mark /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a mark function isMark(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category[0] == "M"; } /// @notice Check if `_char` is punctuation /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is punctuation function isPunctuation(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category[0] == "P"; } /// @notice Check if `_char` is a separator (whitespace) /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is a separator (whitespace) function isSeparator(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category[0] == "Z"; } /// @notice Check if `_char` is in the 'Other' category /// @dev This is only for a single Unicode character not entire strings /// @param _char the character to get /// @return True if the character is in the 'Other' category function isOther(string calldata _char) external view returns (bool) { Character memory char = get(_char); return char.category[0] == "C"; } }
This is only used by the owner to initialize and update Unicode character database _codePoints The Unicode code points to set _data The list of character data to set Order matters! Order of _data must match the order of _codePoints Require name to be non-empty!
function setBatch(uint32[] calldata _codePoints, Character[] calldata _data) external onlyOwner { uint256 len = _codePoints.length; uint256 i; for (i = 0; i < len; i++) { uint32 codePoint = _codePoints[i]; require( bytes(_data[i].name).length > 0, "character name must not be empty" ); characters[codePoint] = _data[i]; } }
953,361
./partial_match/42/0xDf5F7C65437ccEbAeF737374D21346Ab7549f1dF/sources/AugurLite.sol
Do nothing if we haven't properly set up the delegator to delegate calls0x40 is the address where the next free memory slot is stored in Solidity new "memory end" including padding. The bitwise operations here ensure we get rounded up to the nearest 32 byte boundary Update the pointer at 0x40 to point at new free memory location so any theoretical allocation doesn't stomp our memory in this call Copy method signature and parameters of this call into memory Call the actual method via delegation 0 == it threw, so we revert If the call succeeded return the return data from the delegate call Update the pointer at 0x40 again to point at new free memory location so any theoretical allocation doesn't stomp our memory in this call
function() external payable { if (controllerLookupName == 0) { return; } assembly { let _calldataMemoryOffset := mload(0x40) let _size := and(add(calldatasize, 0x1f), not(0x1f)) mstore(0x40, add(_calldataMemoryOffset, _size)) calldatacopy(_calldataMemoryOffset, 0x0, calldatasize) let _retval := delegatecall(gas, _target, _calldataMemoryOffset, calldatasize, 0, 0) switch _retval case 0 { revert(0,0) let _returndataMemoryOffset := mload(0x40) mstore(0x40, add(_returndataMemoryOffset, returndatasize)) returndatacopy(_returndataMemoryOffset, 0x0, returndatasize) return(_returndataMemoryOffset, returndatasize) } } }
3,379,860
/** *Submitted for verification at Etherscan.io on 2021-12-11 */ // SPDX-License-Identifier: AGPL-3.0-or-later // File: interfaces/IExodusAuthority.sol pragma solidity =0.7.5; interface IExodusAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately); event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately); event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GovernorPulled(address indexed from, address indexed to); event GuardianPulled(address indexed from, address indexed to); event PolicyPulled(address indexed from, address indexed to); event VaultPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian() external view returns (address); function policy() external view returns (address); function vault() external view returns (address); } // File: types/ExodusAccessControlled.sol pragma solidity >=0.7.5; abstract contract ExodusAccessControlled { /* ========== EVENTS ========== */ event AuthorityUpdated(IExodusAuthority indexed authority); string UNAUTHORIZED = "UNAUTHORIZED"; // save gas /* ========== STATE VARIABLES ========== */ IExodusAuthority public authority; /* ========== Constructor ========== */ constructor(IExodusAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== MODIFIERS ========== */ modifier onlyGovernor() { require(msg.sender == authority.governor(), UNAUTHORIZED); _; } modifier onlyGuardian() { require(msg.sender == authority.guardian(), UNAUTHORIZED); _; } modifier onlyPolicy() { require(msg.sender == authority.policy(), UNAUTHORIZED); _; } modifier onlyVault() { require(msg.sender == authority.vault(), UNAUTHORIZED); _; } /* ========== GOV ONLY ========== */ function setAuthority(IExodusAuthority _newAuthority) external onlyGovernor { authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } } // File: interfaces/ITreasury.sol pragma solidity >=0.7.5; interface ITreasury { function deposit( uint256 _amount, address _token, uint256 _profit ) external returns (uint256); function withdraw(uint256 _amount, address _token) external; function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_); function mint(address _recipient, uint256 _amount) external; function manage(address _token, uint256 _amount) external; function incurDebt(uint256 amount_, address token_) external; function repayDebtWithReserve(uint256 amount_, address token_) external; function excessReserves() external view returns (uint256); function baseSupply() external view returns (uint256); } // File: interfaces/IBondingCalculator.sol pragma solidity >=0.7.5; interface IBondingCalculator { function markdown( address _LP ) external view returns ( uint ); function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } // File: interfaces/IOwnable.sol pragma solidity >=0.7.5; interface IOwnable { function owner() external view returns (address); function renounceManagement() external; function pushManagement( address newOwner_ ) external; function pullManagement() external; } // File: interfaces/IERC20.sol pragma solidity >=0.7.5; 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: interfaces/IsOHM.sol pragma solidity >=0.7.5; interface IsEXO is IERC20 { function rebase( uint256 exoProfit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); function toG(uint amount) external view returns (uint); function fromG(uint amount) external view returns (uint); function changeDebt( uint256 amount, address debtor, bool add ) external; function debtBalances(address _address) external view returns (uint256); } // File: interfaces/IEXO.sol pragma solidity >=0.7.5; interface IEXO is IERC20 { function mint(address account_, uint256 amount_) external; function burn(uint256 amount) external; function burnFrom(address account_, uint256 amount_) external; } // File: interfaces/IERC20Metadata.sol pragma solidity >=0.7.5; interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: libraries/SafeERC20.sol pragma solidity >=0.7.5; /// @notice Safe IERC20 and ETH transfer library that safely handles missing return values. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol) /// Taken from Solmate library SafeERC20 { function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED"); } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transfer.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); } function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.approve.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED"); } function safeTransferETH(address to, uint256 amount) internal { (bool success, ) = to.call{value: amount}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } } // File: libraries/SafeMath.sol pragma solidity ^0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation 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; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File: Treasury.sol pragma solidity ^0.7.5; contract ExodusTreasury is ExodusAccessControlled, ITreasury { /* ========== DEPENDENCIES ========== */ using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== EVENTS ========== */ event Deposit(address indexed token, uint256 amount, uint256 value); event Withdrawal(address indexed token, uint256 amount, uint256 value); event CreateDebt(address indexed debtor, address indexed token, uint256 amount, uint256 value); event RepayDebt(address indexed debtor, address indexed token, uint256 amount, uint256 value); event Managed(address indexed token, uint256 amount); event ReservesAudited(uint256 indexed totalReserves); event Minted(address indexed caller, address indexed recipient, uint256 amount); event PermissionQueued(STATUS indexed status, address queued); event Permissioned(address addr, STATUS indexed status, bool result); /* ========== DATA STRUCTURES ========== */ enum STATUS { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, RESERVEDEBTOR, REWARDMANAGER, SEXO, EXODEBTOR } struct Queue { STATUS managing; address toPermit; address calculator; uint256 timelockEnd; bool nullify; bool executed; } /* ========== STATE VARIABLES ========== */ IEXO public immutable EXO; IsEXO public sEXO; mapping(STATUS => address[]) public registry; mapping(STATUS => mapping(address => bool)) public permissions; mapping(address => address) public bondCalculator; mapping(address => uint256) public debtLimit; uint256 public totalReserves; uint256 public totalDebt; uint256 public exoDebt; Queue[] public permissionQueue; uint256 public immutable blocksNeededForQueue; bool public timelockEnabled; bool public initialized; uint256 public onChainGovernanceTimelock; string internal notAccepted = "Treasury: not accepted"; string internal notApproved = "Treasury: not approved"; string internal invalidToken = "Treasury: invalid token"; string internal insufficientReserves = "Treasury: insufficient reserves"; /* ========== CONSTRUCTOR ========== */ constructor( address _exo, uint256 _timelock, address _authority ) ExodusAccessControlled(IExodusAuthority(_authority)) { require(_exo != address(0), "Zero address: EXO"); EXO = IEXO(_exo); timelockEnabled = false; initialized = false; blocksNeededForQueue = _timelock; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice allow approved address to deposit an asset for OHM * @param _amount uint256 * @param _token address * @param _profit uint256 * @return send_ uint256 */ function deposit( uint256 _amount, address _token, uint256 _profit ) external override returns (uint256 send_) { if (permissions[STATUS.RESERVETOKEN][_token]) { require(permissions[STATUS.RESERVEDEPOSITOR][msg.sender], notApproved); } else if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { require(permissions[STATUS.LIQUIDITYDEPOSITOR][msg.sender], notApproved); } else { revert(invalidToken); } IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); // mint EXO needed and store amount of rewards for distribution send_ = value.sub(_profit); EXO.mint(msg.sender, send_); totalReserves = totalReserves.add(value); emit Deposit(_token, _amount, value); } /** * @notice allow approved address to burn EXO for reserves * @param _amount uint256 * @param _token address */ function withdraw(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); // Only reserves can be used for redemptions require(permissions[STATUS.RESERVESPENDER][msg.sender], notApproved); uint256 value = tokenValue(_token, _amount); EXO.burnFrom(msg.sender, value); totalReserves = totalReserves.sub(value); IERC20(_token).safeTransfer(msg.sender, _amount); emit Withdrawal(_token, _amount, value); } /** * @notice allow approved address to withdraw assets * @param _token address * @param _amount uint256 */ function manage(address _token, uint256 _amount) external override { if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { require(permissions[STATUS.LIQUIDITYMANAGER][msg.sender], notApproved); } else { require(permissions[STATUS.RESERVEMANAGER][msg.sender], notApproved); } if (permissions[STATUS.RESERVETOKEN][_token] || permissions[STATUS.LIQUIDITYTOKEN][_token]) { uint256 value = tokenValue(_token, _amount); require(value <= excessReserves(), insufficientReserves); totalReserves = totalReserves.sub(value); } IERC20(_token).safeTransfer(msg.sender, _amount); emit Managed(_token, _amount); } /** * @notice mint new EXO using excess reserves * @param _recipient address * @param _amount uint256 */ function mint(address _recipient, uint256 _amount) external override { require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved); require(_amount <= excessReserves(), insufficientReserves); EXO.mint(_recipient, _amount); emit Minted(msg.sender, _recipient, _amount); } /** * DEBT: The debt functions allow approved addresses to borrow treasury assets * or EXO from the treasury, using sEXO as collateral. This might allow an * sEXO holder to provide EXO liquidity without taking on the opportunity cost * of unstaking, or alter their backing without imposing risk onto the treasury. * Many of these use cases are yet to be defined, but they appear promising. * However, we urge the community to think critically and move slowly upon * proposals to acquire these permissions. */ /** * @notice allow approved address to borrow reserves * @param _amount uint256 * @param _token address */ function incurDebt(uint256 _amount, address _token) external override { uint256 value; if (_token == address(EXO)) { require(permissions[STATUS.EXODEBTOR][msg.sender], notApproved); value = _amount; } else { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); value = tokenValue(_token, _amount); } require(value != 0, invalidToken); sEXO.changeDebt(value, msg.sender, true); require(sEXO.debtBalances(msg.sender) <= debtLimit[msg.sender], "Treasury: exceeds limit"); totalDebt = totalDebt.add(value); if (_token == address(EXO)) { EXO.mint(msg.sender, value); exoDebt = exoDebt.add(value); } else { totalReserves = totalReserves.sub(value); IERC20(_token).safeTransfer(msg.sender, _amount); } emit CreateDebt(msg.sender, _token, _amount, value); } /** * @notice allow approved address to repay borrowed reserves with reserves * @param _amount uint256 * @param _token address */ function repayDebtWithReserve(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); sEXO.changeDebt(value, msg.sender, false); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit RepayDebt(msg.sender, _token, _amount, value); } /** * @notice allow approved address to repay borrowed reserves with EXO * @param _amount uint256 */ function repayDebtWithEXO(uint256 _amount) external { require(permissions[STATUS.RESERVEDEBTOR][msg.sender] || permissions[STATUS.EXODEBTOR][msg.sender], notApproved); EXO.burnFrom(msg.sender, _amount); sEXO.changeDebt(_amount, msg.sender, false); totalDebt = totalDebt.sub(_amount); exoDebt = exoDebt.sub(_amount); emit RepayDebt(msg.sender, address(EXO), _amount, _amount); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** * @notice takes inventory of all tracked assets * @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyGovernor { uint256 reserves; address[] memory reserveToken = registry[STATUS.RESERVETOKEN]; for (uint256 i = 0; i < reserveToken.length; i++) { if (permissions[STATUS.RESERVETOKEN][reserveToken[i]]) { reserves = reserves.add(tokenValue(reserveToken[i], IERC20(reserveToken[i]).balanceOf(address(this)))); } } address[] memory liquidityToken = registry[STATUS.LIQUIDITYTOKEN]; for (uint256 i = 0; i < liquidityToken.length; i++) { if (permissions[STATUS.LIQUIDITYTOKEN][liquidityToken[i]]) { reserves = reserves.add(tokenValue(liquidityToken[i], IERC20(liquidityToken[i]).balanceOf(address(this)))); } } totalReserves = reserves; emit ReservesAudited(reserves); } /** * @notice set max debt for address * @param _address address * @param _limit uint256 */ function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; } /** * @notice enable permission from queue * @param _status STATUS * @param _address address * @param _calculator address */ function enable( STATUS _status, address _address, address _calculator ) external onlyGovernor { require(timelockEnabled == false, "Use queueTimelock"); if (_status == STATUS.SEXO) { sEXO = IsEXO(_address); } else { permissions[_status][_address] = true; if (_status == STATUS.LIQUIDITYTOKEN) { bondCalculator[_address] = _calculator; } (bool registered, ) = indexInRegistry(_address, _status); if (!registered) { registry[_status].push(_address); if (_status == STATUS.LIQUIDITYTOKEN || _status == STATUS.RESERVETOKEN) { (bool reg, uint256 index) = indexInRegistry(_address, _status); if (reg) { delete registry[_status][index]; } } } } emit Permissioned(_address, _status, true); } /** * @notice disable permission from address * @param _status STATUS * @param _toDisable address */ function disable(STATUS _status, address _toDisable) external { require(msg.sender == authority.governor() || msg.sender == authority.guardian(), "Only governor or guardian"); permissions[_status][_toDisable] = false; emit Permissioned(_toDisable, _status, false); } /** * @notice check if registry contains address * @return (bool, uint256) */ function indexInRegistry(address _address, STATUS _status) public view returns (bool, uint256) { address[] memory entries = registry[_status]; for (uint256 i = 0; i < entries.length; i++) { if (_address == entries[i]) { return (true, i); } } return (false, 0); } /* ========== TIMELOCKED FUNCTIONS ========== */ // functions are used prior to enabling on-chain governance /** * @notice queue address to receive permission * @param _status STATUS * @param _address address * @param _calculator address */ function queueTimelock( STATUS _status, address _address, address _calculator ) external onlyGovernor { require(_address != address(0)); require(timelockEnabled == true, "Timelock is disabled, use enable"); uint256 timelock = block.number.add(blocksNeededForQueue); if (_status == STATUS.RESERVEMANAGER || _status == STATUS.LIQUIDITYMANAGER) { timelock = block.number.add(blocksNeededForQueue.mul(2)); } permissionQueue.push( Queue({managing: _status, toPermit: _address, calculator: _calculator, timelockEnd: timelock, nullify: false, executed: false}) ); emit PermissionQueued(_status, _address); } /** * @notice enable queued permission * @param _index uint256 */ function execute(uint256 _index) external { require(timelockEnabled == true, "Timelock is disabled, use enable"); Queue memory info = permissionQueue[_index]; require(!info.nullify, "Action has been nullified"); require(!info.executed, "Action has already been executed"); require(block.number >= info.timelockEnd, "Timelock not complete"); if (info.managing == STATUS.SEXO) { // 9 sEXO = IsEXO(info.toPermit); } else { permissions[info.managing][info.toPermit] = true; if (info.managing == STATUS.LIQUIDITYTOKEN) { bondCalculator[info.toPermit] = info.calculator; } (bool registered, ) = indexInRegistry(info.toPermit, info.managing); if (!registered) { registry[info.managing].push(info.toPermit); if (info.managing == STATUS.LIQUIDITYTOKEN) { (bool reg, uint256 index) = indexInRegistry(info.toPermit, STATUS.RESERVETOKEN); if (reg) { delete registry[STATUS.RESERVETOKEN][index]; } } else if (info.managing == STATUS.RESERVETOKEN) { (bool reg, uint256 index) = indexInRegistry(info.toPermit, STATUS.LIQUIDITYTOKEN); if (reg) { delete registry[STATUS.LIQUIDITYTOKEN][index]; } } } } permissionQueue[_index].executed = true; emit Permissioned(info.toPermit, info.managing, true); } /** * @notice cancel timelocked action * @param _index uint256 */ function nullify(uint256 _index) external onlyGovernor { permissionQueue[_index].nullify = true; } /** * @notice disables timelocked functions */ function disableTimelock() external onlyGovernor { require(timelockEnabled == true, "timelock already disabled"); if (onChainGovernanceTimelock != 0 && onChainGovernanceTimelock <= block.number) { timelockEnabled = false; } else { onChainGovernanceTimelock = block.number.add(blocksNeededForQueue.mul(7)); // 7-day timelock } } /** * @notice enables timelocks after initilization */ function initialize() external onlyGovernor { require(initialized == false, "Already initialized"); timelockEnabled = true; initialized = true; } /* ========== VIEW FUNCTIONS ========== */ /** * @notice returns excess reserves not backing tokens * @return uint */ function excessReserves() public view override returns (uint256) { return totalReserves.sub(EXO.totalSupply().sub(totalDebt)); } /** * @notice returns EXO valuation of asset * @param _token address * @param _amount uint256 * @return value_ uint256 */ function tokenValue(address _token, uint256 _amount) public view override returns (uint256 value_) { value_ = _amount.mul(10**IERC20Metadata(address(EXO)).decimals()).div(10**IERC20Metadata(_token).decimals()); if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { value_ = IBondingCalculator(bondCalculator[_token]).valuation(_token, _amount); } } /** * @notice returns supply metric that cannot be manipulated by debt * @dev use this any time you need to query supply * @return uint256 */ function baseSupply() external view override returns (uint256) { return EXO.totalSupply() - exoDebt; } }
allow approved address to repay borrowed reserves with reserves _amount uint256 _token address/
function repayDebtWithReserve(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); sEXO.changeDebt(value, msg.sender, false); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit RepayDebt(msg.sender, _token, _amount, value); }
2,481,090
./full_match/4/0x8904e7a9F49B8C6f9AAB7267A4A2e10e528636F4/sources/contracts/TestUniswapFlashSwap.sol
address token0 = IUniswapV2Pair(pair).token0(); address token1 = IUniswapV2Pair(pair).token1();uint amount0Out = t1 == token0 ? _amount : 0; uint amount1Out = t1 == token1 ? _amount : 0; need to pass some data to trigger uniswapV2Call
function testFlashSwap() external { address pair = IUniswapV2Factory(FACTORY).getPair(t2, t1); require(pair != address(0), "!pair"); bytes memory data = abi.encode(t1, 1000); IUniswapV2Pair(pair).swap(1000, 0, address(this), data); }
12,306,832
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {GammaOperator} from "./GammaOperator.sol"; import {IGammaRedeemerV1} from "./interfaces/IGammaRedeemerV1.sol"; import {IPokeMe} from "./interfaces/IPokeMe.sol"; import {ITaskTreasury} from "./interfaces/ITaskTreasury.sol"; import {IResolver} from "./interfaces/IResolver.sol"; /// @author Willy Shen /// @title Gamma Automatic Redeemer /// @notice An automatic redeemer for Gmma otoken holders and writers contract GammaRedeemerV1 is IGammaRedeemerV1, GammaOperator { Order[] public orders; IPokeMe public automator; ITaskTreasury public automatorTreasury; bool public isAutomatorEnabled; // fee in 1/10.000: 1% = 100, 0.01% = 1 uint256 public redeemFee = 50; uint256 public settleFee = 10; /** * @notice only automator or owner */ modifier onlyAuthorized() { require( msg.sender == address(automator) || msg.sender == owner(), "GammaRedeemer::onlyAuthorized: Only automator or owner" ); _; } constructor( address _gammaAddressBook, address _automator, address _automatorTreasury ) GammaOperator(_gammaAddressBook) { automator = IPokeMe(_automator); automatorTreasury = ITaskTreasury(_automatorTreasury); isAutomatorEnabled = false; } function startAutomator(address _resolver) public onlyOwner { require(!isAutomatorEnabled); isAutomatorEnabled = true; automator.createTask( address(this), bytes4(keccak256("processOrders(uint256[])")), _resolver, abi.encodeWithSelector(IResolver.getProcessableOrders.selector) ); } function stopAutomator() public onlyOwner { require(isAutomatorEnabled); isAutomatorEnabled = false; automator.cancelTask( automator.getTaskId( address(this), address(this), bytes4(keccak256("processOrders(uint256[])")) ) ); } /** * @notice create automation order * @param _otoken the address of otoken (only holders) * @param _amount amount of otoken (only holders) * @param _vaultId the id of specific vault to settle (only writers) */ function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) public override { uint256 fee; bool isSeller; if (_otoken == address(0)) { require( _amount == 0, "GammaRedeemer::createOrder: Amount must be 0 when creating settlement order" ); fee = settleFee; isSeller = true; } else { require( isWhitelistedOtoken(_otoken), "GammaRedeemer::createOrder: Otoken not whitelisted" ); fee = redeemFee; } uint256 orderId = orders.length; Order memory order; order.owner = msg.sender; order.otoken = _otoken; order.amount = _amount; order.vaultId = _vaultId; order.isSeller = isSeller; order.fee = fee; orders.push(order); emit OrderCreated(orderId, msg.sender, _otoken); } /** * @notice cancel automation order * @param _orderId the id of specific order to be cancelled */ function cancelOrder(uint256 _orderId) public override { Order storage order = orders[_orderId]; require( order.owner == msg.sender, "GammaRedeemer::cancelOrder: Sender is not order owner" ); require( !order.finished, "GammaRedeemer::cancelOrder: Order is already finished" ); order.finished = true; emit OrderFinished(_orderId, true); } /** * @notice check if processing order is profitable * @param _orderId the id of specific order to be processed * @return true if settling vault / redeeming returns more than 0 amount */ function shouldProcessOrder(uint256 _orderId) public view override returns (bool) { Order memory order = orders[_orderId]; if (order.finished) return false; if (order.isSeller) { bool shouldSettle = shouldSettleVault(order.owner, order.vaultId); if (!shouldSettle) return false; } else { bool shouldRedeem = shouldRedeemOtoken( order.owner, order.otoken, order.amount ); if (!shouldRedeem) return false; } return true; } /** * @notice process an order * @dev only automator allowed * @param _orderId the id of specific order to process */ function processOrder(uint256 _orderId) public override onlyAuthorized { Order storage order = orders[_orderId]; require( !order.finished, "GammaRedeemer::processOrder: Order is already finished" ); require( shouldProcessOrder(_orderId), "GammaRedeemer::processOrder: Order should not be processed" ); order.finished = true; if (order.isSeller) { settleVault(order.owner, order.vaultId, order.fee); } else { redeemOtoken(order.owner, order.otoken, order.amount, order.fee); } emit OrderFinished(_orderId, false); } /** * @notice process multiple orders * @param _orderIds array of order ids to process */ function processOrders(uint256[] calldata _orderIds) public { for (uint256 i = 0; i < _orderIds.length; i++) { processOrder(_orderIds[i]); } } /** * @notice withdraw funds from automator * @param _token address of token to withdraw * @param _amount amount of token to withdraw */ function withdrawFund(address _token, uint256 _amount) public onlyOwner { automatorTreasury.withdrawFunds(payable(this), _token, _amount); } function setAutomator(address _automator) public onlyOwner { automator = IPokeMe(_automator); } function setAutomatorTreasury(address _automatorTreasury) public onlyOwner { automatorTreasury = ITaskTreasury(_automatorTreasury); } function setRedeemFee(uint256 _redeemFee) public onlyOwner { redeemFee = _redeemFee; } function setSettleFee(uint256 _settleFee) public onlyOwner { settleFee = _settleFee; } function getOrdersLength() public view override returns (uint256) { return orders.length; } function getOrders() public view override returns (Order[] memory) { return orders; } function getOrder(uint256 _orderId) public view override returns (Order memory) { return orders[_orderId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {IAddressBook} from "./interfaces/IAddressBook.sol"; import {IGammaController} from "./interfaces/IGammaController.sol"; import {IWhitelist} from "./interfaces/IWhitelist.sol"; import {IMarginCalculator} from "./interfaces/IMarginCalculator.sol"; import {Actions} from "./external/OpynActions.sol"; import {MarginVault} from "./external/OpynVault.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IOtoken} from "./interfaces/IOtoken.sol"; /// @author Willy Shen /// @title Gamma Operator /// @notice Opyn Gamma protocol adapter for redeeming otokens and settling vaults contract GammaOperator is Ownable { using SafeERC20 for IERC20; // Gamma Protocol contracts IAddressBook public addressBook; IGammaController public controller; IWhitelist public whitelist; IMarginCalculator public calculator; /** * @dev fetch Gamma contracts from address book * @param _addressBook Gamma Address Book address */ constructor(address _addressBook) { setAddressBook(_addressBook); refreshConfig(); } /** * @notice redeem otoken on behalf of user * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @param _fee fee in 1/10.000 */ function redeemOtoken( address _owner, address _otoken, uint256 _amount, uint256 _fee ) internal { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); IERC20(_otoken).safeTransferFrom(_owner, address(this), actualAmount); Actions.ActionArgs memory action; action.actionType = Actions.ActionType.Redeem; action.secondAddress = address(this); action.asset = _otoken; action.amount = _amount; Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; IERC20 collateral = IERC20(IOtoken(_otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice settle vault on behalf of user * @param _owner owner address * @param _vaultId vaultId to settle * @param _fee fee in 1/10.000 */ function settleVault( address _owner, uint256 _vaultId, uint256 _fee ) internal { Actions.ActionArgs memory action; action.actionType = Actions.ActionType.SettleVault; action.owner = _owner; action.vaultId = _vaultId; action.secondAddress = address(this); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; (MarginVault.Vault memory vault, , ) = getVaultWithDetails( _owner, _vaultId ); address otoken = getVaultOtoken(vault); IERC20 collateral = IERC20(IOtoken(otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice return if otoken should be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return true if otoken has expired and payout is greater than zero */ function shouldRedeemOtoken( address _owner, address _otoken, uint256 _amount ) public view returns (bool) { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); try this.getRedeemPayout(_otoken, actualAmount) returns ( uint256 payout ) { if (payout == 0) return false; } catch { return false; } return true; } /** * @notice return if vault should be settled * @param _owner owner address * @param _vaultId vaultId to settle * @return true if vault can be settled, contract is operator of owner, * and excess collateral is greater than zero */ function shouldSettleVault(address _owner, uint256 _vaultId) public view returns (bool) { ( MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 payout, bool isValidVault) = getExcessCollateral( vault, typeVault ); if (!isValidVault || payout == 0) return false; return true; } /** * @notice set Gamma Address Book * @param _address Address Book address */ function setAddressBook(address _address) public onlyOwner { require( _address != address(0), "GammaOperator::setAddressBook: Address must not be zero" ); addressBook = IAddressBook(_address); } /** * @notice transfer operator profit * @param _token address token to transfer * @param _amount amount of token to transfer * @param _to transfer destination */ function harvest( address _token, uint256 _amount, address _to ) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { (bool success, ) = _to.call{value: _amount}(""); require(success, "GammaOperator::harvest: ETH transfer failed"); } else { IERC20(_token).safeTransfer(_to, _amount); } } /** * @notice refresh Gamma contracts' addresses */ function refreshConfig() public { address _controller = addressBook.getController(); controller = IGammaController(_controller); address _whitelist = addressBook.getWhitelist(); whitelist = IWhitelist(_whitelist); address _calculator = addressBook.getMarginCalculator(); calculator = IMarginCalculator(_calculator); } /** * @notice get an oToken's payout in the collateral asset * @param _otoken otoken address * @param _amount amount of otoken to redeem */ function getRedeemPayout(address _otoken, uint256 _amount) public view returns (uint256) { return controller.getPayout(_otoken, _amount); } /** * @notice get amount of otoken that can be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return amount of otoken the contract can transferFrom owner */ function getRedeemableAmount( address _owner, address _otoken, uint256 _amount ) public view returns (uint256) { uint256 ownerBalance = IERC20(_otoken).balanceOf(_owner); uint256 allowance = IERC20(_otoken).allowance(_owner, address(this)); uint256 spendable = min(ownerBalance, allowance); return min(_amount, spendable); } /** * @notice return details of a specific vault * @param _owner owner address * @param _vaultId vaultId * @return vault struct and vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return controller.getVaultWithDetails(_owner, _vaultId); } /** * @notice return the otoken from specific vault * @param _vault vault struct * @return otoken address */ function getVaultOtoken(MarginVault.Vault memory _vault) public pure returns (address) { bool hasShort = isNotEmpty(_vault.shortOtokens); bool hasLong = isNotEmpty(_vault.longOtokens); assert(hasShort || hasLong); return hasShort ? _vault.shortOtokens[0] : _vault.longOtokens[0]; } /** * @notice return amount of collateral that can be removed from a vault * @param _vault vault struct * @param _typeVault vault type * @return excess amount and true if excess is greater than zero */ function getExcessCollateral( MarginVault.Vault memory _vault, uint256 _typeVault ) public view returns (uint256, bool) { return calculator.getExcessCollateral(_vault, _typeVault); } /** * @notice return if otoken is ready to be settled * @param _otoken otoken address * @return true if settlement is allowed */ function isSettlementAllowed(address _otoken) public view returns (bool) { return controller.isSettlementAllowed(_otoken); } /** * @notice return if this contract is Gamma operator of an address * @param _owner owner address * @return true if address(this) is operator of _owner */ function isOperatorOf(address _owner) public view returns (bool) { return controller.isOperator(_owner, address(this)); } /** * @notice return if otoken is whitelisted on Gamma * @param _otoken otoken address * @return true if isWhitelistedOtoken returns true for _otoken */ function isWhitelistedOtoken(address _otoken) public view returns (bool) { return whitelist.isWhitelistedOtoken(_otoken); } /** * @param _otoken otoken address * @return true if otoken has expired and settlement is allowed */ function hasExpiredAndSettlementAllowed(address _otoken) public view returns (bool) { bool hasExpired = block.timestamp >= IOtoken(_otoken).expiryTimestamp(); if (!hasExpired) return false; bool isAllowed = isSettlementAllowed(_otoken); if (!isAllowed) return false; return true; } /** * @notice return if specific vault exist * @param _owner owner address * @param _vaultId vaultId to check * @return true if vault exist for owner */ function isValidVaultId(address _owner, uint256 _vaultId) public view returns (bool) { uint256 vaultCounter = controller.getAccountVaultCounter(_owner); return ((_vaultId > 0) && (_vaultId <= vaultCounter)); } /** * @notice return if array is not empty * @param _array array of address to check * @return true if array length is grreater than zero & first element isn't address zero */ function isNotEmpty(address[] memory _array) private pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return the lowest number * @param a first number * @param b second number * @return the lowest uint256 */ function min(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? b : a; } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; interface IGammaRedeemerV1 { struct Order { // address of user address owner; // address of otoken to redeem address otoken; // amount of otoken to redeem uint256 amount; // vaultId of vault to settle uint256 vaultId; // true if settle vault order, else redeem otoken bool isSeller; // convert proceed to ETH, currently unused bool toETH; // fee in 1/10.000 uint256 fee; // true if order is already processed bool finished; } event OrderCreated( uint256 indexed orderId, address indexed owner, address indexed otoken ); event OrderFinished(uint256 indexed orderId, bool indexed cancelled); function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) external; function cancelOrder(uint256 _orderId) external; function shouldProcessOrder(uint256 _orderId) external view returns (bool); function processOrder(uint256 _orderId) external; function getOrdersLength() external view returns (uint256); function getOrders() external view returns (Order[] memory); function getOrder(uint256 _orderId) external view returns (Order memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IPokeMe { function createTask( address _execAddress, bytes4 _execSelector, address _resolverAddress, bytes calldata _resolverData ) external; function cancelTask(bytes32 _taskId) external; // function withdrawFunds(uint256 _amount) external; function getTaskId( address _taskCreator, address _execAddress, bytes4 _selector ) external pure returns (bytes32); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface ITaskTreasury { function withdrawFunds( address payable _receiver, address _token, uint256 _amount ) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IResolver { function getProcessableOrders() external returns (uint256[] memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IAddressBook { function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {Actions} from "../external/OpynActions.sol"; import {MarginVault} from "../external/OpynVault.sol"; interface IGammaController { function operate(Actions.ActionArgs[] memory _actions) external; function isSettlementAllowed(address _otoken) external view returns (bool); function isOperator(address _owner, address _operator) external view returns (bool); function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function getVaultWithDetails(address _owner, uint256 _vaultId) external view returns ( MarginVault.Vault memory, uint256, uint256 ); function getAccountVaultCounter(address _accountOwner) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IWhitelist { function isWhitelistedOtoken(address _otoken) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {MarginVault} from "../external/OpynVault.sol"; interface IMarginCalculator { function getExcessCollateral( MarginVault.Vault calldata _vault, uint256 _vaultType ) external view returns (uint256 netValue, bool isExcess); } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require( _args.actionType == ActionType.OpenVault, "Actions: can only parse arguments for open vault actions" ); require( _args.owner != address(0), "Actions: cannot open vault for an invalid account" ); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require( vaultType < 2, "Actions: cannot open vault with an invalid type" ); return OpenVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType }); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require( _args.actionType == ActionType.MintShortOption, "Actions: can only parse arguments for mint actions" ); require( _args.owner != address(0), "Actions: cannot mint from an invalid account" ); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require( _args.actionType == ActionType.BurnShortOption, "Actions: can only parse arguments for burn actions" ); require( _args.owner != address(0), "Actions: cannot burn from an invalid account" ); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require( _args.owner != address(0), "Actions: cannot deposit to an invalid account" ); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "Actions: can only parse arguments for withdraw actions" ); require( _args.owner != address(0), "Actions: cannot withdraw from an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw to an invalid account" ); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require( _args.actionType == ActionType.Redeem, "Actions: can only parse arguments for redeem actions" ); require( _args.secondAddress != address(0), "Actions: cannot redeem to an invalid account" ); return RedeemArgs({ receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require( _args.actionType == ActionType.SettleVault, "Actions: can only parse arguments for settle vault actions" ); require( _args.owner != address(0), "Actions: cannot settle vault for an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw payout to an invalid account" ); return SettleVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress }); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require( _args.actionType == ActionType.Liquidate, "Actions: can only parse arguments for liquidate action" ); require( _args.owner != address(0), "Actions: cannot liquidate vault for an invalid account owner" ); require( _args.secondAddress != address(0), "Actions: cannot send collateral to an invalid account" ); require( _args.data.length == 32, "Actions: cannot parse liquidate action with no round id" ); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require( _args.actionType == ActionType.Call, "Actions: can only parse arguments for call actions" ); require( _args.secondAddress != address(0), "Actions: target address cannot be address(0)" ); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: UNLICENSED pragma solidity 0.8.0; interface IOtoken { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
parses the passed in action arguments to get the arguments for a deposit action _args general action arguments structure return arguments for a deposit action/
function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require( _args.owner != address(0), "Actions: cannot deposit to an invalid account" ); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); }
27,829
./full_match/5/0x7ea997bFe3f2355b28faad05e7a7C5f77180C43a/sources/contracts/Contract.sol
Transfer DAO tokens from the sender to the contract Wrap Ether into WETH Mint LP tokens and assign them to the sender Transfer DAO tokens from the sender to the contract Transfer SHIB tokens from the sender to the contract Mint LP tokens and assign them to the sender
function addLiquidity(uint256 amount) external { require(amount > 0, "Amount must be greater than zero."); require(balanceOf[msg.sender] >= amount, "Insufficient balance."); if (liquidityAllocation == LiquidityAllocation.WETH) { balanceOf[msg.sender] -= amount; balanceOf[address(this)] += amount; require(success, "WETH deposit failed."); lpTokenSupply += amount; lpTokenBalance[msg.sender] += amount; balanceOf[msg.sender] -= amount; balanceOf[address(this)] += amount; shibToken.safeTransferFrom(msg.sender, address(this), amount); lpTokenSupply += amount; lpTokenBalance[msg.sender] += amount; } }
11,594,768
./full_match/1/0xa6D116F9272fdfb77aCDD8F13Ad81bc44fda3cF4/sources/browser/xRuneGenerator.sol
Set the migrator contract. Can only be called by the owner.
function setMigrator(IGenerator _migrator) public onlyOwner { migrator = _migrator; }
3,866,887
./partial_match/1/0xe1D11161a48d1630201f5Fd292Bf44F0174187FA/sources/IAN.sol
Use 10 to set 1% -- Base 1000 for easier fine adjust
function ownerUpdateBuyFees (uint256 _liquidityFee, uint256 _reliefFee, uint256 _marketingFee) external onlyOwner { buyFee.liquidityFee = _liquidityFee; buyFee.reliefFee = _reliefFee; buyFee.marketingFee = _marketingFee; buyFee.total = buyFee.liquidityFee + buyFee.reliefFee + buyFee.marketingFee; }
3,589,175
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/IIssuer.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/IPynth.sol"; import "./interfaces/IPeriFin.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/IPeriFinState.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/IDelegateApprovals.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IEtherCollateral.sol"; import "./interfaces/IEtherCollateralpUSD.sol"; import "./interfaces/IHasBalance.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ILiquidations.sol"; import "./interfaces/ICollateralManager.sol"; import "./interfaces/IDebtCache.sol"; interface IRewardEscrowV2 { // Views function balanceOf(address account) external view returns (uint); } interface IIssuerInternalDebtCache { function updateCachedPynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external; function updateCachedPynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external; function updateDebtCacheValidity(bool currentlyInvalid) external; function cacheInfo() external view returns ( uint cachedDebt, uint timestamp, bool isInvalid, bool isStale ); } // /contracts/source/contracts/issuer contract Issuer is Owned, MixinSystemSettings, IIssuer { using SafeMath for uint; using SafeDecimalMath for uint; // Available Pynths which can be used with the system IPynth[] public availablePynths; mapping(bytes32 => IPynth) public pynths; mapping(address => bytes32) public pynthsByAddress; /* ========== ENCODED NAMES ========== */ bytes32 internal constant pUSD = "pUSD"; bytes32 internal constant pETH = "pETH"; bytes32 internal constant PERI = "PERI"; // Flexible storage names bytes32 public constant CONTRACT_NAME = "Issuer"; bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent"; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_PYNTHETIX = "PeriFin"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_PYNTHETIXSTATE = "PeriFinState"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral"; bytes32 private constant CONTRACT_ETHERCOLLATERAL_SUSD = "EtherCollateralpUSD"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_PYNTHETIXESCROW = "PeriFinEscrow"; bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations"; bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](13); newAddresses[0] = CONTRACT_PYNTHETIX; newAddresses[1] = CONTRACT_EXCHANGER; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_PYNTHETIXSTATE; newAddresses[4] = CONTRACT_FEEPOOL; newAddresses[5] = CONTRACT_DELEGATEAPPROVALS; newAddresses[6] = CONTRACT_ETHERCOLLATERAL; newAddresses[7] = CONTRACT_ETHERCOLLATERAL_SUSD; newAddresses[8] = CONTRACT_REWARDESCROW_V2; newAddresses[9] = CONTRACT_PYNTHETIXESCROW; newAddresses[10] = CONTRACT_LIQUIDATIONS; newAddresses[11] = CONTRACT_DEBTCACHE; newAddresses[12] = CONTRACT_COLLATERALMANAGER; return combineArrays(existingAddresses, newAddresses); } function perifin() internal view returns (IPeriFin) { return IPeriFin(requireAndGetAddress(CONTRACT_PYNTHETIX)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function perifinState() internal view returns (IPeriFinState) { return IPeriFinState(requireAndGetAddress(CONTRACT_PYNTHETIXSTATE)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function liquidations() internal view returns (ILiquidations) { return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS)); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS)); } function etherCollateral() internal view returns (IEtherCollateral) { return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL)); } function etherCollateralpUSD() internal view returns (IEtherCollateralpUSD) { return IEtherCollateralpUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_SUSD)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function perifinEscrow() internal view returns (IHasBalance) { return IHasBalance(requireAndGetAddress(CONTRACT_PYNTHETIXESCROW)); } function debtCache() internal view returns (IIssuerInternalDebtCache) { return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) { bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0)); for (uint i = 0; i < availablePynths.length; i++) { currencyKeys[i] = pynthsByAddress[address(availablePynths[i])]; } if (withPERI) { currencyKeys[availablePynths.length] = PERI; } return currencyKeys; } function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral) internal view returns (uint totalIssued, bool anyRateIsInvalid) { (uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo(); anyRateIsInvalid = cacheIsInvalid || cacheIsStale; IExchangeRates exRates = exchangeRates(); // Add total issued pynths from non snx collateral back into the total if not excluded if (!excludeCollateral) { // Get the pUSD equivalent amount of all the MC issued pynths. (uint nonSnxDebt, bool invalid) = collateralManager().totalLong(); debt = debt.add(nonSnxDebt); anyRateIsInvalid = anyRateIsInvalid || invalid; // Now add the ether collateral stuff as we are still supporting it. debt = debt.add(etherCollateralpUSD().totalIssuedPynths()); // Add ether collateral pETH (uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH); uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate); debt = debt.add(ethIssuedDebt); anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid; } if (currencyKey == pUSD) { return (debt, anyRateIsInvalid); } (uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey); return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid); } function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey) internal view returns ( uint debtBalance, uint totalSystemValue, bool anyRateIsInvalid ) { IPeriFinState state = perifinState(); // What was their initial debt ownership? (uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer); // What's the total value of the system excluding ETH backed pynths in their requested currency? (totalSystemValue, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, true); // If it's zero, they haven't issued, and they have no debt. // Note: it's more gas intensive to put this check here rather than before _totalIssuedPynths // if they have 0 PERI, but it's a necessary trade-off if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid); // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = state .lastDebtLedgerEntry() .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise( currentDebtOwnership ); // Convert back into 18 decimals (1e18) debtBalance = highPrecisionBalance.preciseDecimalToDecimal(); } function _canBurnPynths(address account) internal view returns (bool) { return now >= _lastIssueEvent(account).add(getMinimumStakeTime()); } function _lastIssueEvent(address account) internal view returns (uint) { // Get the timestamp of the last issue this account made return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account))); } function _remainingIssuablePynths(address _issuer) internal view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt, bool anyRateIsInvalid ) { (alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD); (uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer); maxIssuable = issuable; anyRateIsInvalid = anyRateIsInvalid || isInvalid; if (alreadyIssued >= maxIssuable) { maxIssuable = 0; } else { maxIssuable = maxIssuable.sub(alreadyIssued); } } function _snxToUSD(uint amount, uint snxRate) internal pure returns (uint) { return amount.multiplyDecimalRound(snxRate); } function _usdToSnx(uint amount, uint snxRate) internal pure returns (uint) { return amount.divideDecimalRound(snxRate); } function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) { // What is the value of their PERI balance in pUSD (uint snxRate, bool isInvalid) = exchangeRates().rateAndInvalid(PERI); uint destinationValue = _snxToUSD(_collateral(_issuer), snxRate); // They're allowed to issue up to issuanceRatio of that value return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid); } function _collateralisationRatio(address _issuer) internal view returns (uint, bool) { uint totalOwnedPeriFin = _collateral(_issuer); (uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PERI); // it's more gas intensive to put this check here if they have 0 PERI, but it complies with the interface if (totalOwnedPeriFin == 0) return (0, anyRateIsInvalid); return (debtBalance.divideDecimalRound(totalOwnedPeriFin), anyRateIsInvalid); } function _collateral(address account) internal view returns (uint) { uint balance = IERC20(address(perifin())).balanceOf(account); if (address(perifinEscrow()) != address(0)) { balance = balance.add(perifinEscrow().balanceOf(account)); } if (address(rewardEscrowV2()) != address(0)) { balance = balance.add(rewardEscrowV2().balanceOf(account)); } return balance; } function minimumStakeTime() external view returns (uint) { return getMinimumStakeTime(); } function canBurnPynths(address account) external view returns (bool) { return _canBurnPynths(account); } function availableCurrencyKeys() external view returns (bytes32[] memory) { return _availableCurrencyKeysWithOptionalPERI(false); } function availablePynthCount() external view returns (uint) { return availablePynths.length; } function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) { (, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalPERI(true)); } function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) { (totalIssued, ) = _totalIssuedPynths(currencyKey, excludeEtherCollateral); } function lastIssueEvent(address account) external view returns (uint) { return _lastIssueEvent(account); } function collateralisationRatio(address _issuer) external view returns (uint cratio) { (cratio, ) = _collateralisationRatio(_issuer); } function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid) { return _collateralisationRatio(_issuer); } function collateral(address account) external view returns (uint) { return _collateral(account); } function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) { IPeriFinState state = perifinState(); // What was their initial debt ownership? (uint initialDebtOwnership, ) = state.issuanceData(_issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; (debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey); } function remainingIssuablePynths(address _issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ) { (maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuablePynths(_issuer); } function maxIssuablePynths(address _issuer) external view returns (uint) { (uint maxIssuable, ) = _maxIssuablePynths(_issuer); return maxIssuable; } function transferablePeriFinAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid) { // How many PERI do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed PERI are not transferable. // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 PERI of value would require // 100 PERI to be locked in their wallet to maintain their collateralisation ratio // The locked perifin value can exceed their balance. uint debtBalance; (debtBalance, , anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI); uint lockedPeriFinValue = debtBalance.divideDecimalRound(getIssuanceRatio()); // If we exceed the balance, no PERI are transferable, otherwise the difference is. if (lockedPeriFinValue >= balance) { transferable = 0; } else { transferable = balance.sub(lockedPeriFinValue); } } function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) { uint numKeys = currencyKeys.length; IPynth[] memory addresses = new IPynth[](numKeys); for (uint i = 0; i < numKeys; i++) { addresses[i] = pynths[currencyKeys[i]]; } return addresses; } /* ========== MUTATIVE FUNCTIONS ========== */ function _addPynth(IPynth pynth) internal { bytes32 currencyKey = pynth.currencyKey(); require(pynths[currencyKey] == IPynth(0), "Pynth exists"); require(pynthsByAddress[address(pynth)] == bytes32(0), "Pynth address already exists"); availablePynths.push(pynth); pynths[currencyKey] = pynth; pynthsByAddress[address(pynth)] = currencyKey; emit PynthAdded(currencyKey, address(pynth)); } function addPynth(IPynth pynth) external onlyOwner { _addPynth(pynth); // Invalidate the cache to force a snapshot to be recomputed. If a pynth were to be added // back to the system and it still somehow had cached debt, this would force the value to be // updated. debtCache().updateDebtCacheValidity(true); } function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner { uint numPynths = pynthsToAdd.length; for (uint i = 0; i < numPynths; i++) { _addPynth(pynthsToAdd[i]); } // Invalidate the cache to force a snapshot to be recomputed. debtCache().updateDebtCacheValidity(true); } function _removePynth(bytes32 currencyKey) internal { address pynthToRemove = address(pynths[currencyKey]); require(pynthToRemove != address(0), "Pynth does not exist"); require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists"); require(currencyKey != pUSD, "Cannot remove pynth"); // Remove the pynth from the availablePynths array. for (uint i = 0; i < availablePynths.length; i++) { if (address(availablePynths[i]) == pynthToRemove) { delete availablePynths[i]; // Copy the last pynth into the place of the one we just deleted // If there's only one pynth, this is pynths[0] = pynths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availablePynths[i] = availablePynths[availablePynths.length - 1]; // Decrease the size of the array by one. availablePynths.length--; break; } } // And remove it from the pynths mapping delete pynthsByAddress[pynthToRemove]; delete pynths[currencyKey]; emit PynthRemoved(currencyKey, pynthToRemove); } function removePynth(bytes32 currencyKey) external onlyOwner { // Remove its contribution from the debt pool snapshot, and // invalidate the cache to force a new snapshot. IIssuerInternalDebtCache cache = debtCache(); cache.updateCachedPynthDebtWithRate(currencyKey, 0); cache.updateDebtCacheValidity(true); _removePynth(currencyKey); } function removePynths(bytes32[] calldata currencyKeys) external onlyOwner { uint numKeys = currencyKeys.length; // Remove their contributions from the debt pool snapshot, and // invalidate the cache to force a new snapshot. IIssuerInternalDebtCache cache = debtCache(); uint[] memory zeroRates = new uint[](numKeys); cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates); cache.updateDebtCacheValidity(true); for (uint i = 0; i < numKeys; i++) { _removePynth(currencyKeys[i]); } } function issuePynths(address from, uint amount) external onlyPeriFin { _issuePynths(from, amount, false); } function issueMaxPynths(address from) external onlyPeriFin { _issuePynths(from, 0, true); } function issuePynthsOnBehalf( address issueForAddress, address from, uint amount ) external onlyPeriFin { _requireCanIssueOnBehalf(issueForAddress, from); _issuePynths(issueForAddress, amount, false); } function issueMaxPynthsOnBehalf(address issueForAddress, address from) external onlyPeriFin { _requireCanIssueOnBehalf(issueForAddress, from); _issuePynths(issueForAddress, 0, true); } function burnPynths(address from, uint amount) external onlyPeriFin { _voluntaryBurnPynths(from, amount, false); } function burnPynthsOnBehalf( address burnForAddress, address from, uint amount ) external onlyPeriFin { _requireCanBurnOnBehalf(burnForAddress, from); _voluntaryBurnPynths(burnForAddress, amount, false); } function burnPynthsToTarget(address from) external onlyPeriFin { _voluntaryBurnPynths(from, 0, true); } function burnPynthsToTargetOnBehalf(address burnForAddress, address from) external onlyPeriFin { _requireCanBurnOnBehalf(burnForAddress, from); _voluntaryBurnPynths(burnForAddress, 0, true); } function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external onlyPeriFin returns (uint totalRedeemed, uint amountToLiquidate) { // Ensure waitingPeriod and pUSD balance is settled as burning impacts the size of debt pool require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled"); // Check account is liquidation open require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation"); // require liquidator has enough pUSD require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= susdAmount, "Not enough pUSD"); uint liquidationPenalty = liquidations().liquidationPenalty(); // What is their debt in pUSD? (uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD); (uint snxRate, bool snxRateInvalid) = exchangeRates().rateAndInvalid(PERI); _requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid); uint collateralForAccount = _collateral(account); uint amountToFixRatio = liquidations().calculateAmountToFixCollateral( debtBalance, _snxToUSD(collateralForAccount, snxRate) ); // Cap amount to liquidate to repair collateral ratio based on issuance ratio amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount; // what's the equivalent amount of snx for the amountToLiquidate? uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate); // Add penalty totalRedeemed = snxRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty)); // if total PERI to redeem is greater than account's collateral // account is under collateralised, liquidate all collateral and reduce pUSD to burn if (totalRedeemed > collateralForAccount) { // set totalRedeemed to all transferable collateral totalRedeemed = collateralForAccount; // whats the equivalent pUSD to burn for all collateral less penalty amountToLiquidate = _snxToUSD( collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)), snxRate ); } // burn pUSD from messageSender (liquidator) and reduce account's debt _burnPynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued); // Remove liquidation flag if amount liquidated fixes ratio if (amountToLiquidate == amountToFixRatio) { // Remove liquidation liquidations().removeAccountInLiquidation(account); } } /* ========== INTERNAL FUNCTIONS ========== */ function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure { require(!anyRateIsInvalid, "A pynth or PERI rate is invalid"); } function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view { require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf"); } function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view { require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf"); } function _issuePynths( address from, uint amount, bool issueMax ) internal { (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) = _remainingIssuablePynths(from); _requireRatesNotInvalid(anyRateIsInvalid); if (!issueMax) { require(amount <= maxIssuable, "Amount too large"); } else { amount = maxIssuable; } // Keep track of the debt they're about to create _addToDebtRegister(from, amount, existingDebt, totalSystemDebt); // record issue timestamp _setLastIssueEvent(from); // Create their pynths pynths[pUSD].issue(from, amount); // Account for the issued debt in the cache debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit()); // Store their locked PERI amount to determine their fee % for the period _appendAccountIssuanceRecord(from); } function _burnPynths( address debtAccount, address burnAccount, uint amount, uint existingDebt, uint totalDebtIssued ) internal returns (uint amountBurnt) { // liquidation requires pUSD to be already settled / not in waiting period // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. amountBurnt = existingDebt < amount ? existingDebt : amount; // Remove liquidated debt from the ledger _removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued); // pynth.burn does a safe subtraction on balance (so it will revert if there are not enough pynths). pynths[pUSD].burn(burnAccount, amountBurnt); // Account for the burnt debt in the cache. debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit()); // Store their debtRatio against a fee period to determine their fee/rewards % for the period _appendAccountIssuanceRecord(debtAccount); } // If burning to target, `amount` is ignored, and the correct quantity of pUSD is burnt to reach the target // c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user // will still have debt remaining after reaching their target. function _voluntaryBurnPynths( address from, uint amount, bool burnToTarget ) internal { if (!burnToTarget) { // If not burning to target, then burning requires that the minimum stake time has elapsed. require(_canBurnPynths(from), "Minimum stake time not reached"); // First settle anything pending into pUSD as burning or issuing impacts the size of the debt pool (, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD); if (numEntriesSettled > 0) { amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded); } } (uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD); (uint maxIssuablePynthsForAccount, bool snxRateInvalid) = _maxIssuablePynths(from); _requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid); require(existingDebt > 0, "No debt to forgive"); if (burnToTarget) { amount = existingDebt.sub(maxIssuablePynthsForAccount); } uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue); // Check and remove liquidation if existingDebt after burning is <= maxIssuablePynths // Issuance ratio is fixed so should remove any liquidations if (existingDebt.sub(amountBurnt) <= maxIssuablePynthsForAccount) { liquidations().removeAccountInLiquidation(from); } } function _setLastIssueEvent(address account) internal { // Set the timestamp of the last issuePynths flexibleStorage().setUIntValue( CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)), block.timestamp ); } function _appendAccountIssuanceRecord(address from) internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = perifinState().issuanceData(from); feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex); } function _addToDebtRegister( address from, uint amount, uint existingDebt, uint totalDebtIssued ) internal { IPeriFinState state = perifinState(); // What will the new total be including the new value? uint newTotalDebtIssued = amount.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } else { // If they have no debt, they're a new issuer; record this. state.incrementTotalIssuerCount(); } // Save the debt entry parameters state.setCurrentIssuanceData(from, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (state.debtLedgerLength() > 0) { state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } else { state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function _removeFromDebtRegister( address from, uint debtToRemove, uint existingDebt, uint totalDebtIssued ) internal { IPeriFinState state = perifinState(); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { state.setCurrentIssuanceData(from, 0); state.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers state.setCurrentIssuanceData(from, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } /* ========== MODIFIERS ========== */ function _onlyPeriFin() internal view { require(msg.sender == address(perifin()), "Issuer: Only the perifin contract can perform this action"); } modifier onlyPeriFin() { _onlyPeriFin(); // Use an internal function to save code size. _; } /* ========== EVENTS ========== */ event PynthAdded(bytes32 currencyKey, address pynth); event PynthRemoved(bytes32 currencyKey, address pynth); }
Remove their contributions from the debt pool snapshot, and invalidate the cache to force a new snapshot.
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner { uint numKeys = currencyKeys.length; IIssuerInternalDebtCache cache = debtCache(); uint[] memory zeroRates = new uint[](numKeys); cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates); cache.updateDebtCacheValidity(true); for (uint i = 0; i < numKeys; i++) { _removePynth(currencyKeys[i]); } }
1,089,742
pragma solidity ^0.4.25; //This is a contract for selling and buying properties where seller can set a specific price in wei and the buyer has to buy it at that price contract RealEstate { address public seller; address public buyer; string public streetAddress; string title; uint256 public price; function RealEstate (){ //who is the seller? seller = msg.sender; //what is the address streetAddress= "221B Baker Street"; //what is the title title="holmes house"; //what is the price price=12000000000000000000; //12 ether equivalent to wei(price of the property) } //making a buy function function buyHouse() payable public{ require(seller != 0x0); // check if seller address exists require(buyer == 0x0); // buyer is not set yet require(msg.sender != seller); // buyer and seller accounts are different require(msg.value == price); //prices match buyer = msg.sender; seller.transfer(msg.value); //sends the value is the msg sender is the value put in box } }
who is the seller?what is the addresswhat is the titlewhat is the price
function RealEstate (){ seller = msg.sender; streetAddress= "221B Baker Street"; title="holmes house"; }
12,843,497
./partial_match/1/0x5d2F6c3bEFAe73276baCC8017cCb907EE921149F/sources/CypherShia.sol
fee must be less than 5%
function setFee(uint256 _fee) external onlyOwner { require(_fee <= 500, "_"); fee = _fee; }
4,214,713
./full_match/1/0x2Bbbdf97295F73175b12CC087cF446765931e1C3/sources/@layerzerolabs/solidity-examples/contracts/token/oft/v2/OFTCoreV2.sol
encode the msg.sender into the payload instead of _from
function _sendAndCall( address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes memory _payload, uint64 _dstGasForCall, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams ) internal virtual returns (uint amount) { _checkGasLimit(_dstChainId, PT_SEND_AND_CALL, _adapterParams, _dstGasForCall); (amount, ) = _removeDust(_amount); amount = _debitFrom(_from, _dstChainId, _toAddress, amount); require(amount > 0, "OFTCore: amount too small"); bytes memory lzPayload = _encodeSendAndCallPayload(msg.sender, _toAddress, _ld2sd(amount), _payload, _dstGasForCall); _lzSend(_dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value); emit SendToChain(_dstChainId, _from, _toAddress, amount); }
8,317,424
./partial_match/1/0xFf8b856CcA6dAC57635B752FDf5e9195986c9Ce5/sources/contracts/protocol/WETHGateway.sol
approve NFT transfer from gateway to lendPool contract/
function approveNFTTransfer(address nftAsset, bool approved) external onlyOwner{ IERC721Upgradeable(nftAsset).setApprovalForAll(address(_getLendPool()), approved); }
4,103,625
pragma solidity ^0.4.17; import "./ERC721.sol"; import "./Migrations.sol"; contract CopyrightToken { struct Copyright { uint id; string photoURL; uint256 issueDate; address originalOwner; address oldOwner; address newOwner; } Copyright[] copyrights; mapping(uint => address) internal prevTokenOwners; mapping(uint => address) internal tokenOwners; mapping(uint => bool) internal tokenExists; mapping(address => uint) internal copyrightCounts; // How many copyrights _id has mapping(address => mapping(address => uint256)) internal allowed; event GenerateToken(uint _imageId, uint _tokenId, uint256 _issueDate, address _originalOwner); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId, uint _imageId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function mint(uint _imageId, string _photoURL) public returns (uint){ uint _tokenId = copyrights.length; Copyright memory _copyright = Copyright({ id: _tokenId, photoURL: _photoURL, issueDate: uint256(now), originalOwner: msg.sender, oldOwner: address(0), newOwner: msg.sender }); copyrights.push(_copyright); prevTokenOwners[_tokenId] = address(0); tokenOwners[_tokenId] = msg.sender; tokenExists[_tokenId] = true; copyrightCounts[msg.sender] += 1; emit GenerateToken(_imageId, _tokenId, _copyright.issueDate, msg.sender); } function getCopyrightInfo(uint _tokenId) external view returns( uint id, string photoURL, uint256 issueDate, address originalOwner, address oldOwner, address newOwner ) { Copyright storage c = copyrights[_tokenId]; id = c.id; photoURL = c.photoURL; issueDate = c.issueDate; originalOwner = c.originalOwner; oldOwner = prevTokenOwners[_tokenId]; newOwner = tokenOwners[_tokenId]; } /* 1. ERC20 compatible functions : let users perform actions such as sending tokens to others and checking balances of accounts.*/ string public constant name = "CopyrightToken"; string public constant symbol = "CRT"; // Token’s shorthand name function totalSupply() public view returns (uint256) { // Total number of copyrights we made return copyrights.length; } function balanceOf(address _owner) public view returns (uint256) { // How many copyrights _owner has return copyrightCounts[_owner]; } /* 2. Ownership Functions */ function ownerOf(uint256 _tokenId) public view returns (address) { // Who is the owner of this token? return tokenOwners[_tokenId]; } function approve(address _to, uint256 _tokenId) public { // Approves other people has permission to transfer a token require(msg.sender == ownerOf(_tokenId)); require(msg.sender != _to); allowed[msg.sender][_to] = _tokenId; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId, uint _imageId) public { require(tokenExists[_tokenId]); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; require(oldOwner != newOwner); require(allowed[oldOwner][newOwner] == _tokenId); copyrightCounts[oldOwner] -= 1; prevTokenOwners[_tokenId] = oldOwner; tokenOwners[_tokenId] = newOwner; copyrightCounts[newOwner] += 1; emit Transfer(oldOwner, newOwner, _tokenId, _imageId); } function transfer(address _to, uint256 _tokenId, uint _imageId) public { address oldOwner = msg.sender; address newOwner = _to; require(tokenExists[_tokenId]); require(oldOwner == ownerOf(_tokenId)); require(oldOwner != newOwner); require(newOwner != address(0)); copyrightCounts[oldOwner] -= 1; prevTokenOwners[_tokenId] = oldOwner; tokenOwners[_tokenId] = newOwner; copyrightCounts[newOwner] += 1; emit Transfer(oldOwner, newOwner, _tokenId, _imageId); } }
How many copyrights _owner has
function balanceOf(address _owner) public view returns (uint256) {
13,047,895
./full_match/43113/0x49E101b346621e5CE74C14DB2d8Be36C751bc4BA/sources/TicketMaketPlace.sol
functionsend the token to the smart contract
function addProduct (uint256 _ticketId, uint256 _price, uint256 _gas) public onlyTokenOwner(_ticketId) { require(!hasBeenListed[_ticketId], "The ticket can only be listed once"); _transfer(msg.sender, address(this), _ticketId); claimableByAccount[_ticketId] = msg.sender; ListProduct[_ticketId] = product( _ticketId, _price, _gas, msg.sender ); hasBeenListed[_ticketId] = true; products.push(_ticketId); _productID[_ticketId] = products.length-1; emit addedProduct(_ticketId, _price, msg.sender); }
13,181,683
pragma solidity ^0.4.25; /* ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░█▀▀▀▀█░█▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀█░█▀▀ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ website: https://redalert.ga discord: https://discord.gg/8AFP9gS 20% Dividends Fees/Payouts for Exchange 2.5% Buy Fee for Bomb Shelter Insurance 2.5% Buy Fee for Bomb Shelter Card Yield Dividends Bomb Shelter Card Game: While you hold a Bomb Shelter Card you will receive dividend Yield Payouts from the Exchange and from other Card Transactions. When someone buys your Bomb Shelter Card: - The card price automatically increases by 25% - The previous owner receives the amount the prior card price plus 45% of the price gain - Other card holders receive 40% of the gain split in relation to their yield amounts - 5% of the gain goes to the exchange token holders as dividends - 5% of the gain goes to bomb shelter insurance Every 8 Hours there is a Red Alert Scramble lasting 1 Hour During the alert the Bomb Shelter Card Half Life Time is 25 Minutes During Each 7 Hour All Clear Period the Half Life Time is 5 Hours If you hold a Bomb Shelter Card when it experiences a Half-life Cut: - Your Bomb Shelter Price will reduce by 3% - You will receive 5% of the Shelter Insurance Fund on every Half-Life Cut Referral Program pays out 33% of Exchange Buy-in Fees to user of masternode link */ contract AcceptsExchange { redalert public tokenContract; function AcceptsExchange(address _tokenContract) public { tokenContract = redalert(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool); } contract redalert { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0 || ownerAccounts[msg.sender] > 0); //require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } modifier allowPlayer(){ require(boolAllowPlayer); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } modifier onlyActive(){ require(boolContractActive); _; } modifier onlyCardActive(){ require(boolCardActive); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? (ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_) || (_customerAddress == dev) ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onCardBuy( address customerAddress, uint256 incomingEthereum, uint256 card, uint256 newPrice, uint256 halfLifeTime ); event onInsuranceChange( address customerAddress, uint256 card, uint256 insuranceAmount ); event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); // HalfLife event Halflife( address customerAddress, uint card, uint price, uint newBlockTime, uint insurancePay, uint cardInsurance ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "RedAlert"; string public symbol = "REDS"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 3 ether; uint256 constant internal ambassadorQuota_ = 100 ether; address dev; uint public nextAvailableCard; address add2 = 0x0; uint public totalCardValue = 0; uint public totalCardInsurance = 0; bool public boolAllowPlayer = false; //TIME struct DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; //CARDS mapping(uint => address) internal cardOwner; mapping(uint => uint) public cardPrice; mapping(uint => uint) public basePrice; mapping(uint => uint) internal cardPreviousPrice; mapping(address => uint) internal ownerAccounts; mapping(uint => uint) internal totalCardDivs; mapping(uint => uint) internal totalCardDivsETH; mapping(uint => string) internal cardName; mapping(uint => uint) internal cardInsurance; uint public cardInsuranceAccount; uint cardPriceIncrement = 1250; //25% Price Increases uint totalDivsProduced; //card rates uint public ownerDivRate = 450; //Split to previous card owner 45% uint public distDivRate = 400; //Split to other card owners 40% uint public devDivRate = 50; //Dev 5% uint public insuranceDivRate = 50; //Split to Shelter Insurance Accounts 5% uint public yieldDivRate = 50; //Split back to Exchange Token Holders 5% uint public referralRate = 50; //Split to Referrals if allowed 5% mapping(uint => uint) internal cardBlockNumber; uint public halfLifeTime = 5900; //1 day half life period uint public halfLifeRate = 970; //cut price by 3% each half life period uint public halfLifeReductionRate = 970; //cut previous price by 3% uint public halfLifeClear = 1230; //Half-Life Clear Period(5 Hours) uint public halfLifeAlert = 100; //Half-Life Alert Period(25 Mins) bool public allowHalfLife = true; //for cards bool public allowReferral = false; //for cards uint public insurancePayoutRate = 50; //pay 5% of the remaining insurance fund for that card on each half-life uint8 public dividendFee_ = 150; uint8 public dividendFeeBuyClear_ = 150; uint8 public dividendFeeSellClear_ = 200; uint8 public dividendFeeBuyAlert_ = 150; uint8 public dividendFeeSellAlert_ = 200; uint8 public cardInsuranceFeeRate_ = 25; // 2.5% fee rate on each buy and sell for Shelter Card Insurance uint8 public yieldDividendFeeRate_ = 25; // 2.5% fee rate on each buy and sell for Shelter Card Yield Dividends //uint8 public investorFeeRate_ = 10;//10; // 1% fee for investors uint public maxCards = 50; bool public boolContractActive = false; bool public boolCardActive = false; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Wall Street Market Platform control from scam game contracts on Wall Street Market platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Wall Street tokens uint public alertTime1 = 0; uint public alertTime2 = 8; uint public alertTime3 = 16; uint public lastHour = 0; bool public boolAlertStatus = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function redalert() public { allowHalfLife = true; allowReferral = false; // add administrators here administrators[msg.sender] = true; dev = msg.sender; ambassadors_[dev] = true; ambassadors_[0x96762288ebb2560a19F8eAdAaa2012504F64278B] = true; ambassadors_[0x5145A296e1bB9d4Cf468d6d97d7B6D15700f39EF] = true; ambassadors_[0xE74b1ea522B9d558C8e8719c3b1C4A9050b531CA] = true; ambassadors_[0xb62A0AC2338C227748E3Ce16d137C6282c9870cF] = true; ambassadors_[0x836e5abac615b371efce0ab399c22a04c1db5ecf] = true; ambassadors_[0xAe3dC7FA07F9dD030fa56C027E90998eD9Fe9D61] = true; ambassadors_[0x38602d1446fe063444B04C3CA5eCDe0cbA104240] = true; ambassadors_[0x3825c8BA07166f34cE9a2cD1e08A68b105c82cB9] = true; ambassadors_[0xa6662191F558e4C611c8f14b50c784EDA9Ace98d] = true; ambassadors_[0xC697BE0b5b82284391A878B226e2f9AfC6B94710] = true; ambassadors_[0x03Ba7aC9fa34E2550dE27B33Cb7eBc8d2618A263] = true; ambassadors_[0x79562dcCFAad8871E2eC1C37172Cb1ce969b04Fd] = true; ambassadors_[0x41fe3738b503cbafd01c1fd8dd66b7fe6ec11b01] = true; ambassadors_[0x96762288ebb2560a19f8eadaaa2012504f64278b] = true; ambassadors_[0xc29a6dd21801e58566df9f003b7011e30724543e] = true; ambassadors_[0xc63ea85cc823c440319013d4b30e19b66466642d] = true; ambassadors_[0xc6f827796a2e1937fd7f97c4e0a4906c476794f6] = true; ambassadors_[0xe74b1ea522b9d558c8e8719c3b1c4a9050b531ca] = true; ambassadors_[0x6b90d498062140c607d03fd642377eeaa325703e] = true; ambassadors_[0x5f1088110edcba27fc206cdcc326b413b5867361] = true; ambassadors_[0xc92fd0e554b12eb10f584819eec2394a9a6f3d1d] = true; ambassadors_[0xb62a0ac2338c227748e3ce16d137c6282c9870cf] = true; ambassadors_[0x3f6c42409da6faf117095131168949ab81d5947d] = true; ambassadors_[0xd54c47b3165508fb5418dbdec59a0d2448eeb3d7] = true; ambassadors_[0x285d366834afaa8628226e65913e0dd1aa26b1f8] = true; ambassadors_[0x285d366834afaa8628226e65913e0dd1aa26b1f8] = true; ambassadors_[0x5f5996f9e1960655d6fc00b945fef90672370d9f] = true; ambassadors_[0x3825c8ba07166f34ce9a2cd1e08a68b105c82cb9] = true; ambassadors_[0x7f3e05b4f258e1c15a0ef49894cffa1d89ceb9d3] = true; ambassadors_[0x3191acf877495e5f4e619ec722f6f38839182660] = true; ambassadors_[0x14f981ec7b0f59df6e1c56502e272298f221d763] = true; ambassadors_[0xae817ec70d8b621bb58a047e63c31445f79e20dc] = true; ambassadors_[0xc43af3becac9c810384b69cf061f2d7ec73105c4] = true; ambassadors_[0x0743469569ed5cc44a51216a1bf5ad7e7f90f40e] = true; ambassadors_[0xff6a4d0ed374ba955048664d6ef5448c6cd1d56a] = true; ambassadors_[0x62358a483311b3de29ae987b990e19de6259fa9c] = true; ambassadors_[0xa0fea1bcfa32713afdb73b9908f6cb055022e95f] = true; ambassadors_[0xb2af816608e1a4d0fb12b81028f32bac76256eba] = true; ambassadors_[0x977193d601b364f38ab1a832dbaef69ca7833992] = true; ambassadors_[0xed3547f0ed028361685b39cd139aa841df6629ab] = true; ambassadors_[0xe40ff298079493cba637d92089e3d1db403974cb] = true; ambassadors_[0xae3dc7fa07f9dd030fa56c027e90998ed9fe9d61] = true; ambassadors_[0x2dd35e7a6f5fcc28d146c04be641f969f6d1e403] = true; ambassadors_[0x2afe21ec5114339922d38546a3be7a0b871d3a0d] = true; ambassadors_[0x6696fee394bb224d0154ea6b58737dca827e1960] = true; ambassadors_[0xccdf159b1340a35c3567b669c836a88070051314] = true; ambassadors_[0x1c3416a34c86f9ddcd05c7828bf5693308d19e0b] = true; ambassadors_[0x846dedb19b105edafac2c9410fa2b5e73b596a14] = true; ambassadors_[0x3e9294f9b01bc0bcb91413112c75c3225c65d0b3] = true; ambassadors_[0x3a5ce61c74343dde474bad4210cccf1dac7b1934] = true; ambassadors_[0x38e123f89a7576b2942010ad1f468cc0ea8f9f4b] = true; ambassadors_[0xdcd8bad894035b5c554ad450ca84ae6be0b73122] = true; ambassadors_[0xcfab320d4379a84fe3736eccf56b09916e35097b] = true; ambassadors_[0x12f53c1d7caea0b41010a0e53d89c801ed579b5a] = true; ambassadors_[0x5145a296e1bb9d4cf468d6d97d7b6d15700f39ef] = true; ambassadors_[0xac707a1b4396a309f4ad01e3da4be607bbf14089] = true; ambassadors_[0x38602d1446fe063444b04c3ca5ecde0cba104240] = true; ambassadors_[0xc951d3463ebba4e9ec8ddfe1f42bc5895c46ec8f] = true; ambassadors_[0x69e566a65d00ad5987359db9b3ced7e1cfe9ac69] = true; ambassadors_[0x533b14f6d04ed3c63a68d5e80b7b1f6204fb4213] = true; ambassadors_[0x5fa0b03bee5b4e6643a1762df718c0a4a7c1842f] = true; ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true; ambassadors_[0xc371117e0adfafe2a3b7b6ba71b7c0352ca7789d] = true; ambassadors_[0xcade49e583bc226f19894458f8e2051289f1ac85] = true; ambassadors_[0xe3fc95aba6655619db88b523ab487d5273db484f] = true; ambassadors_[0x22e4d1433377a2a18452e74fd4ba9eea01824f7d] = true; ambassadors_[0x32ae5eff81881a9a70fcacada5bb1925cabca508] = true; ambassadors_[0xb864d177c291368b52a63a95eeff36e3731303c1] = true; ambassadors_[0x46091f77b224576e224796de5c50e8120ad7d764] = true; ambassadors_[0xc6407dd687a179aa11781b8a1e416bd0515923c2] = true; ambassadors_[0x2502ce06dcb61ddf5136171768dfc08d41db0a75] = true; ambassadors_[0x6b80ca9c66cdcecc39893993df117082cc32bb16] = true; ambassadors_[0xa511ddba25ffd74f19a400fa581a15b5044855ce] = true; ambassadors_[0xce81d90ae52d34588a95db59b89948c8fec487ce] = true; ambassadors_[0x6d60dbf559bbf0969002f19979cad909c2644dad] = true; ambassadors_[0x45101255a2bcad3175e6fda4020a9b77e6353a9a] = true; ambassadors_[0xe9078d7539e5eac3b47801a6ecea8a9ec8f59375] = true; ambassadors_[0x41a21b264f9ebf6cf571d4543a5b3ab1c6bed98c] = true; ambassadors_[0x471e8d970c30e61403186b6f245364ae790d14c3] = true; ambassadors_[0x6eb7f74ff7f57f7ba45ca71712bccef0588d8f0d] = true; ambassadors_[0xe6d6bc079d76dc70fcec5de84721c7b0074d164b] = true; ambassadors_[0x3ec5972c2177a08fd5e5f606f19ab262d28ceffe] = true; ambassadors_[0x108b87a18877104e07bd870af70dfc2487447262] = true; ambassadors_[0x3129354440e4639d2b809ca03d4ccc6277ac8167] = true; ambassadors_[0x21572b6a855ee8b1392ed1003ecf3474fa83de3e] = true; ambassadors_[0x75ab98f33a7a60c4953cb907747b498e0ee8edf7] = true; ambassadors_[0x0fe6967f9a5bb235fc74a63e3f3fc5853c55c083] = true; ambassadors_[0x49545640b9f3266d13cce842b298d450c0f8d776] = true; ambassadors_[0x9327128ead2495f60d41d3933825ffd8080d4d42] = true; ambassadors_[0x82b4e53a7d6bf6c72cc57f8d70dae90a34f0870f] = true; ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true; ambassadors_[0x3749d556c167dd73d536a6faaf0bb4ace8f7dab9] = true; ambassadors_[0x3039f6857071692b540d9e1e759a0add93af3fed] = true; ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true; nextAvailableCard = 13; cardOwner[1] = dev; cardPrice[1] = 5 ether; basePrice[1] = cardPrice[1]; cardPreviousPrice[1] = 0; cardOwner[2] = dev; cardPrice[2] = 4 ether; basePrice[2] = cardPrice[2]; cardPreviousPrice[2] = 0; cardOwner[3] = dev; cardPrice[3] = 3 ether; basePrice[3] = cardPrice[3]; cardPreviousPrice[3] = 0; cardOwner[4] = dev; cardPrice[4] = 2 ether; basePrice[4] = cardPrice[4]; cardPreviousPrice[4] = 0; cardOwner[5] = dev; cardPrice[5] = 1.5 ether; basePrice[5] = cardPrice[5]; cardPreviousPrice[5] = 0; cardOwner[6] = dev; cardPrice[6] = 1 ether; basePrice[6] = cardPrice[6]; cardPreviousPrice[6] = 0; cardOwner[7] = dev; cardPrice[7] = 0.9 ether; basePrice[7] = cardPrice[7]; cardPreviousPrice[7] = 0; cardOwner[8] = dev; cardPrice[8] = 0.7 ether; basePrice[8] = cardPrice[8]; cardPreviousPrice[8] = 0; cardOwner[9] = 0xAe3dC7FA07F9dD030fa56C027E90998eD9Fe9D61; cardPrice[9] = 0.5 ether; basePrice[9] = cardPrice[9]; cardPreviousPrice[9] = 0; cardOwner[10] = dev; cardPrice[10] = 0.4 ether; basePrice[10] = cardPrice[10]; cardPreviousPrice[10] = 0; cardOwner[11] = dev; cardPrice[11] = 0.2 ether; basePrice[11] = cardPrice[11]; cardPreviousPrice[11] = 0; cardOwner[12] = dev; cardPrice[12] = 0.1 ether; basePrice[12] = cardPrice[12]; cardPreviousPrice[12] = 0; getTotalCardValue(); } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress]; referralBalance_[_customerAddress] = 0; ownerAccounts[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); checkHalfLife(); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); checkHalfLife(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress]; referralBalance_[_customerAddress] = 0; ownerAccounts[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); checkHalfLife(); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data uint8 localDivFee = 200; lastHour = getHour(block.timestamp); if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){ boolAlertStatus = true; localDivFee = dividendFeeBuyAlert_; }else{ boolAlertStatus = false; localDivFee = dividendFeeBuyClear_; } address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, localDivFee),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } checkHalfLife(); // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; uint8 localDivFee = 200; lastHour = getHour(block.timestamp); if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){ boolAlertStatus = true; localDivFee = dividendFeeBuyAlert_; }else{ boolAlertStatus = false; localDivFee = dividendFeeBuyClear_; } if (msg.sender == dev){ //exempt the dev from transfer fees so we can do some promo, you'll thank me in the morning localDivFee = 0; } // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 20% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, localDivFee),1000); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); checkHalfLife(); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setAllowHalfLife(bool _allow) onlyAdministrator() public { allowHalfLife = _allow; } function setAllowReferral(bool _allow) onlyAdministrator() public { allowReferral = _allow; //for cards } /** * Set fees/rates */ function setFeeRates(uint8 _newDivRate, uint8 _yieldDivFee, uint8 _newCardFee) onlyAdministrator() public { require(_newDivRate <= 250); //25% require(_yieldDivFee <= 50); //5% require(_newCardFee <= 50); //5% dividendFee_ = _newDivRate; yieldDividendFeeRate_ = _yieldDivFee; cardInsuranceFeeRate_ = _newCardFee; } /** * Set Exchange Rates */ function setExchangeRates(uint8 _newBuyAlert, uint8 _newBuyClear, uint8 _newSellAlert, uint8 _newSellClear) onlyAdministrator() public { require(_newBuyAlert <= 400); //40% require(_newBuyClear <= 400); //40% require(_newSellAlert <= 400); //40% require(_newSellClear <= 400); //40% dividendFeeBuyClear_ = _newBuyClear; dividendFeeSellClear_ = _newSellClear; dividendFeeBuyAlert_ = _newBuyAlert; dividendFeeSellAlert_ = _newSellAlert; } /** * Set Exchange Rates */ function setInsurancePayout(uint8 _newRate) onlyAdministrator() public { require(_newRate <= 200); insurancePayoutRate = _newRate; } /** * Set Alert Times */ function setAlertTimes(uint _newAlert1, uint _newAlert2, uint _newAlert3) onlyAdministrator() public { alertTime1 = _newAlert1; alertTime2 = _newAlert2; alertTime3 = _newAlert3; } /** * Set HalfLifePeriods */ function setHalfLifePeriods(uint _alert, uint _clear) onlyAdministrator() public { halfLifeAlert = _alert; halfLifeClear = _clear; } /** * In case one of us dies, we need to replace ourselves. */ function setContractActive(bool _status) onlyAdministrator() public { boolContractActive = _status; } /** * In case one of us dies, we need to replace ourselves. */ function setCardActive(bool _status) onlyAdministrator() public { boolCardActive = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function setMaxCards(uint _card) onlyAdministrator() public { maxCards = _card; } function setHalfLifeTime(uint _time) onlyAdministrator() public { halfLifeTime = _time; } function setHalfLifeRate(uint _rate) onlyAdministrator() public { halfLifeRate = _rate; } function addNewCard(uint _price) onlyAdministrator() public { require(nextAvailableCard < maxCards); cardPrice[nextAvailableCard] = _price; basePrice[nextAvailableCard] = cardPrice[nextAvailableCard]; cardOwner[nextAvailableCard] = dev; totalCardDivs[nextAvailableCard] = 0; cardPreviousPrice[nextAvailableCard] = 0; nextAvailableCard = nextAvailableCard + 1; getTotalCardValue(); } function addAmbassador(address _newAmbassador) onlyAdministrator() public { ambassadors_[_newAmbassador] = true; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function myCardDividends() public view returns(uint256) { address _customerAddress = msg.sender; return ownerAccounts[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_ ),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function getTotalCardValue() internal view { uint counter = 1; uint _totalVal = 0; while (counter < nextAvailableCard) { _totalVal = SafeMath.add(_totalVal,cardPrice[counter]); counter = counter + 1; } totalCardValue = _totalVal; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) onlyActive() internal returns(uint256) { // data setup // setup data uint8 localDivFee = 200; lastHour = getHour(block.timestamp); if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){ boolAlertStatus = true; localDivFee = dividendFeeBuyAlert_; }else{ boolAlertStatus = false; localDivFee = dividendFeeBuyClear_; } cardInsuranceAccount = SafeMath.add(cardInsuranceAccount, SafeMath.div(SafeMath.mul(_incomingEthereum, cardInsuranceFeeRate_), 1000)); //uint _distDividends = SafeMath.div(SafeMath.mul(_incomingEthereum,yieldDividendFeeRate_),1000); distributeYield(SafeMath.div(SafeMath.mul(_incomingEthereum,yieldDividendFeeRate_),1000)); _incomingEthereum = SafeMath.sub(_incomingEthereum,SafeMath.div(SafeMath.mul(_incomingEthereum, cardInsuranceFeeRate_ + yieldDividendFeeRate_), 1000)); uint256 _referralBonus = SafeMath.div(SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee ),1000), 3); uint256 _dividends = SafeMath.sub(SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee ),1000), _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee),1000)); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; distributeInsurance(); checkHalfLife(); // fire event onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } function buyCard(uint _card, address _referrer) public payable onlyCardActive() { require(_card <= nextAvailableCard); require(_card > 0); require(msg.value >= cardPrice[_card]); cardBlockNumber[_card] = block.number; //reset block number for this card for half life calculations //Determine the total dividends uint _baseDividends = msg.value - cardPreviousPrice[_card]; totalDivsProduced = SafeMath.add(totalDivsProduced, _baseDividends); //uint _devDividends = SafeMath.div(SafeMath.mul(_baseDividends,devDivRate),100); uint _ownerDividends = SafeMath.div(SafeMath.mul(_baseDividends,ownerDivRate),1000); _ownerDividends = SafeMath.add(_ownerDividends,cardPreviousPrice[_card]); //owner receovers price they paid initially uint _insuranceDividends = SafeMath.div(SafeMath.mul(_baseDividends,insuranceDivRate),1000); //add dividends to the exchange tokens uint _exchangeDivs = SafeMath.div(SafeMath.mul(_baseDividends, yieldDivRate),1000); profitPerShare_ += (_exchangeDivs * magnitude / (tokenSupply_)); totalCardDivs[_card] = SafeMath.add(totalCardDivs[_card],_ownerDividends); cardInsuranceAccount = SafeMath.add(cardInsuranceAccount, _insuranceDividends); uint _distDividends = SafeMath.div(SafeMath.mul(_baseDividends,distDivRate),1000); if (allowReferral && (_referrer != msg.sender) && (_referrer != 0x0000000000000000000000000000000000000000)) { uint _referralDividends = SafeMath.div(SafeMath.mul(_baseDividends,referralRate),1000); _distDividends = SafeMath.sub(_distDividends,_referralDividends); ownerAccounts[_referrer] = SafeMath.add(ownerAccounts[_referrer],_referralDividends); } distributeYield(_distDividends); //distribute dividends to accounts address _previousOwner = cardOwner[_card]; address _newOwner = msg.sender; ownerAccounts[_previousOwner] = SafeMath.add(ownerAccounts[_previousOwner],_ownerDividends); ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev],SafeMath.div(SafeMath.mul(_baseDividends,devDivRate),1000)); cardOwner[_card] = _newOwner; //Increment the card Price cardPreviousPrice[_card] = msg.value; cardPrice[_card] = SafeMath.div(SafeMath.mul(msg.value,cardPriceIncrement),1000); getTotalCardValue(); distributeInsurance(); checkHalfLife(); emit onCardBuy(msg.sender, msg.value, _card, SafeMath.div(SafeMath.mul(msg.value,cardPriceIncrement),1000), halfLifeTime + block.number); } function distributeInsurance() internal { uint counter = 1; uint _cardDistAmount = cardInsuranceAccount; cardInsuranceAccount = 0; uint tempInsurance = 0; while (counter < nextAvailableCard) { uint _distAmountLocal = SafeMath.div(SafeMath.mul(_cardDistAmount, cardPrice[counter]),totalCardValue); cardInsurance[counter] = SafeMath.add(cardInsurance[counter], _distAmountLocal); tempInsurance = tempInsurance + cardInsurance[counter]; emit onInsuranceChange(0x0, counter, cardInsurance[counter]); counter = counter + 1; } totalCardInsurance = tempInsurance; } function distributeYield(uint _distDividends) internal //tokens { uint counter = 1; uint currentBlock = block.number; uint insurancePayout = 0; while (counter < nextAvailableCard) { uint _distAmountLocal = SafeMath.div(SafeMath.mul(_distDividends, cardPrice[counter]),totalCardValue); ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]],_distAmountLocal); totalCardDivs[counter] = SafeMath.add(totalCardDivs[counter],_distAmountLocal); counter = counter + 1; } getTotalCardValue(); checkHalfLife(); } function extCheckHalfLife() public { bool _boolDev = (msg.sender == dev); if (_boolDev || boolAllowPlayer){ checkHalfLife(); } } function checkHalfLife() internal //tokens { uint localHalfLifeTime = 120; //check whether we are in Alert or All Clear //set local half life time lastHour = getHour(block.timestamp); if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){ boolAlertStatus = true; localHalfLifeTime = halfLifeAlert; }else{ boolAlertStatus = false; localHalfLifeTime = halfLifeClear; } uint counter = 1; uint currentBlock = block.number; uint insurancePayout = 0; uint tempInsurance = 0; while (counter < nextAvailableCard) { //HalfLife Check if (allowHalfLife) { if (cardPrice[counter] > basePrice[counter]) { uint _life = SafeMath.sub(currentBlock, cardBlockNumber[counter]); if (_life > localHalfLifeTime) { cardBlockNumber[counter] = currentBlock; //Reset the clock for this card if (SafeMath.div(SafeMath.mul(cardPrice[counter], halfLifeRate),1000) < basePrice[counter]){ cardPrice[counter] = basePrice[counter]; insurancePayout = SafeMath.div(SafeMath.mul(cardInsurance[counter],insurancePayoutRate),1000); cardInsurance[counter] = SafeMath.sub(cardInsurance[counter],insurancePayout); ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]], insurancePayout); cardPreviousPrice[counter] = SafeMath.div(SafeMath.mul(cardPrice[counter],halfLifeReductionRate),1000); }else{ cardPrice[counter] = SafeMath.div(SafeMath.mul(cardPrice[counter], halfLifeRate),1000); cardPreviousPrice[counter] = SafeMath.div(SafeMath.mul(cardPreviousPrice[counter],halfLifeReductionRate),1000); insurancePayout = SafeMath.div(SafeMath.mul(cardInsurance[counter],insurancePayoutRate),1000); cardInsurance[counter] = SafeMath.sub(cardInsurance[counter],insurancePayout); ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]], insurancePayout); } emit onInsuranceChange(0x0, counter, cardInsurance[counter]); emit Halflife(cardOwner[counter], counter, cardPrice[counter], localHalfLifeTime + block.number, insurancePayout, cardInsurance[counter]); } //HalfLife Check } } tempInsurance = tempInsurance + cardInsurance[counter]; counter = counter + 1; } totalCardInsurance = tempInsurance; getTotalCardValue(); } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } function getCardPrice(uint _card) public view returns(uint) { require(_card <= nextAvailableCard); return cardPrice[_card]; } function getCardInsurance(uint _card) public view returns(uint) { require(_card <= nextAvailableCard); return cardInsurance[_card]; } function getCardOwner(uint _card) public view returns(address) { require(_card <= nextAvailableCard); return cardOwner[_card]; } function gettotalCardDivs(uint _card) public view returns(uint) { require(_card <= nextAvailableCard); return totalCardDivs[_card]; } function getTotalDivsProduced() public view returns(uint) { return totalDivsProduced; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function isLeapYear(uint16 year) constant returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function parseTimestamp(uint timestamp) internal returns (DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; dt.year = ORIGIN_YEAR; // Year while (true) { if (isLeapYear(dt.year)) { buf = LEAP_YEAR_IN_SECONDS; } else { buf = YEAR_IN_SECONDS; } if (secondsAccountedFor + buf > timestamp) { break; } dt.year += 1; secondsAccountedFor += buf; } // Month uint8[12] monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(dt.year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; uint secondsInMonth; for (i = 0; i < monthDayCounts.length; i++) { secondsInMonth = DAY_IN_SECONDS * monthDayCounts[i]; if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i + 1; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 0; i < monthDayCounts[dt.month - 1]; i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i + 1; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour for (i = 0; i < 24; i++) { if (HOUR_IN_SECONDS + secondsAccountedFor > timestamp) { dt.hour = i; break; } secondsAccountedFor += HOUR_IN_SECONDS; } // Minute for (i = 0; i < 60; i++) { if (MINUTE_IN_SECONDS + secondsAccountedFor > timestamp) { dt.minute = i; break; } secondsAccountedFor += MINUTE_IN_SECONDS; } if (timestamp - secondsAccountedFor > 60) { __throw(); } // Second dt.second = uint8(timestamp - secondsAccountedFor); // Day of week. buf = timestamp / DAY_IN_SECONDS; dt.weekday = uint8((buf + 3) % 7); } function getYear(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).year; } function getMonth(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).hour; } function getMinute(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).minute; } function getSecond(uint timestamp) constant returns (uint16) { return parseTimestamp(timestamp).second; } function getWeekday(uint timestamp) constant returns (uint8) { return parseTimestamp(timestamp).weekday; } function toTimestamp(uint16 year, uint8 month, uint8 day) constant returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) constant returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) constant returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) constant returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } function __throw() { uint[] arst; arst[1]; } } /** * @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; } }
Transfer tokens from the caller to a new holder. Remember, there's a 10% fee here as well./ setup
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; uint8 localDivFee = 200; lastHour = getHour(block.timestamp); if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){ boolAlertStatus = true; localDivFee = dividendFeeBuyAlert_; boolAlertStatus = false; localDivFee = dividendFeeBuyClear_; } localDivFee = 0; } uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); checkHalfLife();
918,645
pragma solidity ^0.5.1; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import "zos-lib/contracts/Initializable.sol"; import "./ERC20.sol"; import "openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol"; import "./Assets.sol"; import "./Whitelist.sol"; import "./MasterPropertyValue.sol"; /** * @title MPVToken * @dev The MPV Token contract. */ contract MPVToken is Initializable, ERC20, ERC20Detailed { using SafeMath for uint256; /* * Events */ event DailyLimitUpdatePending(address account, uint256 currentDailyLimit, uint256 updatedDailyLimit); event DailyLimitUpdateCancelled(address account, uint256 dailyLimit); event DailyLimitUpdated(address indexed sender, uint256 indexed dailyLimit); event DailyLimitUpdateFulfilled(address account, uint256 newDailyLimit); event DelayedTransferCountdownLengthUpdated(address superProtectorMultisig, uint256 updatedCountdownLength); event DelayedTransferInitiated( address from, address to, uint256 value, address sender, uint256 countdownStart, TransferMethod transferMethod ); event AssetsUpdated(address indexed sender, address indexed addr); event MintingAdminUpdated(address indexed sender, address indexed admin); event MPVUpdated(address indexed sender, address indexed addr); event RedemptionAdminUpdated(address indexed sender, address indexed admin); event SuperProtectorMultiSigUpdated(address indexed sender, address indexed addr); event UpdateDailyLimitCountdownLengthUpdated(address superProtectorMultisig, uint256 updatedCountdownLength); /* * Storage */ Assets public assets; Whitelist public whitelist; MasterPropertyValue public masterPropertyValue; address public mintingAdmin; address public redemptionAdmin; address public superProtectorMultiSig; uint256 public updateDailyLimitCountdownLength; uint256 public delayedTransferCountdownLength; uint256 public delayedTransferNonce; mapping(address => DailyLimitInfo) public dailyLimits; mapping(uint256 => DelayedTransfer) public delayedTransfers; /// @dev Daily limit info structure. struct DailyLimitInfo { uint256 lastDay; uint256 spentToday; uint256 dailyLimit; uint256 countdownStart; uint256 updatedDailyLimit; } struct DelayedTransfer { address from; address to; address sender; uint256 value; uint256 countdownStart; TransferMethod transferMethod; } enum TransferMethod { Transfer, TransferFrom } /* * Modifiers */ /// @dev Requires that account address is whitelisted. /// @param account Address of account. modifier whitelistedAddress(address account) { require(whitelist.isWhitelisted(account)); _; } /// @dev Requires that account address is the MPV contract. /// @param account Address of account. modifier mpvAccessOnly(address account) { require(account == address(masterPropertyValue)); _; } /// @dev Requires the sender to be the minting admin role contract. modifier onlyMintingAdmin() { require(mintingAdmin == msg.sender); _; } /// @dev Requires the sender to be the redemption admin role contract. modifier onlyRedemptionAdmin() { require(redemptionAdmin == msg.sender); _; } /// @dev Requires the sender to be the super protector multiSig contract. modifier onlySuperProtectorMultiSig() { require(superProtectorMultiSig == msg.sender); _; } /// @dev Requires that the main MPV contract is not paused. modifier mpvNotPaused() { require(masterPropertyValue.paused() == false); _; } /// @dev Requires that transfer does not exceed account daily limit modifier enforceDailyLimit(address account, uint256 value) { require(_enforceLimit(account, value)); _; } /// @dev Requires the sender to be the basic protector multiSig contract. modifier onlyBasicProtectorMultiSig() { require(basicProtectorMultiSig == msg.sender); _; } // NOTE: NEW STORAGE IS APPENDED HERE event SweepAddressUpdated(address indexed sender, address originalAddress, address indexed sweepAddress, address indexed exchangeOwnedAddress); event OriginalTransfer(address originalFrom, address originalTo, uint256 amount); mapping (address => address) public sweepAddresses; address public basicProtectorMultiSig; event BasicProtectorMultiSigUpdated(address indexed sender, address indexed addr); /* * Public functions */ /// @dev Initialize function sets initial storage values. /// @param name Name of token. /// @param symbol Symbol of token. /// @param decimals Number of decimals for token. /// @param _whitelist Whitelist contract address. /// @param _masterPropertyValue Main MPV contract address. /// @param _mintingAdmin Minting admin role contract address. /// @param _redemptionAdmin Redemption admin role contract address. function initialize( string memory name, string memory symbol, uint8 decimals, Whitelist _whitelist, MasterPropertyValue _masterPropertyValue, address _mintingAdmin, address _redemptionAdmin, address _superProtectorMultiSig ) public initializer { ERC20Detailed.initialize(name, symbol, decimals); whitelist = _whitelist; masterPropertyValue = _masterPropertyValue; mintingAdmin = _mintingAdmin; redemptionAdmin = _redemptionAdmin; superProtectorMultiSig = _superProtectorMultiSig; updateDailyLimitCountdownLength = 48 hours; delayedTransferCountdownLength = 48 hours; delayedTransferNonce = 0; } /// @dev Set the MPV contract address. /// @param _masterPropertyValue Address of main MPV contract. function updateMPV(address _masterPropertyValue) public mpvAccessOnly(msg.sender) mpvNotPaused { require(_masterPropertyValue != address(0)); masterPropertyValue = MasterPropertyValue(_masterPropertyValue); emit MPVUpdated(msg.sender, _masterPropertyValue); } /// @dev Set the minting admin role contract address. /// @param _mintingAdmin Address of minting admin role contract. function updateMintingAdmin(address _mintingAdmin) public onlyMintingAdmin mpvNotPaused { require(_mintingAdmin != address(0)); mintingAdmin = _mintingAdmin; emit MintingAdminUpdated(msg.sender, _mintingAdmin); } function updateSuperProtectorMultiSig(address _multisig) public onlySuperProtectorMultiSig mpvNotPaused { require(_multisig != address(0)); superProtectorMultiSig = _multisig; emit SuperProtectorMultiSigUpdated(msg.sender, _multisig); } // this function is called once immediately after upgrade function initializeBasicProtectorMultiSig(address _multisig) public { require(basicProtectorMultiSig == address(0)); require(_multisig != address(0)); basicProtectorMultiSig = _multisig; emit BasicProtectorMultiSigUpdated(msg.sender, _multisig); } function updateBasicProtectorMultiSig(address _multisig) public onlyBasicProtectorMultiSig mpvNotPaused { require(_multisig != address(0)); basicProtectorMultiSig = _multisig; emit BasicProtectorMultiSigUpdated(msg.sender, _multisig); } /// @dev Set the assets contract address. /// @param _assets Address of assets contract. function updateAssets(address _assets) public onlySuperProtectorMultiSig mpvNotPaused { require(_assets != address(0)); assets = Assets(_assets); emit AssetsUpdated(msg.sender, _assets); } /// @dev Set the redemption admin role contract address. /// @param _redemptionAdmin Address of redemption admin role contract. function updateRedemptionAdmin(address _redemptionAdmin) public onlyRedemptionAdmin mpvNotPaused { redemptionAdmin = _redemptionAdmin; emit RedemptionAdminUpdated(msg.sender, _redemptionAdmin); } /// @dev Update the updateDailyLimitCountdownLength /// @param updatedCountdownLength Address of redemption admin role contract. function updateUpdateDailyLimitCountdownLength(uint256 updatedCountdownLength) public onlySuperProtectorMultiSig mpvNotPaused { updateDailyLimitCountdownLength = updatedCountdownLength; emit UpdateDailyLimitCountdownLengthUpdated(msg.sender, updatedCountdownLength); } /// @dev Update the delayedTransferCountdownLength /// @param updatedCountdownLength Address of redemption admin role contract. function updateDelayedTransferCountdownLength(uint256 updatedCountdownLength) public onlySuperProtectorMultiSig mpvNotPaused { delayedTransferCountdownLength = updatedCountdownLength; emit DelayedTransferCountdownLengthUpdated(msg.sender, updatedCountdownLength); } /// @dev Sets new daily limit for sender account after countdown resolves /// @param updatedDailyLimit Updated dailyLimit function updateDailyLimit(uint256 updatedDailyLimit) public { DailyLimitInfo storage limitInfo = dailyLimits[msg.sender]; limitInfo.updatedDailyLimit = updatedDailyLimit; limitInfo.countdownStart = now; emit DailyLimitUpdatePending(msg.sender, limitInfo.dailyLimit, updatedDailyLimit); } /// @dev Cancels dailyLimit update for sender if countdown hasn't /// yet expired function cancelDailyLimitUpdate() public { DailyLimitInfo storage limitInfo = dailyLimits[msg.sender]; require(limitInfo.countdownStart.add(updateDailyLimitCountdownLength) < now); limitInfo.countdownStart = 0; limitInfo.updatedDailyLimit = 0; emit DailyLimitUpdateCancelled(msg.sender, limitInfo.dailyLimit); } /// @dev Transfer tokens to another account. /// @param to Address to transfer tokens to. /// @param value Amount of tokens to transfer. /// @return Success boolean. function transfer(address to, uint256 value) public enforceDailyLimit(msg.sender, value) mpvNotPaused returns (bool) { dailyLimits[msg.sender].spentToday = dailyLimits[msg.sender].spentToday.add(value); return _transferToken(msg.sender, to, value, false); } /// @dev Transfer tokens from an account to another account. /// @param from Address to transfer tokens from. /// @param to Address to transfer tokens to. /// @param value Amount of tokens to transfer. /// @return Success boolean. function transferFrom(address from, address to, uint256 value) public mpvNotPaused enforceDailyLimit(from, value) returns (bool) { dailyLimits[from].spentToday = dailyLimits[from].spentToday.add(value); return _transferToken(from, to, value, true); } /// @dev Starts delayedTransferCountdown to execute transfer in 48 hours /// and allows value to exceed daily transfer limit /// @param to Address to transfer tokens to. /// @param value Amount of tokens to transfer. /// @return transferId The corresponding transferId for delayedTransfers mapping function delayedTransfer(address to, uint256 value) public whitelistedAddress(to) mpvNotPaused returns (uint256 transferId) { transferId = delayedTransferNonce++; DelayedTransfer storage delayedTransfer = delayedTransfers[transferId]; delayedTransfer.from = msg.sender; delayedTransfer.to = to; delayedTransfer.value = value; delayedTransfer.countdownStart = now; delayedTransfer.transferMethod = TransferMethod.Transfer; emit DelayedTransferInitiated( msg.sender, to, value, address(0), delayedTransfer.countdownStart, TransferMethod.Transfer ); } /// @dev Starts delayedTransferCountdown to execute transfer in 48 hours /// and allows value to exceed daily transfer limit /// @param from Address to transfer tokens from. /// @param to Address to transfer tokens to. /// @param value Amount of tokens to transfer. /// @return transferId The corresponding transferId for delayedTransfers mapping function delayedTransferFrom(address from, address to, uint256 value) public whitelistedAddress(to) mpvNotPaused returns (uint256 transferId) { transferId = delayedTransferNonce++; DelayedTransfer storage delayedTransfer = delayedTransfers[transferId]; delayedTransfer.from = from; delayedTransfer.to = to; delayedTransfer.sender = msg.sender; delayedTransfer.value = value; delayedTransfer.countdownStart = now; delayedTransfer.transferMethod = TransferMethod.TransferFrom; emit DelayedTransferInitiated( from, to, value, msg.sender, delayedTransfer.countdownStart, TransferMethod.Transfer ); } /// @dev Executes delayedTransfer given countdown has expired and recipient /// is a whitelisted address /// @param transferId The corresponding transferId /// @return success boolean function executeDelayedTransfer(uint256 transferId) public mpvNotPaused returns (bool success) { DelayedTransfer storage delayedTransfer = delayedTransfers[transferId]; require(whitelist.isWhitelisted(delayedTransfer.to)); require(delayedTransfer.countdownStart.add(delayedTransferCountdownLength) < now); if (delayedTransfer.transferMethod == TransferMethod.Transfer) { success = _transferToken(msg.sender, delayedTransfer.to, delayedTransfer.value, false); } else if (delayedTransfer.transferMethod == TransferMethod.TransferFrom) { success = _transferToken(delayedTransfer.from, delayedTransfer.to, delayedTransfer.value, true); } delete delayedTransfers[transferId]; } /// @dev Cancels a delayedTransfer if called by the initiator of the transfer /// or the owner of the funds /// @param transferId The corresponding transferId /// @return success boolean function cancelDelayedTransfer(uint256 transferId) public mpvNotPaused returns (bool success) { DelayedTransfer storage delayedTransfer = delayedTransfers[transferId]; require(msg.sender == delayedTransfer.from || msg.sender == delayedTransfer.sender); delete delayedTransfers[transferId]; return true; } /// @dev Mint new tokens. /// @param account Address to send newly minted tokens to. /// @param value Amount of tokens to mint. function mint(address account, uint value) public onlyMintingAdmin whitelistedAddress(account) mpvNotPaused { uint256 newTotal = totalSupply().add(value); uint256 totalTokens = assets.totalTokens(); require(newTotal == totalTokens); _mint(account, value); } /// @dev Burn tokens. /// @param account Address to burn tokens from. /// @param value Amount of tokens to burn. function burn(address account, uint value) public onlyRedemptionAdmin mpvNotPaused { uint256 newTotal = totalSupply().sub(value); uint256 totalTokens = assets.totalTokens(); require(newTotal == totalTokens); _burn(account, value); } /* * ERC1404 Implementation */ /// @dev View function that allows a quick check on daily limits /// @param from Address to transfer tokens from. /// @param to Address to transfer tokens to. /// @param value Amount of tokens to transfer. /// @return Returns uint8 0 on valid transfer any other number on invalid transfer function detectTransferRestriction( address from, address to, uint256 value ) public view returns (uint8 returnValue) { DailyLimitInfo storage limitInfo = dailyLimits[from]; if (!whitelist.isWhitelisted(to)) { return 1; } // if daily limit exists if (limitInfo.dailyLimit != 0){ // if new day, only check current transfer value if (now > limitInfo.lastDay + 24 hours) { if (value > limitInfo.dailyLimit) { return 2; } // if daily period not over, check against previous transfers } else if (!_isUnderLimit(limitInfo, value)) { return 2; } } return 0; } /// @dev Translates uint8 restriction code to a human readable string // @param restrictionCode valid code for transfer restrictions /// @return human readable transfer restriction error function messageForTransferRestriction ( uint8 restrictionCode ) public view returns (string memory) { if (restrictionCode == 0) return "Valid transfer"; if (restrictionCode == 1) return "Invalid transfer: nonwhitelisted recipient"; if (restrictionCode == 2) { return "Invalid transfer: exceeds daily limit"; } else { revert("Invalid restrictionCode"); } } function updateSweepAddress( address addr, address exchangeOwnedAddress ) public onlyBasicProtectorMultiSig { address sweepAddress = computeSweepAddress(addr); require(sweepAddress != address(0)); sweepAddresses[sweepAddress] = exchangeOwnedAddress; emit SweepAddressUpdated(msg.sender, addr, sweepAddress, exchangeOwnedAddress); } /* * Internal functions */ /// @dev Updates account info and reverts if daily limit is breached /// @param account Address of account. /// @param amount Amount of tokens account needing to transfer. /// @return boolean. function _enforceLimit(address account, uint amount) internal returns (bool isUnderLimit) { DailyLimitInfo storage limitInfo = dailyLimits[account]; if (now > limitInfo.lastDay + 24 hours) { limitInfo.lastDay = now; limitInfo.spentToday = 0; } if ( limitInfo.countdownStart != 0 && now > limitInfo.countdownStart.add(updateDailyLimitCountdownLength) ) { limitInfo.countdownStart = 0; limitInfo.dailyLimit = limitInfo.updatedDailyLimit; limitInfo.updatedDailyLimit = 0; emit DailyLimitUpdateFulfilled(account, limitInfo.dailyLimit); } isUnderLimit = _isUnderLimit(limitInfo, amount); } function _isUnderLimit(DailyLimitInfo memory limitInfo, uint256 amount) internal pure returns(bool) { return ( // NOTE: 0 == no daily limit limitInfo.dailyLimit == 0 || limitInfo.spentToday.add(amount) <= limitInfo.dailyLimit ); } function _transferToken( address sender, address recipient, uint256 amount, bool isTransferFrom ) internal returns (bool result) { require(sender != address(0)); require(recipient != address(0)); address newRecipient = computeSweepAddress(recipient); address exchangeAddress = sweepAddresses[newRecipient]; if (exchangeAddress != address(0)) { require(whitelist.isWhitelisted(exchangeAddress)); emit Transfer(sender, recipient, amount); emit Transfer(recipient, exchangeAddress, amount); if (isTransferFrom) { result = super.transferFrom(sender, exchangeAddress, amount); } else { result = super.transfer(exchangeAddress, amount); } emit OriginalTransfer(sender, recipient, amount); } else { require(whitelist.isWhitelisted(recipient)); if (isTransferFrom) { result = super.transferFrom(sender, recipient, amount); } else { result = super.transfer(recipient, amount); } emit Transfer(sender, recipient, amount); } } function computeSweepAddress(address addr) public pure returns (address) { return address(uint(addr) >> 20); } }
Transfer tokens from an account to another account. from Address to transfer tokens from. to Address to transfer tokens to. value Amount of tokens to transfer. return Success boolean.
function transferFrom(address from, address to, uint256 value) public mpvNotPaused enforceDailyLimit(from, value) returns (bool) { dailyLimits[from].spentToday = dailyLimits[from].spentToday.add(value); return _transferToken(from, to, value, true); }
6,358,884
./partial_match/42/0x53968fFA6B37E7850fA58941cd4ca90dD7A51571/sources/DFG.sol
Possible ways this could break addressed 1) Accessing before event is over and resetting eth contributed -- added require 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool 3) LP per unit is 0 - impossible checked at generation function
function claimLPTokens() public { require(LPGenerationCompleted, "LGE not completed"); require(ethContributed[msg.sender] > 0 , "Nothing to claim, nothing to see here"); IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); }
3,487,552
./full_match/137/0x0754B593578994d87B70ef3d77bC4C5f171a0919/sources/src/contracts/SignatureMintWithParamsERC1155.sol
Verifies that a mint request is valid.
function verifyRequest(MintRequestWithParams calldata _req, bytes calldata _signature) internal virtual returns (address) { bytes memory encoded = abi.encode(_req); require(_req.to != address(0), "!r"); require(_req.quantity > 0, "!q"); return _processRequest(encoded, _signature); }
4,683,661
./full_match/80001/0x1BD0dD0f3A5A2Fa7055b012Ff6618ED0248193Fa/sources/contracts/QuadraticStreamFunding.sol
Calculate the quadratic funding amount for a user
function calculateMatchingAmount( string calldata _name ) public view returns (uint256) { Contribution[] memory contributor = contributors[_name]; address projectAddress = projectToAddress[_name]; uint projectTotal; for (uint256 j = 0; j < contributor.length; j++) { uint amount = contributor[j].amount; (uint startTime, int96 flowRate, , ) = _acceptedToken.getFlowInfo( contributor[j].contributor, projectAddress ); uint256 timeElapsed = block.timestamp - startTime; amount = amount + (uint96(flowRate) * timeElapsed); projectTotal += Math.sqrt(amount); } projectTotal = projectTotal * projectTotal; uint256 totalContributions = totalContributionsSquared(); uint256 matchingAmount = (projectTotal * matchingPool) / totalContributions; return matchingAmount; }
5,684,035
./full_match/5/0xdF03d0DD06cd35e547b6A270a8fe821aA788e8aa/sources/src/stake/HoprStakeBase.sol
Reclaim any ERC20 token being accidentally sent to the contract. tokenAddress address ERC20 token address./
function reclaimErc20Tokens(address tokenAddress) external onlyOwner nonReentrant { uint256 difference; if (tokenAddress == LOCK_TOKEN) { difference = IERC20(LOCK_TOKEN).balanceOf(address(this)) - totalLocked; difference = IERC20(tokenAddress).balanceOf(address(this)); } IERC20(tokenAddress).safeTransfer(owner(), difference); }
1,882,227
// SPDX-License-Identifier: bsl-1.1 pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 () { 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; } } /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } /// @title Reader of MetadataOracle core data interface ICoreMetadataOracleReader { struct Quote { uint256 price; uint32 updateTS; } /// @notice Gets a list of assets quoted by this oracle. function getAssets() external view returns (address[] memory); /// @notice Checks if an asset is quoted by this oracle. function hasAsset(address asset) external view returns (bool); /** * @notice Gets last known quotes for the assets. * @param assets Assets to query * @return quotes Prices and update timestamps for corresponding assets. */ function quoteAssets(address[] calldata assets) external view returns (Quote[] memory quotes); } /** * @notice Write-efficient oracle */ contract MetadataOracle is ICoreMetadataOracleReader, Ownable { using ABDKMath64x64 for int128; // Signed 64.64 fixed point number 1.002 gives us minimal distinguishable price change of 0.2%. int128 public constant DELTA_BASE = int128(uint128(1002 * 2 ** 64) / uint128(1000)); // min delta is DELTA_BASE ** -512, max delta is DELTA_BASE ** 511 uint256 public constant DELTA_BITS = 10; // keccak256("MetadataOracle.deltas") uint256 private constant DELTAS_LOCATION = 0x13564db6094c800c2f97ce40db2ed0766673b9ca1c1adc61480074f2544395d8; uint256 private constant NO_DELTA = 0; uint256 private constant DELTA_MODULO = 1 << DELTA_BITS; // module for two's complement arithmetic uint256 private constant DELTA_MASK = DELTA_MODULO - 1; // mask to extract a delta uint256 private constant DELTAS_PER_SLOT = 256 / DELTA_BITS; // note that there may be unused bits in a slot uint256 private constant SLOT_PADDING_BITS = 256 - DELTAS_PER_SLOT * DELTA_BITS; // unused bits in a slot int128 private constant ABDK_ONE = int128(int256(1 << 64)); struct Status { // TODO replace with per-asset update timestamps // and // externally set epoch ts for replay attack protection: current epoch < new epoch <= now. uint32 updateTS; // last unix timestamp of ANY update // pricesHash was used instead of nonces since the same nonce may be associated with different // base prices arrays in different chain forks. That is unacceptable for the delta application. // So we had to check the entire prices content for equality. // TODO replace with current epoch as a collision preventer. // Now this is acceptable since prices for an epoch are deterministic. uint64 pricesHash; // for updater only! } Status internal status; address[] internal assets; mapping(address => uint) internal assetId; uint[] internal prices; /// @inheritdoc ICoreMetadataOracleReader function getAssets() external view override returns (address[] memory) { return assets; } function getStatus() external view returns (Status memory) { return status; } // prices WITHOUT deltas applied! for updater only! function getBasePrices() external view returns (uint[] memory) { return prices; } // for updater only! function getCurrentDeltas() external view returns (uint[] memory result) { result = new uint[](assets.length); // TODO optimize excess sload-s for (uint i = 0; i < result.length; i++) result[i] = getDelta(i); } /// @inheritdoc ICoreMetadataOracleReader function hasAsset(address asset) public view override returns (bool) { return assetId[asset] != 0 || (assets.length != 0 && assets[0] == asset); } /// @inheritdoc ICoreMetadataOracleReader function quoteAssets(address[] calldata assets_) external view override returns (Quote[] memory quotes) { uint32 updateTS = status.updateTS; uint256 length = assets_.length; quotes = new Quote[](length); for (uint i = 0; i < length; i++) { address asset = assets_[i]; uint256 id = assetId[asset]; require(id != 0 || (assets.length != 0 && assets[0] == asset), "MetadataOracle: ASSET_NOT_FOUND"); // TODO optimize excess sload-s quotes[i] = Quote(getPrice(id), updateTS); } } function addAsset(address asset, uint256 currentPrice) external onlyOwner { require(!hasAsset(asset), "MetadataOracle: ASSET_EXISTS"); assetId[asset] = assets.length; assets.push(asset); prices.push(currentPrice); setDelta(assetId[asset], NO_DELTA); updated(); addToPricesHash(asset, currentPrice); } function addAssets(address[] calldata assets_, uint256[] calldata prices_) external onlyOwner { require(assets_.length != 0 && assets_.length == prices_.length, "MetadataOracle: BAD_LENGTH"); uint256 length = assets_.length; uint64 pricesHash = status.pricesHash; uint256 id = assets.length; for (uint256 i = 0; i < length; i++) { address asset = assets_[i]; uint256 currentPrice = prices_[i]; require(!hasAsset(asset), "MetadataOracle: ASSET_EXISTS"); assetId[asset] = id; assets.push(asset); prices.push(currentPrice); setDelta(id, NO_DELTA); id++; pricesHash = uint64(uint256(keccak256(abi.encodePacked(pricesHash, asset, currentPrice)))); } status.pricesHash = pricesHash; updated(); } function setPrice(address asset, uint256 price) external onlyOwner { require(hasAsset(asset), "MetadataOracle: ASSET_NOT_FOUND"); uint256 id = assetId[asset]; prices[id] = price; setDelta(id, NO_DELTA); updated(); addToPricesHash(asset, price); } function setPrices(address[] calldata assets_, uint256[] calldata prices_) external onlyOwner { require(assets_.length != 0 && assets_.length == prices_.length, "MetadataOracle: BAD_LENGTH"); uint256 length = assets_.length; uint64 pricesHash = status.pricesHash; for (uint256 i = 0; i < length; i++) { address asset = assets_[i]; uint256 price = prices_[i]; require(hasAsset(asset), "MetadataOracle: ASSET_NOT_FOUND"); uint256 id = assetId[asset]; prices[id] = price; setDelta(id, NO_DELTA); pricesHash = uint64(uint256(keccak256(abi.encodePacked(pricesHash, asset, price)))); } status.pricesHash = pricesHash; updated(); } // deltas := [slot], [slot ...] // slot := delta, [delta ...], zero padding up to 256 bits // delta := signed DELTA_BITS-bit number, to be used as an exponent of DELTA_BASE function updateDeltas(bytes calldata deltas, uint64 pricesHashCheck) external onlyOwner { uint256 assetsNum = assets.length; if (0 == assetsNum) { require(0 == deltas.length, "MetadataOracle: WRONG_LENGTH"); return; } uint256 slots = (assetsNum - 1) / DELTAS_PER_SLOT + 1; require(deltas.length == 32 * slots, "MetadataOracle: WRONG_LENGTH"); uint256 currentPricesHash = status.pricesHash; require(pricesHashCheck == currentPricesHash, "MetadataOracle: STALE_UPDATE"); status.pricesHash = uint64(uint256(keccak256(abi.encodePacked(currentPricesHash, deltas)))); updated(); // calldata pointer: selector + deltas position + uint(pricesHashCheck) + length word uint256 srcOffset = 4 + 32 + 32 + 32; uint256 dstSlot = DELTAS_LOCATION; // storage pointer for (uint256 i = 0; i < slots; i++) { assembly { sstore(dstSlot, calldataload(srcOffset)) } srcOffset += 32; dstSlot++; } } /// @dev Gets raw asset delta (signed logarithm encoded as two's complement) function getDelta(uint256 id) internal view returns (uint256) { uint256 slot = DELTAS_LOCATION + id / DELTAS_PER_SLOT; uint256 deltaBlock; assembly { deltaBlock := sload(slot) } // Unpack one delta from the slot contents return (deltaBlock >> getBitsAfterDelta(id)) & DELTA_MASK; } /// @dev Sets raw asset delta (signed logarithm encoded as two's complement) function setDelta(uint256 id, uint256 delta) internal { uint256 dstSlot = DELTAS_LOCATION + id / DELTAS_PER_SLOT; uint256 current; assembly { current := sload(dstSlot) } // Clear the delta & overwrite it with new content keeping others intact uint256 bitsAfterDelta = getBitsAfterDelta(id); current &= ~(DELTA_MASK << bitsAfterDelta); // setting zeroes current |= delta << bitsAfterDelta; // writing delta assembly { sstore(dstSlot, current) } } function getBitsAfterDelta(uint256 id) internal pure returns (uint256) { uint256 deltaIdx = id % DELTAS_PER_SLOT; return (DELTAS_PER_SLOT - 1 - deltaIdx) * DELTA_BITS + SLOT_PADDING_BITS; } function getPrice(uint256 id) internal view returns (uint256) { uint256 rawDelta = getDelta(id); int128 delta; if (0 == rawDelta & (1 << (DELTA_BITS - 1))) { // Non-negative power delta = DELTA_BASE.pow(rawDelta); } else { // Negative power, converting from two's complement delta = ABDK_ONE.div(DELTA_BASE.pow(DELTA_MODULO - rawDelta)); } uint256 basePrice = prices[id]; return delta.mulu(basePrice); } function addToPricesHash(address asset, uint256 currentPrice) internal { status.pricesHash = uint64(uint256(keccak256(abi.encodePacked(status.pricesHash, asset, currentPrice)))); } function updated() internal virtual { uint256 ts = block.timestamp; assert(ts <= type(uint32).max); status.updateTS = uint32(ts); } }
Non-negative power Negative power, converting from two's complement
function getPrice(uint256 id) internal view returns (uint256) { uint256 rawDelta = getDelta(id); int128 delta; if (0 == rawDelta & (1 << (DELTA_BITS - 1))) { delta = DELTA_BASE.pow(rawDelta); } else { delta = ABDK_ONE.div(DELTA_BASE.pow(DELTA_MODULO - rawDelta)); } uint256 basePrice = prices[id]; return delta.mulu(basePrice); }
5,973,723
./partial_match/1/0x63A7Ceb30Be1d4b108F597B4A294DB2973e6772c/sources/contracts/utils/TransferHelper.sol
bytes4(keccak256(bytes('transfer(address,uint256)')));
function safeTransferToken( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED"); }
3,680,763
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 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); } /** * @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, 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 defaut 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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal 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"); _balances[account] = accountBalance - amount; _totalSupply -= 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 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 { } } /** * Depositor is a ERC20 proxy for the MultiverseToken whose only supported transaction is * `transfer()`, which is converted to a `MultiverseToken.depositFrom()` call with the * `depository` associated via `MultiverseToken.createDepositor()`. */ contract Depositor is Context, IERC20, IERC20Metadata { MultiverseToken private _multiverseToken; string private _name; constructor(MultiverseToken multiverseToken_, string memory name_) { _multiverseToken = multiverseToken_; _name = name_; } /** * @dev The Despositor fulfills the ERC20 `transfer` operation by transferring * the specified `value` from the `msg.sender` to the Depositor's `depository`, * destined for specified `account`. */ function transfer(address account, uint256 value) public virtual override returns (bool) { return _multiverseToken.depositFrom(_msgSender(), account, value); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _multiverseToken.symbol(); } function decimals() public view virtual override returns (uint8) { return _multiverseToken.decimals(); } function totalSupply() public view virtual override returns (uint256) { return _multiverseToken.totalSupply(); } function balanceOf(address account) public view virtual override returns (uint256) { return _multiverseToken.balanceOf(account); } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _multiverseToken.allowance(owner, spender); } function approve(address, uint256) public virtual override returns (bool) { require(false, "approve() is not supported. call the MultiverseToken directly"); return false; } function transferFrom(address, address, uint256) public virtual override returns (bool) { require(false, "transferFrom() is not supported. call the MultiverseToken directly"); return false; } } /** * ERC20 token for the Multiverse. */ contract MultiverseToken is ERC20 { address private reserve; mapping (address => address) private depositors; /** * @dev Constructor that initializes the initial token supply under the care of the "reserve" account. */ constructor( string memory name, string memory symbol, uint256 initialSupply, address reserveAddr ) ERC20(name, symbol) { reserve = reserveAddr; emit ReserveChanged(address(0), reserve); _mint(reserve, initialSupply); } modifier reserved() { require(_msgSender() == reserve, "operation is reserved"); _; } /** * @dev Decreases the money supply. */ function burn(uint256 value) reserved external { _burn(reserve, value); } /** * @dev Emitted when the `reserve` is changed from one account (`from`) to * another (`to`). */ event ReserveChanged(address indexed from, address indexed to); /** * @dev Transfers the role of the reserve to a new account (e.g. key rotation). * Note that allowances are NOT transferred. */ function setReserve(address newReserve) reserved external { transfer(newReserve, balanceOf(reserve)); reserve = newReserve; emit ReserveChanged(_msgSender(), newReserve); } /** * @dev Gets the current reserve. */ function getReserve() external view returns (address) { return reserve; } /** @dev Emitted when a Deposit is made to a `depository` destined for a depository-managed `account`. */ event Deposit(address indexed from, address indexed depository, uint256 value, address indexed account); /** * @dev Transfers `value` tokens from the `msg.sender` to the `depository`, destined for * the specified `account`. This emits an ERC20 `Transfer()` event to the depository, and a corresponding * `Deposit()` event that indicates the `account` address, to be managed off-chain by the depository. */ function deposit(address depository, uint256 value, address account) external returns (bool) { return _deposit(_msgSender(), depository, value, account); } /** * @dev A _deposit() is essentially a transfer to a `depository` that emits a special `Deposit()` * event reporting the destination `account`, which is managed off-chain by the depository. */ function _deposit(address from, address depository, uint256 value, address account) internal returns (bool) { emit Deposit(from, depository, value, account); _transfer(from, depository, value); return true; } /** * @dev Emitted when a Depositor is created. */ event DepositorCreated(address depositor, address indexed depository); /** * @dev Deploys a new Depositor ERC20 contract that deposits to a specified `depository` * in response to the `transfer(account, value)` operation, essentially converting it * to `deposit(despository, value, account)` on behalf of the sender. Only the reserve * can call this method. */ function createDepositor(string memory name, address depository) reserved external returns (address) { require(depository != address(0), "cannot deposit to zero address"); Depositor depositor = new Depositor(this, name); address depositorAddress = address(depositor); depositors[depositorAddress] = depository; emit DepositorCreated(depositorAddress, depository); return depositorAddress; } /** @dev Returns the depository for the specified Depositor address. */ function getDepository(address depositor) external view returns (address) { return depositors[depositor]; } /** * @dev Transfers `value` tokens from the `from` address to the calling Depositor's depository, * emiting a `Deposit()` event that indicates the destination `account`. Only Depositors created * via `createDepositor()` can call this method. */ function depositFrom(address from, address account, uint256 value) external returns (bool) { address depository = depositors[_msgSender()]; require(depository != address(0), "depositFrom() can only be called by Depositors created by this contract"); return _deposit(from, depository, value, account); } }
Returns the depository for the specified Depositor address. /
function getDepository(address depositor) external view returns (address) { return depositors[depositor]; }
6,254,581
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @author token * This treasury contract has been developed by token.info */ import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import "../libs/IUniFactory.sol"; import "../libs/IUniRouter02.sol"; import "../libs/IWETH.sol"; interface IStaking { function performanceFee() external view returns(uint256); function setServiceInfo(address _addr, uint256 _fee) external; } interface IFarm { function setBuyBackWallet(address _addr) external; } contract ShamanTreasury is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Whether it is initialized bool private isInitialized; uint256 private TIME_UNIT = 1 days; IERC20 public token; address public dividendToken; address public pair; uint256 public period = 30; // 30 days uint256 public withdrawalLimit = 500; // 5% of total supply uint256 public liquidityWithdrawalLimit = 2000; // 20% of LP supply uint256 public buybackRate = 9500; // 95% uint256 public addLiquidityRate = 9400; // 94% uint256 private startTime; uint256 private sumWithdrawals = 0; uint256 private sumLiquidityWithdrawals = 0; uint256 public performanceFee = 100; // 1% uint256 public performanceLpFee = 200; // 2% address public feeWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F; // swap router and path, slipPage address public uniRouterAddress; address[] public wNativeToTokenPath; uint256 public slippageFactor = 800; // 20% uint256 public constant slippageFactorUL = 995; event TokenBuyBack(uint256 amountETH, uint256 amountToken); event LiquidityAdded(uint256 amountETH, uint256 amountToken, uint256 liquidity); event SetSwapConfig(address router, uint256 slipPage, address[] path); event TransferBuyBackWallet(address staking, address wallet); event LiquidityWithdrawn(uint256 amount); event Withdrawn(uint256 amount); event AddLiquidityRateUpdated(uint256 percent); event BuybackRateUpdated(uint256 percent); event PeriodUpdated(uint256 duration); event LiquidityWithdrawLimitUpdated(uint256 percent); event WithdrawLimitUpdated(uint256 percent); event ServiceInfoUpdated(address wallet, uint256 performanceFee, uint256 liquidityFee); constructor() {} /** * @notice Initialize the contract * @param _token: token address * @param _dividendToken: reflection token address * @param _uniRouter: uniswap router address for swap tokens * @param _wNativeToTokenPath: swap path to buy token */ function initialize( IERC20 _token, address _dividendToken, address _uniRouter, address[] memory _wNativeToTokenPath ) external onlyOwner { require(!isInitialized, "Already initialized"); // Make this contract initialized isInitialized = true; token = _token; dividendToken = _dividendToken; pair = IUniV2Factory(IUniRouter02(_uniRouter).factory()).getPair(_wNativeToTokenPath[0], address(token)); uniRouterAddress = _uniRouter; wNativeToTokenPath = _wNativeToTokenPath; } /** * @notice Buy token from BNB */ function buyBack() external onlyOwner nonReentrant{ uint256 ethAmt = address(this).balance; uint256 _fee = ethAmt.mul(performanceFee).div(10000); if(_fee > 0) { payable(feeWallet).transfer(_fee); ethAmt = ethAmt.sub(_fee); } ethAmt = ethAmt.mul(buybackRate).div(10000); if(ethAmt > 0) { uint256[] memory amounts = _safeSwapEth(ethAmt, wNativeToTokenPath, address(this)); emit TokenBuyBack(amounts[0], amounts[amounts.length - 1]); } } /** * @notice Add liquidity */ function addLiquidity() external onlyOwner nonReentrant{ uint256 ethAmt = address(this).balance; uint256 _fee = ethAmt.mul(performanceLpFee).div(10000); if(_fee > 0) { payable(feeWallet).transfer(_fee); ethAmt = ethAmt.sub(_fee); } ethAmt = ethAmt.mul(addLiquidityRate).div(10000).div(2); if(ethAmt > 0) { uint256[] memory amounts = _safeSwapEth(ethAmt, wNativeToTokenPath, address(this)); uint256 _tokenAmt = amounts[amounts.length - 1]; emit TokenBuyBack(amounts[0], _tokenAmt); (uint256 amountToken, uint256 amountETH, uint256 liquidity) = _addLiquidityEth(address(token), ethAmt, _tokenAmt, address(this)); emit LiquidityAdded(amountETH, amountToken, liquidity); } } /** * @notice Withdraw brews as much as maximum 5% of total supply * @param _amount: amount to withdraw */ function withdraw(uint256 _amount) external onlyOwner { uint256 tokenAmt = token.balanceOf(address(this)); require(_amount > 0 && _amount <= tokenAmt, "Invalid Amount"); if(block.timestamp.sub(startTime) > period.mul(TIME_UNIT)) { startTime = block.timestamp; sumWithdrawals = 0; } uint256 limit = withdrawalLimit.mul(token.totalSupply()).div(10000); require(sumWithdrawals.add(_amount) <= limit, "exceed maximum withdrawal limit for 30 days"); token.safeTransfer(msg.sender, _amount); emit Withdrawn(_amount); } /** * @notice Withdraw brews as much as maximum 20% of lp supply * @param _amount: liquidity amount to withdraw */ function withdrawLiquidity(uint256 _amount) external onlyOwner { uint256 tokenAmt = IERC20(pair).balanceOf(address(this)); require(_amount > 0 && _amount <= tokenAmt, "Invalid Amount"); if(block.timestamp.sub(startTime) > period.mul(TIME_UNIT)) { startTime = block.timestamp; sumLiquidityWithdrawals = 0; } uint256 limit = liquidityWithdrawalLimit.mul(IERC20(pair).totalSupply()).div(10000); require(sumLiquidityWithdrawals.add(_amount) <= limit, "exceed maximum LP withdrawal limit for 30 days"); IERC20(pair).safeTransfer(msg.sender, _amount); emit LiquidityWithdrawn(_amount); } /** * @notice Withdraw tokens * @dev Needs to be for emergency. */ function emergencyWithdraw() external onlyOwner { uint256 tokenAmt = token.balanceOf(address(this)); if(tokenAmt > 0) { token.transfer(msg.sender, tokenAmt); } tokenAmt = IERC20(pair).balanceOf(address(this)); if(tokenAmt > 0) { IERC20(pair).transfer(msg.sender, tokenAmt); } uint256 ethAmt = address(this).balance; if(ethAmt > 0) { payable(msg.sender).transfer(ethAmt); } } /** * @notice Harvest reflection for token */ function harvest() external onlyOwner { if(dividendToken == address(0x0)) { uint256 ethAmt = address(dividendToken).balance; if(ethAmt > 0) { payable(msg.sender).transfer(ethAmt); } } else { uint256 tokenAmt = IERC20(dividendToken).balanceOf(address(this)); if(tokenAmt > 0) { IERC20(dividendToken).transfer(msg.sender, tokenAmt); } } } /** * @notice Set duration for withdraw limit * @param _period: duration */ function setWithdrawalLimitPeriod(uint256 _period) external onlyOwner { require(_period >= 10, "small period"); period = _period; emit PeriodUpdated(_period); } /** * @notice Set liquidity withdraw limit * @param _percent: percentage of LP supply in point */ function setLiquidityWithdrawalLimit(uint256 _percent) external onlyOwner { require(_percent < 10000, "Invalid percentage"); liquidityWithdrawalLimit = _percent; emit LiquidityWithdrawLimitUpdated(_percent); } /** * @notice Set withdraw limit * @param _percent: percentage of total supply in point */ function setWithdrawalLimit(uint256 _percent) external onlyOwner { require(_percent < 10000, "Invalid percentage"); withdrawalLimit = _percent; emit WithdrawLimitUpdated(_percent); } /** * @notice Set buyback amount * @param _percent: percentage in point */ function setBuybackRate(uint256 _percent) external onlyOwner { require(_percent < 10000, "Invalid percentage"); buybackRate = _percent; emit BuybackRateUpdated(_percent); } /** * @notice Set addliquidy amount * @param _percent: percentage in point */ function setAddLiquidityRate(uint256 _percent) external onlyOwner { require(_percent < 10000, "Invalid percentage"); addLiquidityRate = _percent; emit AddLiquidityRateUpdated(_percent); } function setServiceInfo(address _wallet, uint256 _fee) external { require(msg.sender == feeWallet, "Invalid setter"); require(_wallet != feeWallet && _wallet != address(0x0), "Invalid new wallet"); require(_fee < 500, "invalid performance fee"); feeWallet = _wallet; performanceFee = _fee; performanceLpFee = _fee.mul(2); emit ServiceInfoUpdated(_wallet, performanceFee, performanceLpFee); } /** * @notice Set buyback wallet of farm contract * @param _uniRouter: dex router address * @param _slipPage: slip page for swap * @param _path: bnb-brews path */ function setSwapSettings(address _uniRouter, uint256 _slipPage, address[] memory _path) external onlyOwner { require(_slipPage < 1000, "Invalid percentage"); uniRouterAddress = _uniRouter; slippageFactor = _slipPage; wNativeToTokenPath = _path; emit SetSwapConfig(_uniRouter, _slipPage, _path); } /** * @notice set buyback wallet of farm contract * @param _farm: farm contract address * @param _addr: buyback wallet address */ function setFarmServiceInfo(address _farm, address _addr) external onlyOwner { require(_farm != address(0x0) && _addr != address(0x0), "Invalid Address"); IFarm(_farm).setBuyBackWallet(_addr); emit TransferBuyBackWallet(_farm, _addr); } /** * @notice set buyback wallet of staking contract * @param _staking: staking contract address * @param _addr: buyback wallet address */ function setStakingServiceInfo(address _staking, address _addr) external onlyOwner { require(_staking != address(0x0) && _addr != address(0x0), "Invalid Address"); uint256 _fee = IStaking(_staking).performanceFee(); IStaking(_staking).setServiceInfo(_addr, _fee); emit TransferBuyBackWallet(_staking, _addr); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _token: the address of the token to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _token) external onlyOwner { require(_token != address(token) && _token != dividendToken && _token != pair, "Cannot be token & dividend token, pair"); if(_token == address(0x0)) { uint256 _tokenAmount = address(this).balance; payable(msg.sender).transfer(_tokenAmount); } else { uint256 _tokenAmount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, _tokenAmount); } } /************************ ** Internal Methods *************************/ /* * @notice get token from ETH via swap. */ function _safeSwapEth( uint256 _amountIn, address[] memory _path, address _to ) internal returns (uint256[] memory amounts) { amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path); uint256 amountOut = amounts[amounts.length.sub(1)]; IUniRouter02(uniRouterAddress).swapExactETHForTokensSupportingFeeOnTransferTokens{value: _amountIn}( amountOut.mul(slippageFactor).div(1000), _path, _to, block.timestamp.add(600) ); } /* * @notice Add liquidity for token-BNB pair. */ function _addLiquidityEth( address _token, uint256 _ethAmt, uint256 _tokenAmt, address _to ) internal returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) { IERC20(_token).safeIncreaseAllowance(uniRouterAddress, _tokenAmt); (amountToken, amountETH, liquidity) = IUniRouter02(uniRouterAddress).addLiquidityETH{value: _ethAmt}( address(_token), _tokenAmt, 0, 0, _to, block.timestamp.add(600) ); IERC20(_token).safeApprove(uniRouterAddress, uint256(0)); } receive() external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IUniRouter01.sol"; interface IUniRouter02 is IUniRouter01 { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // 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 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniRouter01 { 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); }
Set buyback wallet of farm contract _uniRouter: dex router address _slipPage: slip page for swap _path: bnb-brews path/
function setSwapSettings(address _uniRouter, uint256 _slipPage, address[] memory _path) external onlyOwner { require(_slipPage < 1000, "Invalid percentage"); uniRouterAddress = _uniRouter; slippageFactor = _slipPage; wNativeToTokenPath = _path; emit SetSwapConfig(_uniRouter, _slipPage, _path); }
14,846,743
./partial_match/3/0xFDFA7AB1bf2671A184413Fc99628Bd23980Ce95e/sources/FaucetToken.sol
Added for testing purposes
function transfer(address dst, uint256 amount) external returns (bool success) { if (failTransferToAddresses[dst]) { return false; } balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount, "Insufficient balance"); balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow"); emit Transfer(msg.sender, dst, amount); return true; }
5,240,745
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./GenerationManager.sol"; import "./DarkMatter.sol"; import "./interfaces/IStackOsNFT.sol"; import "./interfaces/IStackOsNFTBasic.sol"; import "./Exchange.sol"; // import "hardhat/console.sol"; contract Royalty is Ownable, ReentrancyGuard { using Counters for Counters.Counter; event SetFeeAddress(address payable _feeAddress); event SetWETH(IERC20 WETH); event SetFeePercent(uint256 _percent); event SetMinEthPerCycle(uint256 amount); event NewCycle(uint256 newCycleId); event SetCycleDuration(uint256 _seconds); Counters.Counter public counter; // counting cycles uint256 private constant HUNDRED_PERCENT = 10000; GenerationManager private immutable generations; DarkMatter private immutable darkMatter; Exchange private immutable exchange; IERC20 private WETH; // for Matic network address payable private feeAddress; IERC20 private stackToken; uint256 private feePercent; uint256 public minEthPerCycle; uint256 public cycleDuration = 30 days; uint256 public adminWithdrawable; struct GenData { // total received by each generation in cycle uint256 balance; // whether reward for this token in this cycle for this generation is claimed mapping(uint256 => mapping(uint256 => bool)) isClaimed; } struct Cycle { // cycle started timestamp uint256 startTimestamp; // this is used in admin withdrawable // and for cycle ending condition uint256 totalBalance; // per generation balance mapping(uint256 => GenData) genData; } mapping(uint256 => Cycle) public cycles; // generationId => total maxSupply of generations below plus this one mapping(uint256 => uint256) public maxSupplys; constructor( GenerationManager _generations, DarkMatter _darkMatter, Exchange _exchange, address payable _feeAddress, IERC20 _stackToken, uint256 _minEthPerCycle ) { generations = _generations; darkMatter = _darkMatter; exchange = _exchange; feeAddress = _feeAddress; stackToken = _stackToken; minEthPerCycle = _minEthPerCycle; cycles[counter.current()].startTimestamp = block.timestamp; } /** * @notice Deposit royalty so that NFT holders can claim it later. * @notice Deposits to the latest generation at this time, * so that any generation below can claim that. */ receive() external payable { uint256 generationId = generations.count() - 1; // take fee from deposits uint256 feePart = msg.value * feePercent / HUNDRED_PERCENT; uint256 valuePart = msg.value - feePart; updateCycle(); // console.log("receive", generationId, counter.current(), valuePart); cycles[counter.current()].totalBalance += valuePart; cycles[counter.current()].genData[generationId].balance += valuePart; (bool success, ) = feeAddress.call{value: feePart}(""); require(success, "Transfer failed."); } /** * @notice Deposit royalty so that NFT holders can claim it later. * @param generationId Which generation balance receives royalty. */ function onReceive(uint256 generationId) external payable nonReentrant { require(generationId < generations.count(), "Wrong generationId"); // take fee from deposits uint256 feePart = msg.value * feePercent / HUNDRED_PERCENT; uint256 valuePart = msg.value - feePart; updateCycle(); // console.log("onReceive", generationId, counter.current(), valuePart); cycles[counter.current()].totalBalance += valuePart; cycles[counter.current()].genData[generationId].balance += valuePart; (bool success, ) = feeAddress.call{value: feePart}(""); require(success, "Transfer failed."); } function updateCycle() private { // is current cycle lasts enough? if ( cycles[counter.current()].startTimestamp + cycleDuration < block.timestamp ) { // is current cycle got enough ether? if (cycles[counter.current()].totalBalance >= minEthPerCycle) { // start new cycle counter.increment(); cycles[counter.current()].startTimestamp = block.timestamp; if(counter.current() > 3) { // subtract 4 because need to ignore current cycle + 3 cycles before it uint256 removeIndex = counter.current() - 4; adminWithdrawable += cycles[removeIndex].totalBalance; // console.log("adminWithdrawable: %s, added: %s", adminWithdrawable, cycles[removeIndex].totalBalance); cycles[removeIndex].totalBalance = 0; } emit NewCycle(counter.current()); } } } function genDataBalance( uint256 cycleId, uint256 generationFeeBalanceId ) external view returns (uint256) { return cycles[cycleId].genData[generationFeeBalanceId].balance; } function isClaimed( uint256 cycleId, uint256 generationFeeBalanceId, uint256 generationId, uint256 tokenId ) external view returns (bool) { return cycles[cycleId] .genData[generationFeeBalanceId] .isClaimed[generationId][tokenId]; } /** * @dev Save total max supply of all preveious generations + added one. */ function onGenerationAdded( uint256 generationId, address stack ) external { require(address(msg.sender) == address(generations)); if(generationId == 0) { maxSupplys[generationId] = IStackOsNFT(stack).getMaxSupply(); } else { maxSupplys[generationId] = maxSupplys[generationId - 1] + IStackOsNFT(stack).getMaxSupply(); } } /** * @notice Set cycle duration. * @dev Could only be invoked by the contract owner. */ function setCycleDuration(uint256 _seconds) external onlyOwner { require(_seconds > 0, "Must be not zero"); cycleDuration = _seconds; emit SetCycleDuration(_seconds); } /** * @notice Set fee address. * @notice Fee transfered when contract receives new royalties. * @param _feeAddress Fee address. * @dev Could only be invoked by the contract owner. */ function setFeeAddress(address payable _feeAddress) external onlyOwner { require(_feeAddress != address(0), "Must be not zero-address"); feeAddress = _feeAddress; emit SetFeeAddress(_feeAddress); } /** * @notice Set WETH address. * @notice Used to claim royalty in weth instead of matic. * @param _WETH WETH address. * @dev Could only be invoked by the contract owner. */ function setWETH(IERC20 _WETH) external onlyOwner { require(address(_WETH) != address(0), "Must be not zero-address"); WETH = _WETH; emit SetWETH(_WETH); } /** * @notice Set minimum eth needed to end cycle. * @param amount Amount of eth. * @dev Could only be invoked by the contract owner. */ function setMinEthPerCycle(uint256 amount) external onlyOwner { require(amount > 0); minEthPerCycle = amount; emit SetMinEthPerCycle(amount); } /** * @notice Set fee percent taken everytime royalties recieved. * @param _percent Fee basis points. * @dev Could only be invoked by the contract owner. */ function setFeePercent(uint256 _percent) external onlyOwner { require(feePercent <= HUNDRED_PERCENT, "invalid fee basis points"); feePercent = _percent; emit SetFeePercent(_percent); } /** * @notice Claim royalty for tokens. * @param _generationId Generation id of tokens that will claim royalty. * @param _tokenIds Token ids who will claim royalty. * @param _genIds Ids of generation balances to claim royalties. * @dev Tokens must be owned by the caller. * @dev When generation tranded on market, fee is transfered to * dedicated balance of this generation in royalty contract (_genIds). * Then tokens that have lower generation id can claim part of this. * So token of generation 1 can claim from genId 1,2,3. * But token of generation 5 can't claim from genId 1. */ function claim( uint256 _generationId, uint256[] calldata _tokenIds, uint256[] calldata _genIds ) external { _claim(_generationId, _tokenIds, 0, false, _genIds); } /** * @notice Same as `claim` but caller receives WETH. * @dev WETH address must be set in the contract. */ function claimWETH( uint256 _generationId, uint256[] calldata _tokenIds, uint256[] calldata _genIds ) external { require(address(WETH) != address(0), "Wrong WETH address"); _claim(_generationId, _tokenIds, 0, true, _genIds); } /** * @notice Purchase StackNFTs for royalties. * @notice Caller will receive the left over amount of royalties as STACK tokens. * @param _generationId Generation id to claim royalty and purchase, should be greater than 0. * @param _tokenIds Token ids that claim royalty. * @param _mintNum Amount to mint. * @param _genIds Ids of generation balances to claim royalties. * @dev Tokens must be owned by the caller. * @dev `_generationId` should be greater than 0. * @dev See `claim` function description for info on `_genIds`. */ function purchaseNewNft( uint256 _generationId, uint256[] calldata _tokenIds, uint256 _mintNum, uint256[] calldata _genIds ) external nonReentrant { require(_generationId > 0, "Must be not first generation"); require(_mintNum > 0, "Mint num is 0"); _claim(_generationId, _tokenIds, _mintNum, false, _genIds); } function _claim( uint256 generationId, uint256[] calldata tokenIds, uint256 _mintNum, bool _claimWETH, uint256[] calldata _genIds ) internal { require(_genIds.length > 0, "No gen ids"); require(address(this).balance > 0, "No royalty"); IStackOsNFTBasic stack = IStackOsNFTBasic(address(generations.get(generationId))); updateCycle(); // console.log("current cycle in _claim", counter.current()); require(counter.current() > 0, "Still first cycle"); uint256 reward; // iterate over tokens from args for (uint256 i; i < tokenIds.length; i++) { // console.log("tokenId claim ", tokenIds[i]); require( darkMatter.isOwnStackOrDarkMatter( msg.sender, generationId, tokenIds[i] ), "Not owner" ); reward += calcReward(generationId, tokenIds[i], _genIds); } require(reward > 0, "Nothing to claim"); // console.log("reward claim:", reward); if (_mintNum == 0) { if(_claimWETH) { uint256 wethReceived = exchange.swapExactETHForTokens{value: reward}(WETH); require(WETH.transfer(msg.sender, wethReceived), "WETH: transfer failed"); } else { (bool success, ) = payable(msg.sender).call{value: reward}( "" ); require(success, "Transfer failed"); } } else { uint256 stackReceived = exchange.swapExactETHForTokens{value: reward}(stackToken); stackToken.approve(address(stack), stackReceived); uint256 spendAmount = stack.mintFromRoyaltyRewards( _mintNum, msg.sender ); // console.log("reward claim stack:", stackReceived, stackReceived - spendAmount); stackToken.transfer(msg.sender, stackReceived - spendAmount); } } function calcReward( uint256 generationId, uint256 tokenId, uint256[] calldata _genIds ) private returns (uint256 reward) { for (uint256 o = 1; o <= 3; o++) { uint256 cycleId = counter.current() - o; uint256 removeFromCycle; for (uint256 j; j < _genIds.length; j++) { require(_genIds[j] >= generationId, "Bad gen id"); require(_genIds[j] < generations.count(), "genId not exists"); GenData storage genData = cycles[cycleId].genData[_genIds[j]]; if ( genData.balance > 0 && genData.isClaimed[generationId][tokenId] == false ) { uint256 claimAmount = genData.balance / maxSupplys[_genIds[j]]; reward += claimAmount; removeFromCycle += claimAmount; genData.isClaimed[generationId][tokenId] = true; // console.log(address(this).balance, maxSupplys[ _genIds[j]]); } // console.log(cycleId, _genIds[j], genData.balance, reward); } cycles[cycleId].totalBalance -= removeFromCycle; if(cycleId == 0) break; } } /** * @notice Get pending royalty for NFT. * @param generationId StackOS generation id. * @param tokenIds Token ids. * @return withdrawableRoyalty Total withdrawable royalty from all cycles and all balances. */ function pendingRoyalty( uint256 generationId, uint256[] calldata tokenIds ) external view returns (uint256 withdrawableRoyalty) { require(generationId < generations.count(), "Wrong generation id"); uint256 _counterCurrent = counter.current(); if ( cycles[counter.current()].startTimestamp + cycleDuration < block.timestamp ) { if (cycles[counter.current()].totalBalance >= minEthPerCycle) { _counterCurrent += 1; } } require(_counterCurrent > 0, "Still first cycle"); uint256 reward; // iterate over tokens from args for (uint256 i; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; for (uint256 o = 1; o <= 3; o++) { uint256 cycleId = _counterCurrent - o; // console.log("pending", cycleId, _counterCurrent); // j is pool id, should be greater or equal than token generation for (uint256 j = generationId; j < generations.count(); j++) { GenData storage genData = cycles[cycleId].genData[j]; if ( genData.balance > 0 && // verify reward is unclaimed genData.isClaimed[generationId][tokenId] == false ) { reward += genData.balance / maxSupplys[j]; } } if(cycleId == 0) break; } } withdrawableRoyalty = reward; } function adminWithdraw() external onlyOwner { require(adminWithdrawable > 0, "Nothing to withdraw"); (bool success, ) = payable(msg.sender).call{value: adminWithdrawable}( "" ); require(success, "Transfer failed"); } }
Purchase StackNFTs for royalties. Caller will receive the left over amount of royalties as STACK tokens. _generationId Generation id to claim royalty and purchase, should be greater than 0. _tokenIds Token ids that claim royalty. _mintNum Amount to mint. _genIds Ids of generation balances to claim royalties. Tokens must be owned by the caller. `_generationId` should be greater than 0. See `claim` function description for info on `_genIds`./
function purchaseNewNft( uint256 _generationId, uint256[] calldata _tokenIds, uint256 _mintNum, uint256[] calldata _genIds ) external nonReentrant { require(_generationId > 0, "Must be not first generation"); require(_mintNum > 0, "Mint num is 0"); _claim(_generationId, _tokenIds, _mintNum, false, _genIds); }
1,078,195
./full_match/43113/0x98A992392858d98D2715fb116915bF54cF1A175E/sources/registry/ENSRegistry.sol
Sets the resolver address for the specified node. _node The node to update. _resolver The address of the resolver./
function setResolver(bytes32 _node, address _resolver) public virtual override authorised(_node) { emit NewResolver(_node, _resolver); records[_node].resolver = _resolver; }
7,167,534
./full_match/43113/0x7adeEB2f6145796b0eb5e7FC9Cd42fb81f05778C/sources/contracts/AG.sol
string memory _name, string memory _descr, uint duration, uint _ballotType 0=perAPA 1=perAddressBallotType _ballotType proposals[nextPropId].id = nextPropId; proposals[nextPropId].name = _name; proposals[nextPropId].description = _descr; proposals[nextPropId].end = block.timestamp + duration; proposals[nextPropId].ballotType = _ballotType;
function createProposal( string[] memory _options ) external verifyNumApas(proposerApas) returns(uint) { for(uint i=0; i < _options.length; i++) { proposals[nextPropId].options[i] = Option(i, _options[i], 0 ); } nextPropId += 1; return _options.length; }
13,211,419
//! The receipting contract. Just records who sent what. //! //! Copyright 2017 Gavin Wood, Parity Technologies Ltd. //! //! 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.4.7; /// Will accept Ether "contributions" and record each both as a log and in a /// queryable record. contract Receipter { /// Constructor. `_admin` has the ability to pause the /// contribution period and, eventually, kill this contract. `_treasury` /// receives all funds. `_beginBlock` and `_endBlock` define the begin and /// end of the period. function Receipter(address _admin, address _treasury, uint _beginBlock, uint _endBlock) { admin = _admin; treasury = _treasury; beginBlock = _beginBlock; endBlock = _endBlock; } // Can only be called by _admin. modifier only_admin { if (msg.sender != admin) throw; _; } // Can only be called by prior to the period. modifier only_before_period { if (block.number >= beginBlock) throw; _; } // Can only be called during the period when not halted. modifier only_during_period { if (block.number < beginBlock || block.number >= endBlock || isHalted) throw; _; } // Can only be called during the period when halted. modifier only_during_halted_period { if (block.number < beginBlock || block.number >= endBlock || !isHalted) throw; _; } // Can only be called after the period. modifier only_after_period { if (block.number < endBlock || isHalted) throw; _; } // The value of the message must be sufficiently large to not be considered dust. modifier is_not_dust { if (msg.value < dust) throw; _; } /// Some contribution `amount` received from `recipient`. event Received(address indexed recipient, uint amount); /// Period halted abnormally. event Halted(); /// Period restarted after abnormal halt. event Unhalted(); /// Fallback function: receive a contribution from sender. function() payable { receiveFrom(msg.sender); } /// Receive a contribution from `_recipient`. function receiveFrom(address _recipient) payable only_during_period is_not_dust { if (!treasury.call.value(msg.value)()) throw; record[_recipient] += msg.value; total += msg.value; Received(_recipient, msg.value); } /// Halt the contribution period. Any attempt at contributing will fail. function halt() only_admin only_during_period { isHalted = true; Halted(); } /// Unhalt the contribution period. function unhalt() only_admin only_during_halted_period { isHalted = false; Unhalted(); } /// Kill this contract. function kill() only_admin only_after_period { suicide(treasury); } // How much is enough? uint public constant dust = 100 finney; // Who can halt/unhalt/kill? address public admin; // Who gets the stash? address public treasury; // When does the contribution period begin? uint public beginBlock; // When does the period end? uint public endBlock; // Are contributions abnormally halted? bool public isHalted = false; mapping (address => uint) public record; uint public total = 0; } contract SignedReceipter is Receipter { function Receipter(address _admin, address _treasury, uint _beginBlock, uint _endBlock, bytes32 _sigHash) { admin = _admin; treasury = _treasury; beginBlock = _beginBlock; endBlock = _endBlock; sigHash = _sigHash; } modifier when_signed(address who, uint8 v, bytes32 r, bytes32 s) { if (ecrecover(sigHash, v, r, s) != who) throw; _; } function() payable { throw; } /// Fallback function: receive a contribution from sender. function receive(uint8 v, bytes32 r, bytes32 s) payable { receiveFrom(msg.sender, v, r, s); } /// Receive a contribution from `_recipient`. function receiveFrom(address _source, uint8 v, bytes32 r, bytes32 s) payable only_during_period is_not_dust when_signed(_source, v, r, s) { if (!treasury.call.value(msg.value)()) throw; record[_source] += msg.value; total += msg.value; Received(_source, msg.value); } bytes32 sigHash; }
Fallback function: receive a contribution from sender.
function receive(uint8 v, bytes32 r, bytes32 s) payable { receiveFrom(msg.sender, v, r, s); }
6,430,243
pragma solidity ^0.4.19; /** * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * license: MIT */ contract OwnableSimple { 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 OwnableSimple() 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; } } // based on axiomzen, MIT license contract RandomApi { uint64 _seed = 0; function random(uint64 maxExclusive) public returns (uint64 randomNumber) { // the blockhash of the current block (and future block) is 0 because it doesn't exist _seed = uint64(keccak256(keccak256(block.blockhash(block.number - 1), _seed), block.timestamp)); return _seed % maxExclusive; } function random256() public returns (uint256 randomNumber) { uint256 rand = uint256(keccak256(keccak256(block.blockhash(block.number - 1), _seed), block.timestamp)); _seed = uint64(rand); return rand; } } // @title ERC-165: Standard interface detection // https://github.com/ethereum/EIPs/issues/165 contract ERC165 { function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // @title ERC-721: Non-Fungible Tokens // @author Dieter Shirley (https://github.com/dete) // @dev https://github.com/ethereum/eips/issues/721 contract ERC721 is ERC165 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 count); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // described in old version of the standard // use the more flexible transferFrom function takeOwnership(uint256 _tokenId) external; // Events event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Optional // function name() public view returns (string); // function symbol() public view returns (string); function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl); // Optional, described in old version of the standard function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl); } // Based on strings library by Nick Johnson <[email protected]> // Apache license // https://github.com/Arachnid/solidity-stringutils library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } function len(slice self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } function toSliceB32(bytes32 self) internal pure returns (slice ret) { assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } function concat(slice self, slice other) internal pure returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } } /** * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract PausableSimple is OwnableSimple { event Pause(); event Unpause(); bool public paused = true; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // heavily modified from https://github.com/dob/auctionhouse/blob/master/contracts/AuctionHouse.sol // license: MIT // original author: Doug Petkanics ([email protected]) https://github.com/dob contract PresaleMarket is PausableSimple { struct Auction { address seller; uint256 price; // In wei, can be 0 } ERC721 public artworkContract; mapping (uint256 => Auction) artworkIdToAuction; // 0 means everything goes to the seller // 1000 means 1% // 2500 means 2.5% // 4000 means 4% // 50000 means 50% // 100000 means everything goes to us uint256 public distributionCut = 2500; bool public constant isPresaleMarket = true; event AuctionCreated(uint256 _artworkId, uint256 _price); event AuctionConcluded(uint256 _artworkId, uint256 _price, address _buyer); event AuctionCancelled(uint256 _artworkId); // mapping(address => uint256[]) public auctionsRunByUser; // No need to have a dedicated variable // Can be found by // iterate all artwork ids owned by this auction contract // get the auction object from artworkIdToAuction // get the seller property // return artwork id // however it would be a lot better if our second layer keeps track of it function auctionsRunByUser(address _address) external view returns(uint256[]) { uint256 allArtworkCount = artworkContract.balanceOf(this); uint256 artworkCount = 0; uint256[] memory allArtworkIds = new uint256[](allArtworkCount); for(uint256 i = 0; i < allArtworkCount; i++) { uint256 artworkId = artworkContract.tokenOfOwnerByIndex(this, i); Auction storage auction = artworkIdToAuction[artworkId]; if(auction.seller == _address) { allArtworkIds[artworkCount++] = artworkId; } } uint256[] memory result = new uint256[](artworkCount); for(i = 0; i < artworkCount; i++) { result[i] = allArtworkIds[i]; } return result; } // constructor. rename this if you rename the contract function PresaleMarket(address _artworkContract) public { artworkContract = ERC721(_artworkContract); } function bid(uint256 _artworkId) external payable whenNotPaused { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; require(auction.seller != msg.sender); uint256 price = auction.price; require(msg.value == price); address seller = auction.seller; delete artworkIdToAuction[_artworkId]; if(price > 0) { uint256 myCut = price * distributionCut / 100000; uint256 sellerCut = price - myCut; seller.transfer(sellerCut); } AuctionConcluded(_artworkId, price, msg.sender); artworkContract.transfer(msg.sender, _artworkId); } function getAuction(uint256 _artworkId) external view returns(address seller, uint256 price) { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; return (auction.seller, auction.price); } function createAuction(uint256 _artworkId, uint256 _price, address _originalOwner) external whenNotPaused { require(msg.sender == address(artworkContract)); // Will check to see if the seller owns the asset at the contract _takeOwnership(_originalOwner, _artworkId); Auction memory auction; auction.seller = _originalOwner; auction.price = _price; _createAuction(_artworkId, auction); } function _createAuction(uint256 _artworkId, Auction _auction) internal { artworkIdToAuction[_artworkId] = _auction; AuctionCreated(_artworkId, _auction.price); } function cancelAuction(uint256 _artworkId) external { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_artworkId, seller); } function _cancelAuction(uint256 _artworkId, address _owner) internal { delete artworkIdToAuction[_artworkId]; artworkContract.transfer(_owner, _artworkId); AuctionCancelled(_artworkId); } function withdraw() public onlyOwner { msg.sender.transfer(this.balance); } // only if there is a bug discovered and we need to migrate to a new market contract function cancelAuctionEmergency(uint256 _artworkId) external whenPaused onlyOwner { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; _cancelAuction(_artworkId, auction.seller); } // simple methods function _isAuctionExist(uint256 _artworkId) internal view returns(bool) { return artworkIdToAuction[_artworkId].seller != address(0); } function _owns(address _address, uint256 _artworkId) internal view returns(bool) { return artworkContract.ownerOf(_artworkId) == _address; } function _takeOwnership(address _originalOwner, uint256 _artworkId) internal { artworkContract.transferFrom(_originalOwner, this, _artworkId); } } contract Presale is OwnableSimple, RandomApi, ERC721 { using strings for *; // There are 4 batches available for presale. // A batch is a set of artworks and // we plan to release batches monthly. uint256 public batchCount; mapping(uint256 => uint256) public prices; mapping(uint256 => uint256) public supplies; mapping(uint256 => uint256) public sold; // Before each batch is released on the main contract, // we will disable transfers (including trading) // on this contract. // This is to prevent someone selling an artwork // on the presale contract when we are migrating // the artworks to the main contract. mapping(uint256 => bool) public isTransferDisabled; uint256[] public dnas; mapping(address => uint256) public ownerToTokenCount; mapping (uint256 => address) public artworkIdToOwner; mapping (uint256 => address) public artworkIdToTransferApproved; PresaleMarket public presaleMarket; bytes4 constant ERC165Signature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); // Latest version of ERC721 perhaps bytes4 constant ERC165Signature_ERC721A = bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); // as described in https://github.com/ethereum/eips/issues/721 // as of January 23, 2018 bytes4 constant ERC165Signature_ERC721B = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('tokenMetadata(uint256)')); function Presale() public { // Artworks are released in batches, which we plan to release // every month if possible. New batches might contain new characters, // or old characters in new poses. Later batches will definitely be // more rare. // By buying at presale, you have a chance to buy the // artwork at potentially 50% of the public release initial sales price. // Note that because the public release uses a sliding price system, // once an artwork is in the marketplace, the price will get lower until // someone buys it. // Example: You bought a batch 1 artwork at presale for 0.05 eth. // When the game launches, the first batch 1 artworks are generated // on the marketplace with the initial price of 0.1 eth. You sell yours // on the marketplace for 0.08 eth which is lower than the public release // initial sales price. If someone buys your artwork, you will get profit. // Note that we do not guarantee any profit whatsoever. The price of an // item we sell will get cheaper until someone buys it. So other people might wait // for the public release artworks to get cheaper and buy it instead of // buying yours. // Distribution of presale artworks: // When the game is released, all batch 1 presale artworks // will be immediately available for trading. // When other batches are released, first we will generate 10 artworks // on the marketplace. After that we will distribute the presale // artworks with the rate of around 10 every minute. // Note that because of mining uncertainties we cannot guarantee any // specific timings. // public release initial sales price >= 0.1 ether _addPresale(0.05 ether, 450); // public release initial sales price >= 0.24 ether _addPresale(0.12 ether, 325); // public release initial sales price >= 0.7 ether _addPresale(0.35 ether, 150); // public release initial sales price >= 2.0 ether _addPresale(1.0 ether, 75); } function buy(uint256 _batch) public payable { require(_batch < batchCount); require(msg.value == prices[_batch]); // we don't want to deal with refunds require(sold[_batch] < supplies[_batch]); sold[_batch]++; uint256 dna = _generateRandomDna(_batch); uint256 artworkId = dnas.push(dna) - 1; ownerToTokenCount[msg.sender]++; artworkIdToOwner[artworkId] = msg.sender; Transfer(0, msg.sender, artworkId); } function getArtworkInfo(uint256 _id) external view returns ( uint256 dna, address owner) { require(_id < totalSupply()); dna = dnas[_id]; owner = artworkIdToOwner[_id]; } function withdraw() public onlyOwner { msg.sender.transfer(this.balance); } function getBatchInfo(uint256 _batch) external view returns(uint256 price, uint256 supply, uint256 soldAmount) { require(_batch < batchCount); return (prices[_batch], supplies[_batch], sold[_batch]); } function setTransferDisabled(uint256 _batch, bool _isDisabled) external onlyOwner { require(_batch < batchCount); isTransferDisabled[_batch] = _isDisabled; } function setPresaleMarketAddress(address _address) public onlyOwner { PresaleMarket presaleMarketTest = PresaleMarket(_address); require(presaleMarketTest.isPresaleMarket()); presaleMarket = presaleMarketTest; } function sell(uint256 _artworkId, uint256 _price) external { require(_isOwnerOf(msg.sender, _artworkId)); require(_canTransferBatch(_artworkId)); _approveTransfer(_artworkId, presaleMarket); presaleMarket.createAuction(_artworkId, _price, msg.sender); } // Helper methods function _addPresale(uint256 _price, uint256 _supply) private { prices[batchCount] = _price; supplies[batchCount] = _supply; batchCount++; } function _generateRandomDna(uint256 _batch) private returns(uint256 dna) { uint256 rand = random256() % (10 ** 76); // set batch digits rand = rand / 100000000 * 100000000 + _batch; return rand; } function _isOwnerOf(address _address, uint256 _tokenId) private view returns (bool) { return artworkIdToOwner[_tokenId] == _address; } function _approveTransfer(uint256 _tokenId, address _address) internal { artworkIdToTransferApproved[_tokenId] = _address; } function _transfer(address _from, address _to, uint256 _tokenId) internal { artworkIdToOwner[_tokenId] = _to; ownerToTokenCount[_to]++; ownerToTokenCount[_from]--; delete artworkIdToTransferApproved[_tokenId]; Transfer(_from, _to, _tokenId); } function _approvedForTransfer(address _address, uint256 _tokenId) internal view returns (bool) { return artworkIdToTransferApproved[_tokenId] == _address; } function _transferFrom(address _from, address _to, uint256 _tokenId) internal { require(_isOwnerOf(_from, _tokenId)); require(_approvedForTransfer(msg.sender, _tokenId)); // prevent accidental transfer require(_to != address(0)); require(_to != address(this)); // perform the transfer and emit Transfer event _transfer(_from, _to, _tokenId); } function _canTransferBatch(uint256 _tokenId) internal view returns(bool) { uint256 batch = dnas[_tokenId] % 10; return !isTransferDisabled[batch]; } function _tokenMetadata(uint256 _tokenId, string _preferredTransport) internal view returns (string infoUrl) { _preferredTransport; // we don't use this parameter require(_tokenId < totalSupply()); strings.slice memory tokenIdSlice = _uintToBytes(_tokenId).toSliceB32(); return "/http/etherwaifu.com/presale/artwork/".toSlice().concat(tokenIdSlice); } // Author: pipermerriam // MIT license // https://github.com/pipermerriam/ethereum-string-utils function _uintToBytes(uint256 v) internal pure returns(bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint256(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } // Required methods of ERC721 function totalSupply() public view returns (uint256) { return dnas.length; } function balanceOf(address _owner) public view returns (uint256) { return ownerToTokenCount[_owner]; } function ownerOf(uint256 _tokenId) external view returns (address) { address theOwner = artworkIdToOwner[_tokenId]; require(theOwner != address(0)); return theOwner; } function approve(address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); require(_isOwnerOf(msg.sender, _tokenId)); // MUST throw if _tokenID does not represent an NFT // but if it is not NFT, owner is address(0) // which means it is impossible because msg.sender is a nonzero address require(msg.sender != _to); address prevApprovedAddress = artworkIdToTransferApproved[_tokenId]; _approveTransfer(_tokenId, _to); // Don't send Approval event if it is just // reaffirming that there is no one approved if(!(prevApprovedAddress == address(0) && _to == address(0))) { Approval(msg.sender, _to, _tokenId); } } function transfer(address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); require(_isOwnerOf(msg.sender, _tokenId)); // prevent accidental transfers require(_to != address(0)); require(_to != address(this)); require(_to != address(presaleMarket)); // perform the transfer and emit Transfer event _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); _transferFrom(_from, _to, _tokenId); } function takeOwnership(uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); address owner = artworkIdToOwner[_tokenId]; _transferFrom(owner, msg.sender, _tokenId); } // Optional methods of ERC721 function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds) { uint256 count = balanceOf(_owner); uint256[] memory res = new uint256[](count); uint256 allArtworkCount = totalSupply(); uint256 i = 0; for(uint256 artworkId = 1; artworkId <= allArtworkCount && i < count; artworkId++) { if(artworkIdToOwner[artworkId] == _owner) { res[i++] = artworkId; } } return res; } function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { return _tokenMetadata(_tokenId, _preferredTransport); } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId) { require(_index < balanceOf(_owner)); // not strictly needed because if the state is consistent then // a match will be found uint256 allArtworkCount = totalSupply(); uint256 i = 0; for(uint256 artworkId = 0; artworkId < allArtworkCount; artworkId++) { if(artworkIdToOwner[artworkId] == _owner) { if(i == _index) { return artworkId; } else { i++; } } } assert(false); // should never reach here } function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl) { return _tokenMetadata(_tokenId, "http"); } // ERC-165 Standard interface detection (required) function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return _interfaceID == ERC165Signature_ERC165 || _interfaceID == ERC165Signature_ERC721A || _interfaceID == ERC165Signature_ERC721B; } }
Will check to see if the seller owns the asset at the contract
function createAuction(uint256 _artworkId, uint256 _price, address _originalOwner) external whenNotPaused { require(msg.sender == address(artworkContract)); _takeOwnership(_originalOwner, _artworkId); Auction memory auction; auction.seller = _originalOwner; auction.price = _price; _createAuction(_artworkId, auction); }
13,112,651
// SPDX-License-Identifier: Apache 2.0 /* Original work Copyright 2019 ZeroEx Intl. Modified work Copyright 2020 Rigo Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./libs/LibSafeDowncast.sol"; import "./immutable/MixinStorage.sol"; import "./immutable/MixinConstants.sol"; import "./interfaces/IStorageInit.sol"; import "./interfaces/IStakingProxy.sol"; /// #dev The RigoBlock Staking contract. contract StakingProxy is IStakingProxy, MixinStorage, MixinConstants { using LibSafeDowncast for uint256; /// @dev Constructor. /// @param _stakingContract Staking contract to delegate calls to. constructor(address _stakingContract) MixinStorage() { // Deployer address must be authorized in order to call `init` _addAuthorizedAddress(msg.sender); // Attach the staking contract and initialize state _attachStakingContract(_stakingContract); // Remove the sender as an authorized address _removeAuthorizedAddressAtIndex(msg.sender, 0); } /// @dev Delegates calls to the staking contract, if it is set. fallback() external { // Sanity check that we have a staking contract to call address stakingContract_ = stakingContract; if (stakingContract_ == NIL_ADDRESS) { LibRichErrors.rrevert( LibStakingRichErrors.ProxyDestinationCannotBeNilError() ); } // Call the staking contract with the provided calldata. (bool success, bytes memory returnData) = stakingContract_.delegatecall(msg.data); // Revert on failure or return on success. assembly { switch success case 0 { revert(add(0x20, returnData), mload(returnData)) } default { return(add(0x20, returnData), mload(returnData)) } } } /// @dev Attach a staking contract; future calls will be delegated to the staking contract. /// Note that this is callable only by an authorized address. /// @param _stakingContract Address of staking contract. function attachStakingContract(address _stakingContract) external override onlyAuthorized { _attachStakingContract(_stakingContract); } /// @dev Detach the current staking contract. /// Note that this is callable only by an authorized address. function detachStakingContract() external override onlyAuthorized { stakingContract = NIL_ADDRESS; emit StakingContractDetachedFromProxy(); } /// @dev Batch executes a series of calls to the staking contract. /// @param data An array of data that encodes a sequence of functions to /// call in the staking contracts. function batchExecute(bytes[] calldata data) external returns (bytes[] memory batchReturnData) { // Initialize commonly used variables. bool success; bytes memory returnData; uint256 dataLength = data.length; batchReturnData = new bytes[](dataLength); address staking = stakingContract; // Ensure that a staking contract has been attached to the proxy. if (staking == NIL_ADDRESS) { LibRichErrors.rrevert( LibStakingRichErrors.ProxyDestinationCannotBeNilError() ); } // Execute all of the calls encoded in the provided calldata. for (uint256 i = 0; i != dataLength; i++) { // Call the staking contract with the provided calldata. (success, returnData) = staking.delegatecall(data[i]); // Revert on failure. if (!success) { assembly { revert(add(0x20, returnData), mload(returnData)) } } // Add the returndata to the batch returndata. batchReturnData[i] = returnData; } return batchReturnData; } /// @dev Asserts that an epoch is between 5 and 90 days long. // Asserts that 0 < cobb douglas alpha value <= 1. // Asserts that a stake weight is <= 100%. // Asserts that pools allow >= 1 maker. // Asserts that all addresses are initialized. function assertValidStorageParams() public view override { // Epoch length must be between 5 and 90 days long uint256 _epochDurationInSeconds = epochDurationInSeconds; if (_epochDurationInSeconds < 5 days || _epochDurationInSeconds > 90 days) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidEpochDuration )); } // Alpha must be 0 < x <= 1 uint32 _cobbDouglasAlphaDenominator = cobbDouglasAlphaDenominator; if (cobbDouglasAlphaNumerator > _cobbDouglasAlphaDenominator || _cobbDouglasAlphaDenominator == 0) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha )); } // Weight of delegated stake must be <= 100% if (rewardDelegatedStakeWeight > PPM_DENOMINATOR) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight )); } // Minimum stake must be > 1 if (minimumPoolStake < 2) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake )); } } /// @dev Attach a staking contract; future calls will be delegated to the staking contract. /// @param _stakingContract Address of staking contract. function _attachStakingContract(address _stakingContract) internal { // Attach the staking contract stakingContract = _stakingContract; emit StakingContractAttachedToProxy(_stakingContract); // Call `init()` on the staking contract to initialize storage. (bool didInitSucceed, bytes memory initReturnData) = stakingContract.delegatecall( abi.encodeWithSelector(IStorageInit(0).init.selector) ); if (!didInitSucceed) { assembly { revert(add(initReturnData, 0x20), mload(initReturnData)) } } // Assert initialized storage values are valid assertValidStorageParams(); } }
Asserts that an epoch is between 5 and 90 days long. Asserts that 0 < cobb douglas alpha value <= 1. Asserts that a stake weight is <= 100%. Asserts that pools allow >= 1 maker. Asserts that all addresses are initialized. Epoch length must be between 5 and 90 days long Weight of delegated stake must be <= 100% Minimum stake must be > 1
function assertValidStorageParams() public view override { uint256 _epochDurationInSeconds = epochDurationInSeconds; if (_epochDurationInSeconds < 5 days || _epochDurationInSeconds > 90 days) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidEpochDuration )); } if (cobbDouglasAlphaNumerator > _cobbDouglasAlphaDenominator || _cobbDouglasAlphaDenominator == 0) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha )); } if (rewardDelegatedStakeWeight > PPM_DENOMINATOR) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight )); } if (minimumPoolStake < 2) { LibRichErrors.rrevert( LibStakingRichErrors.InvalidParamValueError( LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake )); } }
1,820,462
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import "./interfaces/IWETH.sol"; import "./interfaces/IMirinPool.sol"; import "./interfaces/IMirinCurve.sol"; import "./libraries/MirinLibrary.sol"; import "./libraries/SafeERC20.sol"; contract MirinRouter { using SafeERC20 for IERC20; address public immutable factory; address public immutable legacyFactory; address public immutable weth; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "MIRIN: EXPIRED"); _; } constructor( address _factory, address _legacyFactory, address _weth ) { factory = _factory; legacyFactory = _legacyFactory; weth = _weth; } receive() external payable { assert(msg.sender == weth); // only accept ETH via fallback from the weth contract } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { return _swapExactTokensForTokens(amountIn, amountOutMin, path, pids, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { amounts = MirinLibrary.getAmountsIn(factory, legacyFactory, amountOut, path, pids); require(amounts[0] <= amountInMax, "MIRIN: EXCESSIVE_INPUT_AMOUNT"); IERC20(path[0]).safeTransferFrom( msg.sender, MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0] ); _swap(amounts, path, pids, to); } function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external payable ensure(deadline) returns (uint256[] memory amounts) { return _swapExactETHForTokens(amountOutMin, path, pids, to); } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == weth, "MIRIN: INVALID_PATH"); amounts = MirinLibrary.getAmountsIn(factory, legacyFactory, amountOut, path, pids); require(amounts[0] <= amountInMax, "MIRIN: EXCESSIVE_INPUT_AMOUNT"); IERC20(path[0]).safeTransferFrom( msg.sender, MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0] ); _swap(amounts, path, pids, address(this)); IWETH(weth).withdraw(amounts[amounts.length - 1]); MirinLibrary.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { return _swapExactTokensForETH(amountIn, amountOutMin, path, pids, to); } function swapETHForExactTokens( uint256 amountOut, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == weth, "MIRIN: INVALID_PATH"); amounts = MirinLibrary.getAmountsIn(factory, legacyFactory, amountOut, path, pids); require(amounts[0] <= msg.value, "MIRIN: EXCESSIVE_INPUT_AMOUNT"); IWETH(weth).deposit{value: amounts[0]}(); assert( IWETH(weth).transfer(MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0]) ); _swap(amounts, path, pids, to); // refund dust eth, if any if (msg.value > amounts[0]) MirinLibrary.safeTransferETH(msg.sender, msg.value - amounts[0]); } function _swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to ) internal returns (uint256[] memory amounts) { amounts = MirinLibrary.getAmountsOut(factory, legacyFactory, amountIn, path, pids); require(amounts[amounts.length - 1] >= amountOutMin, "MIRIN: INSUFFICIENT_OUTPUT_AMOUNT"); IERC20(path[0]).safeTransferFrom( msg.sender, MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0] ); _swap(amounts, path, pids, to); } function _swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to ) internal returns (uint256[] memory amounts) { require(path[0] == weth, "MIRIN: INVALID_PATH"); amounts = MirinLibrary.getAmountsOut(factory, legacyFactory, msg.value, path, pids); require(amounts[amounts.length - 1] >= amountOutMin, "MIRIN: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(weth).deposit{value: amounts[0]}(); assert( IWETH(weth).transfer(MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0]) ); _swap(amounts, path, pids, to); } function _swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256[] calldata pids, address to ) internal returns (uint256[] memory amounts) { require(path[path.length - 1] == weth, "MIRIN: INVALID_PATH"); amounts = MirinLibrary.getAmountsOut(factory, legacyFactory, amountIn, path, pids); require(amounts[amounts.length - 1] >= amountOutMin, "MIRIN: INSUFFICIENT_OUTPUT_AMOUNT"); IERC20(path[0]).safeTransferFrom( msg.sender, MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0] ); _swap(amounts, path, pids, address(this)); IWETH(weth).withdraw(amounts[amounts.length - 1]); MirinLibrary.safeTransferETH(to, amounts[amounts.length - 1]); } function _swap( uint256[] memory amounts, address[] memory path, uint256[] memory pids, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = MirinLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? MirinLibrary.getPool(factory, legacyFactory, output, path[i + 2], pids[i + 1]) : _to; IMirinPool(MirinLibrary.getPool(factory, legacyFactory, input, output, pids[i])).swap( amount0Out, amount1Out, to, bytes("") ); } } }
refund dust eth, if any
function swapETHForExactTokens( uint256 amountOut, address[] calldata path, uint256[] calldata pids, address to, uint256 deadline ) external payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == weth, "MIRIN: INVALID_PATH"); amounts = MirinLibrary.getAmountsIn(factory, legacyFactory, amountOut, path, pids); require(amounts[0] <= msg.value, "MIRIN: EXCESSIVE_INPUT_AMOUNT"); assert( IWETH(weth).transfer(MirinLibrary.getPool(factory, legacyFactory, path[0], path[1], pids[0]), amounts[0]) ); _swap(amounts, path, pids, to); if (msg.value > amounts[0]) MirinLibrary.safeTransferETH(msg.sender, msg.value - amounts[0]); }
12,718,181
./full_match/1/0xB248c975DaeAc47c4960EcBD10a79E486eBD1cA8/sources/contracts/token/OUSDResolutionUpgrade.sol
Handle special for non-rebasing accounts
function upgradeAccounts(address[] calldata accounts) external { for (uint256 i = 0; i < accounts.length; i++) { address account = accounts[i]; require(account != address(0), "Reserved"); require(isUpgraded[account] == 0, "Account already upgraded"); isUpgraded[account] = 1; uint256 nrc = nonRebasingCreditsPerToken[account]; if (nrc > 0) { require(nrc < 1e18, "Account already highres"); nonRebasingCreditsPerToken[account] = nrc * RESOLUTION_INCREASE; } require(balance > 0, "Will not upgrade zero balance"); _creditBalances[account] = balance * RESOLUTION_INCREASE; } }
9,761,441
pragma solidity ^0.4.16; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /******************************************/ /* ITECToken STARTS HERE */ /******************************************/ contract ITECToken { // Public variables of the token(TokenERC20) string public name; string public symbol; uint256 public totalSupply; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it address public owner; using SafeMath for uint; // use the library for uint type /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes owner = msg.sender; } // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event FrozenFunds(address target, bool frozen); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); //authorized parts start modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } //authorized parts end /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) onlyOwner public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; }
11,682,777
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./ERC1155.sol"; import "./SafeMath.sol"; import "./Counters.sol"; import "./AbstractNFTAccess.sol"; contract NFTAccess is AbstractNFTAccess { using SafeMath for uint256; using Counters for Counters.Counter; uint public tier1 = 0; uint public tier2 = 1; uint public tier3 = 2; bool public canSingleMint = false; address public NFT_Access_Address = 0x95F71D6424F2B9bfc29378Ea9539372c986F2E9b; Counters.Counter private ticketCount; mapping(uint256 => ticketStruct) public tickets; struct ticketStruct { uint256 mintPrice; uint supply; uint currentSupply; uint claimLimit; string hash; bool canClaim; mapping(address => uint256) amountClaimed; } constructor(string memory _name, string memory _symbol) ERC1155("ipfs://") { name_ = _name; symbol_ = _symbol; } /* * @notice Add item to collection * * @param _mintPrice the price per ticket * @param _supply the max supply of this item * @param _claimLimit the max amount of nfts each user can claim for this item * @param _hash the hash of the image * @param _canClaim if it can currently be claimed */ function addTicketStruct (uint256 _mintPrice, uint _supply, uint _claimLimit, string memory _hash, bool _canClaim) external onlyOwner { ticketStruct storage ticket = tickets[ticketCount.current()]; ticket.mintPrice = _mintPrice; ticket.supply = _supply; ticket.currentSupply = 0; ticket.claimLimit = _claimLimit; ticket.hash = _hash; ticket.canClaim = _canClaim; ticketCount.increment(); } /* * @notice Edit item in collection * * @param _mintPrice the price per ticket * @param _ticket the ticket to edit * @param _supply the max supply of this item * @param _claimLimit the max amount of nfts each user can claim for this item * @param _hash the hash of the image * @param _canClaim if it can currently be claimed */ function editTicketStruct (uint256 _mintPrice, uint _ticket, uint _supply, uint _claimLimit, string memory _hash, bool _canClaim) external onlyOwner { tickets[_ticket].mintPrice = _mintPrice; tickets[_ticket].hash = _hash; tickets[_ticket].supply = _supply; tickets[_ticket].claimLimit = _claimLimit; tickets[_ticket].canClaim = _canClaim; } /* * @notice mint item in collection * * @param quantity the quantity to mint */ function tieredMint (uint256 quantity) external payable { uint tier; uint currentSupply; uint tier1CurrentSupply = tickets[tier1].currentSupply; uint tier2CurrentSupply = tickets[tier2].currentSupply; uint tier3CurrentSupply = tickets[tier3].currentSupply; if (tier1CurrentSupply + quantity <= tickets[tier1].supply) { tier = tier1; currentSupply = tier1CurrentSupply; } else if (tier2CurrentSupply + quantity <= tickets[tier2].supply) { tier = tier2; currentSupply = tier2CurrentSupply; } else if (tier3CurrentSupply + quantity <= tickets[tier3].supply) { tier = tier3; currentSupply = tier3CurrentSupply; } else { require(false, "No tickets left from any tier"); } require(currentSupply + quantity <= tickets[tier].supply, "Not enough tickets able to be claimed" ); if (msg.sender != NFT_Access_Address) { require(tickets[tier].canClaim, "Not currently allowed to be claimed" ); require(quantity <= tickets[tier].claimLimit, "Attempting to claim too many tickets"); require(quantity.mul(tickets[tier].mintPrice) <= msg.value, "Not enough eth sent"); require(tickets[tier].amountClaimed[msg.sender] < tickets[tier].claimLimit , "Claimed max amount"); tickets[tier].amountClaimed[msg.sender] += 1; } tickets[tier].currentSupply = tickets[tier].currentSupply + quantity; _mint(msg.sender, tier, quantity, ""); } /* * @notice mint item in collection * * @param quantity the quantity to mint * @param _ticket the ticket to mint */ function singleMint (uint256 quantity, uint256 _ticket) external payable { if (msg.sender != NFT_Access_Address) { require(canSingleMint, "Must tier mint"); require(tickets[_ticket].canClaim, "Not currently allowed to be claimed" ); require(quantity <= tickets[_ticket].claimLimit, "Attempting to claim too many tickets"); require(quantity.mul(tickets[_ticket].mintPrice) <= msg.value, "Not enough eth sent"); require(tickets[_ticket].amountClaimed[msg.sender] < tickets[_ticket].claimLimit , "Claimed max amount"); tickets[_ticket].amountClaimed[msg.sender] += 1; } uint currentSupply = tickets[_ticket].currentSupply; require(currentSupply + quantity <= tickets[_ticket].supply, "Not enough tickets able to be claimed" ); tickets[_ticket].supply = tickets[_ticket].supply + quantity; _mint(msg.sender, _ticket, quantity, ""); } /* * @notice withdraw any money from the contract */ function withdraw() external { require(address(this).balance > 0, "Contract currently has no ether"); uint256 walletBalance = address(this).balance; (bool status,) = NFT_Access_Address.call{value: walletBalance}(""); require(status, "Failed withdraw"); } /* * @notice change the tiers for tierTickets * * @param _tier1 the quantity to mint * @param _tier2 the quantity to mint * @param _tier3 the quantity to mint */ function changeTierTickets(uint _tier1, uint _tier2, uint _tier3) external onlyOwner { tier1 = _tier1; tier2 = _tier2; tier3 = _tier3; } /* * @notice get the total quantities of current tiers */ function totalTierQuantity() public view returns (uint) { uint quantity1 = tickets[tier1].supply; uint quantity2 = tickets[tier2].supply; uint quantity3 = tickets[tier3].supply; return (quantity1 + quantity2 + quantity3); } /* * @notice get the current quantities of current tiers */ function currentTierQuantity() public view returns (uint) { uint quantity1 = tickets[tier1].currentSupply; uint quantity2 = tickets[tier2].currentSupply; uint quantity3 = tickets[tier3].currentSupply; return (quantity1 + quantity2 + quantity3); } function uri(uint256 _id) public view override returns (string memory) { require(tickets[_id].supply > 0, "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), tickets[_id].hash)); } }
Add item to collection _mintPrice the price per ticket _supply the max supply of this item _claimLimit the max amount of nfts each user can claim for this item _hash the hash of the image _canClaim if it can currently be claimed/
function addTicketStruct (uint256 _mintPrice, uint _supply, uint _claimLimit, string memory _hash, bool _canClaim) external onlyOwner { ticketStruct storage ticket = tickets[ticketCount.current()]; ticket.mintPrice = _mintPrice; ticket.supply = _supply; ticket.currentSupply = 0; ticket.claimLimit = _claimLimit; ticket.hash = _hash; ticket.canClaim = _canClaim; ticketCount.increment(); }
11,873,612
// SPDX-License-Identifier: MIT pragma solidity ^0.7.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. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view 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 override virtual returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.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 msg.sender == _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; } } interface TownInterface { function checkProposal(address proposal) external returns (bool); function voteOn(address externalToken, uint256 amount) external returns (bool); } contract TownToken is ERC20, Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; bool public initiated; address[] private _holders; TownInterface _town; event Init(string name, string indexed symbol, uint256 decimals, uint256 totalSupply, address indexed townContract); constructor (string memory _name, string memory _symbol) { initiated = false; name = _name; symbol = _symbol; } function getHoldersCount() external view returns (uint256) { return _holders.length; } function getHolderByIndex(uint256 index) external view returns (address) { return _holders[index]; } function init( uint256 totalSupply, address townContract) public onlyOwner { require(initiated == false, "contract already initiated"); _town = TownInterface(townContract); _mint(townContract, totalSupply); initiated = true; emit Init(name,symbol,decimals,totalSupply,townContract); } function transfer(address recipient, uint256 amount) public override returns (bool) { if (msg.sender != address(_town)) { if (_town.checkProposal(recipient) == true) { super.transfer(address(_town), amount); return _town.voteOn(recipient, amount); } // check 223 ERC and call voteOn function } if (recipient != address(_town)) { bool found = false; for (uint i = 0; i < _holders.length; ++i) { // find recipient address in holders list if (_holders[i] == recipient) { found = true; break; } } if (found == false) { // if recipient not found, we push new address _holders.push(recipient); } } if (balanceOf(address(msg.sender)) == amount && msg.sender != address(_town)) { // remove address with 0 balance from holders uint i = 0; for (; i < _holders.length; ++i) { if (_holders[i] == address(msg.sender)) { break; } } if (i < (_holders.length - 1)) { _holders[i] = _holders[_holders.length - 1]; //delete _holders[_holders.length - 1]; _holders.pop(); } } return super.transfer(recipient, amount); } }
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 override virtual returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
2,439,093
pragma solidity ^0.4.24; contract Publisher { struct Publication { address document; address by; address to; uint when; } Publication[] publications; mapping(address => uint[]) publishedToPublications; mapping(address => uint[]) documentToPublications; event PublicationsCreated(uint[] publications); function getPublication(uint index) public view returns (address document, address by, address to, uint when) { Publication storage publication = publications[index]; return (publication.document, publication.by, publication.to, publication.when); } function getPublicationsTo(address _to) public view returns (uint[]) { return publishedToPublications[_to]; } function isDocumentPublishedBy(address _document, address _by) public view returns (bool) { //take the optimum lookup path uint[] storage publicationsByDocument = documentToPublications[_document]; for (uint i = 0; i < publicationsByDocument.length; i++) { if (publications[publicationsByDocument[i]].by == _by) return true; } return false; } function isDocumentPublishedTo(address _document, address _to) public view returns (bool) { //take the optimum lookup path uint[] storage publicationsByPublished = publishedToPublications[_to]; uint[] storage publicationsByDocument = documentToPublications[_document]; if (publicationsByPublished.length > publicationsByDocument.length ) { for (uint i = 0; i < publicationsByDocument.length; i++) { if (publications[publicationsByDocument[i]].to == _to) return true; } }else { for (uint j = 0; j < publicationsByPublished.length; j++) { if ( publications[publicationsByPublished[j]].document == _document) return true; } } return false; } function isDocumentPublished(address _document) public view returns (bool) { return documentToPublications[_document].length > 0; } function isPublished(address _document, address _by, address _to) public view returns (bool) { //take the optimum lookup path uint[] storage publicationsByPublished = publishedToPublications[_to]; uint[] storage publicationsByDocument = documentToPublications[_document]; if (publicationsByPublished.length > publicationsByDocument.length ) { for (uint i = 0; i < publicationsByDocument.length; i++) { if ( publications[publicationsByDocument[i]].by == _by && publications[publicationsByDocument[i]].to == _to) return true; } }else { for (uint j = 0; j < publicationsByPublished.length; j++) { if ( publications[publicationsByPublished[j]].by == _by && publications[publicationsByPublished[j]].document == _document) return true; } } return false; } function publish(address _document, address _by, address[] _to) public returns (uint[]){ uint[] memory created = new uint[](_to.length); for (uint i = 0; i < _to.length; i++) { address to = _to[i]; if (isPublished(_document, _by, to) == false){ publications.push(Publication(_document, _by, to, now)); uint index = publications.length-1; documentToPublications[_document].push(index); publishedToPublications[to].push(index); created[i] = index; } } emit PublicationsCreated(created); return created; } }
take the optimum lookup path
function isDocumentPublishedTo(address _document, address _to) public view returns (bool) { uint[] storage publicationsByPublished = publishedToPublications[_to]; uint[] storage publicationsByDocument = documentToPublications[_document]; if (publicationsByPublished.length > publicationsByDocument.length ) { for (uint i = 0; i < publicationsByDocument.length; i++) { if (publications[publicationsByDocument[i]].to == _to) return true; } for (uint j = 0; j < publicationsByPublished.length; j++) { if ( publications[publicationsByPublished[j]].document == _document) return true; } } return false; }
2,545,429
./full_match/11155111/0x7c045ecB589D4fF5c06B712C2d6BB1e855f4a719/sources/contracts/NFT.sol
get total stake count
function getTotalStaked() external view onlyRole(DEV_ROLE) returns (uint256 _total) { uint256 total; for (uint256 i; i < totalSupply(); i++) { if (tokenStakeStatus[i] > 0) { total++; } } return total; }
3,800,192
./partial_match/97/0xEB77528ABdfBEa2860B0A3b5da39e50Ab2c5a6D6/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accOctanPerShare: 0 })); updateStakingPool(); }
17,209,677
./partial_match/42/0xD72cb19D7AB0Bfb3793358242aF508fC67722178/sources/ETHTornado.sol
this function is defined in a child contract / whether a note is already spent /
function _processWithdraw(address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) internal; function isSpent(bytes32 _nullifierHash) public view returns(bool) { return nullifierHashes[_nullifierHash]; }
3,454,840
pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; /* Eidoo ICO Engine interface This interface enables Eidoo wallet to query our ICO and display all the informations needed in the app */ contract ICOEngineInterface { function started() public view returns (bool); function ended() public view returns (bool); function startTime() public view returns (uint); function endTime() public view returns (uint); function startBlock() public view returns (uint); function endBlock() public view returns (uint); function totalTokens() public view returns (uint); function remainingTokens() public view returns (uint); function price() public view returns (uint); } // UbiatarCoin Abstract Contract contract UACAC { function lockTransfer(bool _lock) public; function issueTokens(address _who, uint _tokens) public; function balanceOf(address _owner) public constant returns (uint256); } // PreSaleVesting Abstract Contract contract PreSaleVestingAC { function finishIco() public; } // Founders Vesting Abstract Contract contract FoundersVestingAC { function finishIco() public; } // UbiatarPlay Abstract Contract contract UbiatarPlayAC { function finishIco() public; } /* ICO crowdsale main contract It is in charge to issue all the token for the ICO, preSales, advisors and founders vesting */ contract ICO is Ownable, ICOEngineInterface { // SafeMath standard lib using SafeMath for uint; // total Wei collected during the ICO uint collectedWei = 0; // Standard token price in USD CENTS per token uint public usdTokenPrice = 2 * 100; // The USD/ETH // UPDATE CHANGE RATE WITH CURRENT RATE WHEN DEPLOYING // This value is given in USD CENTS uint public usdPerEth = 1100 * 100; // Founders reward uint public constant FOUNDERS_REWARD = 12000000 * 1 ether; // Total Tokens bought in PreSale uint public constant PRESALE_REWARD = 17584778551358900100698693; // 15 000 000 tokens on sale during the ICO uint public constant ICO_TOKEN_SUPPLY_LIMIT = 15000000 * 1 ether; // Tokens for advisors uint public constant ADVISORS_TOKENS = 4915221448641099899301307; // 50 500 000 tokens for Ubiatar Play uint public constant UBIATARPLAY_TOKENS = 50500000 * 1 ether; // 7 500 000 tokens for Reservation contract campaign uint public constant RC_TOKEN_LIMIT = 7500000 * 1 ether; /// Fields: // ICO starting block number uint public icoBlockNumberStart = 5305785; // ICO finish time in epoch time uint public icoFinishTime = 1524488400; // ICO partecipant to be refund in case of overflow on the last token purchase address public toBeRefund = 0x0; // ICO refund amount in case of overflow on the last token purchase uint public refundAmount; // Reservation contract participant to be refund in case of overflow on the last token purchase address public toBeRefundRC = 0x0; // Reservation contract participant to be refund in case of overflow on the last token purchase uint public refundAmountRC = 0; // Total amount of tokens sold during ICO uint public icoTokensSold = 0; // Total amount of tokens sent to UACUnsold contract after ICO is finished uint public icoTokensUnsold = 0; // This is where FOUNDERS_REWARD will be allocated address public foundersVestingAddress = 0x0; // This is where PRESALE_REWARD will be allocated address public preSaleVestingAddress = 0x0; // This is where UBIATARPLAY_TOKENS will be allocated address public ubiatarPlayAddress = 0x0; // UbiatarCoin ERC20 address address public uacTokenAddress = 0x0; // Unsold token contract address address public unsoldContractAddress = 0x0; // This is where ADVISORS_TOKEN will be allocated address public advisorsWalletAddress = 0x0; // This is where Ethers will be transfered address public ubiatarColdWallet = 0x0; // Reservation contract address address public RCContractAddress = 0x0; // UbiatarCoin contract reference UACAC public uacToken; // PreSaleVesting contract reference PreSaleVestingAC public preSaleVesting; // FoundersVesting contract reference FoundersVestingAC public foundersVesting; // UbiatarPlay contract reference UbiatarPlayAC public ubiatarPlay; // ICO possibles state. enum State { Init, ICORunning, ICOFinished } // ICO current state, initialized with Init state State public currentState = State.Init; /// Modifiers // Only in a given ICO state modifier onlyInState(State state) { require(state == currentState); _; } // Only before ICO crowdsale starting block number modifier onlyBeforeBlockNumber() { require(block.number < icoBlockNumberStart); _; } // Only after ICO crowdsale starting block number modifier onlyAfterBlockNumber() { require(block.number >= icoBlockNumberStart); _; } // Only before ICO crowdsale finishing epoch time modifier onlyBeforeIcoFinishTime() { require(uint(now) <= icoFinishTime); _; } // Only if ICO can finish (so after finishing epoch time, or when all tokens are sold) modifier canFinishICO() { require((uint(now) >= icoFinishTime) || (icoTokensSold == ICO_TOKEN_SUPPLY_LIMIT)); _; } // Can only be called from the reservation contract modifier onlyFromRC() { require(msg.sender == RCContractAddress); _; } /// Events event LogStateSwitch(State newState); event LogBuy(address owner, uint value); event LogBurn(address owner, uint value); event LogWithdraw(address to, uint value); event LogOverflow(address to, uint value); event LogRefund(address to, uint value); event LogUbiatarColdWalletSet(address ubiatarColdWallet); event LogAdvisorsWalletAddressSet(address advisorsWalletAddress); event LogUbiatarPlayAddressSet(address ubiatarPlayAddress); event LogUacTokenAddressSet(address uacTokenAddress); event LogUnsoldContractAddressSet(address unsoldContractAddress); event LogFoundersVestingAddressSet(address foundersVestingAddress); event LogPreSaleVestingAddressSet(address preSaleVestingAddress); event LogBlockNumberStartSet(uint icoBlockNumberStart); event LogIcoFinishTimeSet(uint icoFinishTime); event LogUsdPerEthRateSet(uint usdPerEth); event LogUsdTokenPrice(uint usdTokenPrice); event LogStartICO(); event LogFinishICO(); /// Functions: // ICO constructor. It takes main contracts adresses function ICO ( address _uacTokenAddress, address _unsoldContractAddress, address _foundersVestingAddress, address _preSaleVestingAddress, address _ubiatarPlayAddress, address _advisorsWalletAddress ) public { uacToken = UACAC(_uacTokenAddress); preSaleVesting = PreSaleVestingAC(_preSaleVestingAddress); foundersVesting = FoundersVestingAC(_foundersVestingAddress); ubiatarPlay = UbiatarPlayAC(_ubiatarPlayAddress); uacTokenAddress = _uacTokenAddress; unsoldContractAddress = _unsoldContractAddress; foundersVestingAddress = _foundersVestingAddress; preSaleVestingAddress = _preSaleVestingAddress; ubiatarPlayAddress = _ubiatarPlayAddress; advisorsWalletAddress = _advisorsWalletAddress; } // It will put ICO in Running state, it should be launched before starting block function startICO() public onlyOwner onlyInState(State.Init) { setState(State.ICORunning); uacToken.issueTokens(foundersVestingAddress, FOUNDERS_REWARD); uacToken.issueTokens(preSaleVestingAddress, PRESALE_REWARD); uacToken.issueTokens(advisorsWalletAddress, ADVISORS_TOKENS); uacToken.issueTokens(ubiatarPlayAddress, UBIATARPLAY_TOKENS); LogStartICO(); } // It allows to withdraw crowdsale Ether only when ICO is finished function withdraw(uint withdrawAmount) public onlyOwner onlyInState(State.ICOFinished) { // Checks if the UbiatarColdWallet address has been set require(ubiatarColdWallet != 0x0); // If we're trying to withdraw more than the current contract's balance withdraws remaining ether if (withdrawAmount > this.balance) { withdrawAmount = this.balance; } ubiatarColdWallet.transfer(withdrawAmount); LogWithdraw(ubiatarColdWallet, withdrawAmount); } // It will set ICO in Finished state and it will call finish functions in side contracts function finishICO() public onlyOwner canFinishICO onlyInState(State.ICORunning) { setState(State.ICOFinished); // 1 - lock all transfers uacToken.lockTransfer(false); // 2 - move all unsold tokens to unsoldTokens contract icoTokensUnsold = ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold); if (icoTokensUnsold > 0) { uacToken.issueTokens(unsoldContractAddress, icoTokensUnsold); LogBurn(unsoldContractAddress, icoTokensUnsold); } // Calls finish function in other contracts and sets their starting times for the withdraw functions preSaleVesting.finishIco(); ubiatarPlay.finishIco(); foundersVesting.finishIco(); LogFinishICO(); } // It will refunds last address in case of overflow function refund() public onlyOwner { require(toBeRefund != 0x0); require(refundAmount > 0); uint _refundAmount = refundAmount; address _toBeRefund = toBeRefund; refundAmount = 0; toBeRefund = 0x0; _toBeRefund.transfer(_refundAmount); LogRefund(_toBeRefund, _refundAmount); } // This is the main function for Token purchase during ICO. It takes a buyer address where tokens should be issued function buyTokens(address _buyer) internal onlyInState(State.ICORunning) onlyBeforeIcoFinishTime onlyAfterBlockNumber { // Checks that the investor has sent at least 0.1 ETH require(msg.value >= 100 finney); uint bonusPercent = 0; // Gives 4% of discount for the first 42 hours of the ICO if (block.number < icoBlockNumberStart.add(10164)) { bonusPercent = 4; } // Gives 6% of discount for the first 24 hours of the ICO if (block.number < icoBlockNumberStart.add(2541)) { bonusPercent = 6; } // Gives 8% of discount for the first 3 hours of the ICO if (block.number < icoBlockNumberStart.add(635)) { bonusPercent = 8; } // Calculates the amount of tokens to be issued by multiplying the amount of ether sent by the number of tokens // per ETH. We multiply and divide by 1 ETH to avoid approximation errors uint newTokens = (msg.value.mul(getUacTokensPerEth(bonusPercent))).div(1 ether); // Checks if there are enough tokens left to be issued, if not if ((icoTokensSold.add(newTokens)) <= ICO_TOKEN_SUPPLY_LIMIT) { issueTokensInternal(_buyer, newTokens); collectedWei = collectedWei.add(msg.value); } // Refund function, calculates the amount of tokens still available and issues them to the investor, then calculates // the amount of etther to be sent back else { // Calculates the amount of token remaining in the ICO uint tokensBought = ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold); // Calculates the amount of ETH to be sent back to the buyer depending on the amount of tokens still available // at the moment of the purchase uint _refundAmount = msg.value.sub((tokensBought.div(getUacTokensPerEth(bonusPercent))).mul(1 ether)); // Checks if the refund amount is actually less than the ETH sent by the investor then saves the amount to // be refund and the address which will receive the refund require(_refundAmount < msg.value); refundAmount = _refundAmount; toBeRefund = _buyer; LogOverflow(_buyer, _refundAmount); issueTokensInternal(_buyer, tokensBought); collectedWei = collectedWei.add(msg.value).sub(_refundAmount); } } // Same as buyTokens, can only be called by the reservation contract and sets the bonus percent to 10% function buyTokensRC(address _buyer) public payable onlyFromRC { // Checks that the investor has sent at least 0.1 ETH require(msg.value >= 100 finney); uint bonusPercent = 10; // Calculates the amount of tokens to be issued by multiplying the amount of ether sent by the number of tokens // per ETH. We multiply and divide by 1 ETH to avoid approximation errors uint newTokens = (msg.value.mul(getUacTokensPerEth(bonusPercent))).div(1 ether); // Checks if the amount of tokens to be sold is lower than the amount of tokens available to the reservation contract if ((icoTokensSold.add(newTokens)) <= RC_TOKEN_LIMIT) { issueTokensInternal(_buyer, newTokens); collectedWei = collectedWei.add(msg.value); } // Refund function, calculates the amount of tokens still available and issues them to the investor, then calculates // the amount of etther to be sent back else { // Calculates the amount of token still available to the reservation contract uint tokensBought = RC_TOKEN_LIMIT.sub(icoTokensSold); // Calculates the amount of ETH to be sent back to the buyer depending on the amount of tokens still available // at the moment of the purchase uint _refundAmount = msg.value.sub((tokensBought.div(getUacTokensPerEth(bonusPercent))).mul(1 ether)); // Checks if the refund amount is actually less than the ETH sent by the investor then saves the amount to // be refund and the address which will receive the refund require(_refundAmount < msg.value); refundAmountRC = _refundAmount; toBeRefundRC = _buyer; issueTokensInternal(_buyer, tokensBought); LogOverflow(_buyer, _refundAmount); collectedWei = collectedWei.add(msg.value).sub(_refundAmount); } } // It is an internal function that will call UAC ERC20 contract to issue the tokens function issueTokensInternal(address _to, uint _tokens) internal { require((icoTokensSold.add(_tokens)) <= ICO_TOKEN_SUPPLY_LIMIT); uacToken.issueTokens(_to, _tokens); icoTokensSold = icoTokensSold.add(_tokens); LogBuy(_to, _tokens); } /// Setters function setUbiatarColdWallet(address _ubiatarColdWallet) public onlyOwner { ubiatarColdWallet = _ubiatarColdWallet; LogUbiatarColdWalletSet(ubiatarColdWallet); } function setAdvisorsWalletAddress(address _advisorsWalletAddress) public onlyOwner onlyInState(State.Init) { advisorsWalletAddress = _advisorsWalletAddress; LogAdvisorsWalletAddressSet(advisorsWalletAddress); } function setUbiatarPlayAddress(address _ubiatarPlayAddress) public onlyOwner onlyInState(State.Init) { ubiatarPlayAddress = _ubiatarPlayAddress; ubiatarPlay = UbiatarPlayAC(_ubiatarPlayAddress); LogUbiatarPlayAddressSet(ubiatarPlayAddress); } function setUacTokenAddress(address _uacTokenAddress) public onlyOwner onlyInState(State.Init) { uacTokenAddress = _uacTokenAddress; uacToken = UACAC(_uacTokenAddress); LogUacTokenAddressSet(uacTokenAddress); } function setUnsoldContractAddress(address _unsoldContractAddress) public onlyOwner onlyInState(State.Init) { unsoldContractAddress = _unsoldContractAddress; LogUnsoldContractAddressSet(unsoldContractAddress); } function setRcContractAddress(address _RCContractAddress) public onlyOwner { RCContractAddress = _RCContractAddress; } function setFoundersVestingAddress(address _foundersVestingAddress) public onlyOwner onlyInState(State.Init) { foundersVestingAddress = _foundersVestingAddress; foundersVesting = FoundersVestingAC(_foundersVestingAddress); LogFoundersVestingAddressSet(foundersVestingAddress); } function setPreSaleVestingAddress(address _preSaleVestingAddress) public onlyOwner onlyInState(State.Init) { preSaleVestingAddress = _preSaleVestingAddress; preSaleVesting = PreSaleVestingAC(_preSaleVestingAddress); LogPreSaleVestingAddressSet(preSaleVestingAddress); } // It will set ICO crowdsale starting block number function setBlockNumberStart(uint _blockNumber) public onlyOwner { icoBlockNumberStart = _blockNumber; LogBlockNumberStartSet(icoBlockNumberStart); } // It will set ICO finishing epoch time function setIcoFinishTime(uint _time) public onlyOwner { icoFinishTime = _time; LogIcoFinishTimeSet(icoFinishTime); } function setUsdPerEthRate(uint _usdPerEthRate) public onlyOwner { usdPerEth = _usdPerEthRate; LogUsdPerEthRateSet(usdPerEth); } // It will switch ICO State function setState(State _s) internal { currentState = _s; LogStateSwitch(_s); } function setUsdTokenPrice(uint tokenPrice) public onlyOwner { usdTokenPrice = tokenPrice; LogUsdTokenPrice(usdTokenPrice); } /// Getters function getBlockNumberStart() constant public returns (uint) { return icoBlockNumberStart; } function getTokensIcoSold() constant public returns (uint) { return icoTokensSold; } function getTotalIcoTokens() pure public returns (uint) { return ICO_TOKEN_SUPPLY_LIMIT; } function getUacTokenBalance(address _of) constant public returns (uint) { return uacToken.balanceOf(_of); } function getTotalCollectedWei() constant public returns (uint) { return collectedWei; } function isIcoRunning() constant public returns (bool) { return (currentState == State.ICORunning); } function isIcoFinished() constant public returns (bool) { return (currentState == State.ICOFinished || icoTokensSold >= ICO_TOKEN_SUPPLY_LIMIT); } // Calculates the token price including the bonus percent received from the buyTokens function // Returns the amount of UAC per 1 ETH to be given function getUacTokensPerEth(uint bonusPercent) constant internal returns (uint) { uint tokenPrice = (usdTokenPrice.mul(100).mul(1 ether)).div(bonusPercent.add(100)); uint uacPerEth = (usdPerEth.mul(1 ether).mul(1 ether)).div(tokenPrice); return uacPerEth; } /// ICOEngineInterface // false if the ico is not started, true if the ico is started and running, true if the ico is completed function started() public view returns (bool) { if ((currentState == State.ICORunning || currentState == State.ICOFinished) && block.number >= icoBlockNumberStart) { return true; } else { return false; } } // false if the ico is not started, false if the ico is started and running, true if the ico is completed function ended() public view returns (bool) { return ((uint(now) >= icoFinishTime) || (icoTokensSold == ICO_TOKEN_SUPPLY_LIMIT)); } // time stamp of the starting time of the ico, must return 0 if it depends on the block number function startTime() public view returns (uint) { return 0; } // time stamp of the ending time of the ico, must return 0 if it depends on the block number function endTime() public view returns (uint) { return icoFinishTime; } // Optional function, can be implemented in place of startTime // Returns the starting block number of the ico, must return 0 if it depends on the time stamp function startBlock() public view returns (uint) { return icoBlockNumberStart; } // Optional function, can be implemented in place of endTime // Returns theending block number of the ico, must retrun 0 if it depends on the time stamp function endBlock() public view returns (uint) { return 0; } // returns the total number of the tokens available for the sale, must not change when the ico is started function totalTokens() public view returns (uint) { return ICO_TOKEN_SUPPLY_LIMIT; } // returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(), // then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens() function remainingTokens() public view returns (uint) { return ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold); } // return the price as number of tokens released for each ether function price() public view returns (uint) { uint bonusPercent = 0; if (block.number < icoBlockNumberStart.add(10164)) { bonusPercent = 4; } if (block.number < icoBlockNumberStart.add(2541)) { bonusPercent = 6; } if (block.number < icoBlockNumberStart.add(635)) { bonusPercent = 8; } return getUacTokensPerEth(bonusPercent); } // It allows to buy tokens for an other address than msg.sender function buyTokensFor(address _to) payable public { // buyTokens -> issueTokensInternal buyTokens(_to); } // Default fallback function function() payable public { buyTokens(msg.sender); } }
Optional function, can be implemented in place of endTime Returns theending block number of the ico, must retrun 0 if it depends on the time stamp
function endBlock() public view returns (uint) { return 0; }
12,552,995
./full_match/4/0x6238b60F5503f0c8E577d5afC8aA760bB9615d87/sources/CryptOgres.sol
publicPRESALE MINTrequire(msg.value >= cost _mintAmount, "Ether value sent is not correct.");
function mintPresale(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(presaleWallets[msg.sender] == true, "You are not on the presale whitelist."); require(presaleStart <= block.timestamp && publicStart >= block.timestamp); require(_mintAmount > 0); require(_mintAmount <= maxPresaleMintAmount, "You can only mint 3 in presale."); require(supply + _mintAmount <= maxPresaleSupply, "Purchase would exceed max presale tokens."); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } }
12,505,714
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface ICurveGaugeMapping { struct GaugeData { address gaugeAddress; bool rewardToken; } function GAUGEMAPPING439(bytes32) external view returns(GaugeData memory); //inject NONSTANDARD NAMING } interface TokenInterface { function BALANCEOF742(address) external view returns (uint); //inject NONSTANDARD NAMING } interface IMintor { function MINTED437(address) external view returns (uint); //inject NONSTANDARD NAMING } interface IGauge { function INTEGRATE_FRACTION856(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function LP_TOKEN427() external view returns(address token); //inject NONSTANDARD NAMING function REWARDED_TOKEN28() external view returns(address token); //inject NONSTANDARD NAMING function CRV_TOKEN827() external view returns(address token); //inject NONSTANDARD NAMING function BALANCEOF742(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function REWARDS_FOR32(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function CLAIMED_REWARDS_FOR119(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING } contract GaugeHelper { function GETCURVEGAUGEMAPPINGADDR166() internal pure returns (address){ //inject NONSTANDARD NAMING return 0x1C800eF1bBfE3b458969226A96c56B92a069Cc92; } function GETCURVEMINTORADDR2() internal pure returns (address){ //inject NONSTANDARD NAMING return 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; } function STRINGTOBYTES32152(string memory str) internal pure returns (bytes32 result) { //inject NONSTANDARD NAMING require(bytes(str).length != 0, "string-empty"); // solium-disable-next-line security/no-inline-assembly assembly { result := mload(add(str, 32)) } } } contract Resolver is GaugeHelper { struct PositionData { uint stakedBal; uint crvEarned; uint crvClaimed; uint rewardsEarned; uint rewardsClaimed; uint crvBal; uint rewardBal; bool hasReward; } function GETPOSITION539(string memory gaugeName, address user) public view returns (PositionData memory positionData) { //inject NONSTANDARD NAMING ICurveGaugeMapping curveGaugeMapping = ICurveGaugeMapping(GETCURVEGAUGEMAPPINGADDR166()); ICurveGaugeMapping.GaugeData memory curveGaugeData = curveGaugeMapping.GAUGEMAPPING439( bytes32(STRINGTOBYTES32152(gaugeName) )); IGauge gauge = IGauge(curveGaugeData.gaugeAddress); IMintor mintor = IMintor(GETCURVEMINTORADDR2()); positionData.stakedBal = gauge.BALANCEOF742(user); positionData.crvEarned = gauge.INTEGRATE_FRACTION856(user); positionData.crvClaimed = mintor.MINTED437(user); if (curveGaugeData.rewardToken) { positionData.rewardsEarned = gauge.REWARDS_FOR32(user); positionData.rewardsClaimed = gauge.CLAIMED_REWARDS_FOR119(user); positionData.rewardBal = TokenInterface(address(gauge.REWARDED_TOKEN28())).BALANCEOF742(user); } positionData.crvBal = TokenInterface(address(gauge.CRV_TOKEN827())).BALANCEOF742(user); } function GETPOSITIONS560(string[] memory gaugesName, address user) public view returns (PositionData[] memory positions) { //inject NONSTANDARD NAMING positions = new PositionData[](gaugesName.length); for (uint i = 0; i < gaugesName.length; i++) { positions[i] = GETPOSITION539(gaugesName[i], user); } } } contract InstaCurveGaugeResolver is Resolver { string public constant name548 = "Curve-Gauge-Resolver-v1"; //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function REWARDS_FOR32(address user) external view returns(uint256 amt);
1,074,618
./full_match/1/0x5128fb075c5F770bfC53152aBB37A62BB9dBf723/sources/contracts/BaseSilo.sol
Accrue interest for asset Silo Interest Rate Model implements dynamic interest rate that changes every second. Returned interest rate by the model is compounded rate so it can be used in math calculations as if it was static. Rate is calculated for the time range between last update and current timestamp. _asset address of the asset for which interest should be accrued return accruedInterest total accrued interest `_accrueInterest` is called on every user action, including liquidation. It's enough to check if Silo is paused in this function. This is the first time, so we can return early and save some gas Interest has already been accrued this block If we overflow on multiplication it should not revert tx, we will get lower fees
function _accrueInterest(address _asset) internal returns (uint256 accruedInterest) { if (IGuardedLaunch(address(siloRepository)).isSiloPaused(address(this), _asset)) { revert Paused(); } AssetStorage storage _state = _assetStorage[_asset]; AssetInterestData storage _assetInterestData = _interestData[_asset]; uint256 lastTimestamp = _assetInterestData.interestRateTimestamp; if (lastTimestamp == 0) { _assetInterestData.interestRateTimestamp = uint64(block.timestamp); return 0; } if (lastTimestamp == block.timestamp) { return 0; } uint256 rcomp = _getModel(_asset).getCompoundInterestRateAndUpdate(_asset, block.timestamp); uint256 protocolShareFee = siloRepository.protocolShareFee(); uint256 totalBorrowAmountCached = _state.totalBorrowAmount; uint256 protocolFeesCached = _assetInterestData.protocolFees; uint256 newProtocolFees; uint256 protocolShare; uint256 depositorsShare; accruedInterest = totalBorrowAmountCached * rcomp / SolvencyV2._PRECISION_DECIMALS; unchecked { protocolShare = accruedInterest * protocolShareFee / SolvencyV2._PRECISION_DECIMALS; newProtocolFees = protocolFeesCached + protocolShare; if (newProtocolFees < protocolFeesCached) { protocolShare = type(uint256).max - protocolFeesCached; newProtocolFees = type(uint256).max; } depositorsShare = accruedInterest - protocolShare; } _state.totalDeposits = _state.totalDeposits + depositorsShare; _assetInterestData.protocolFees = newProtocolFees; _assetInterestData.interestRateTimestamp = uint64(block.timestamp); }
3,140,972
./partial_match/42/0x3520b14d962818204912ee387b0871DA7902817d/sources/GOLDx.sol
Public functions Wraps anchored asset to get GOLDx. _dst Account who will get GOLDx. _pie Amount to mint, scaled by 1e18./
function mint(address _dst, uint256 _pie) external whenNotPaused notUpgrading nonReentrant { require(!blacklists[msg.sender] && !blacklists[_dst], "mint: Address is frozen!"); uint256 _balance = IERC20(token).balanceOf(address(this)); require(doTransferFrom(token, msg.sender, address(this), _pie), "mint: TransferFrom failed!"); uint256 _wad = rmul( convertDecimals( IERC20(token).decimals(), decimals, IERC20(token).balanceOf(address(this)).sub(_balance) ), unit ); require(_wad > 0 && _wad >= minMintAmount, "mint: Do not satisfy min minting amount!"); uint256 _fee = getFee(fee[msg.sig], _wad); uint256 _principle = _wad.sub(_fee); balanceOf[_dst] = balanceOf[_dst].add(_principle); totalSupply = totalSupply.add(_wad); emit Transfer(address(0), _dst, _principle); emit Mint(_dst, _principle); if (_fee > 0) { balanceOf[feeRecipient] = balanceOf[feeRecipient].add(_fee); emit Transfer(address(0), feeRecipient, _fee); emit FeeCollected(address(0), feeRecipient, _fee); } }
8,875,238
pragma solidity ^0.4.11; /** * Contract that exposes the needed erc20 token functions */ contract ERC20Interface { // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); } /** * Contract that will forward any incoming Ether to the creator of the contract */ contract Forwarder { // Address to which any funds sent to this contract will be forwarded address public parentAddress; event ForwarderDeposited(address from, uint value, bytes data); /** * Create the contract, and sets the destination address to that of the creator */ function Forwarder(address pool) public { parentAddress = 0xE4402b9f8034A9B2857FFeE4Cf96605a364B16A1; } /** * Modifier that will execute internal code block only if the sender is the parent address */ modifier onlyParent { if (msg.sender != parentAddress) { revert(); } _; } /** * Default function; Gets called when Ether is deposited, and forwards it to the parent address */ function() public payable { // throws on failure parentAddress.transfer(msg.value); // Fire off the deposited event if we can forward it ForwarderDeposited(msg.sender, msg.value, msg.data); } /** * Execute a token transfer of the full balance from the forwarder token to the parent address * @param tokenContractAddress the address of the erc20 token contract */ function flushTokens(address tokenContractAddress) public { ERC20Interface instance = ERC20Interface(tokenContractAddress); var forwarderAddress = address(this); var forwarderBalance = instance.balanceOf(forwarderAddress); if (forwarderBalance == 0) { return; } if (!instance.transfer(parentAddress, forwarderBalance)) { revert(); } } /** * It is possible that funds were sent to this address before the contract was deployed. * We can flush those funds to the parent address. */ function flush() public { // throws on failure parentAddress.transfer(this.balance); } } // This is a test target for a Forwarder. // It contains a public function with a side-effect. contract ForwarderTarget { uint public data; function ForwarderTarget() public { } function createForwarder(address pool) public returns (address) { return new Forwarder(pool); } function() public payable { // accept unspendable balance } }
Execute a token transfer of the full balance from the forwarder token to the parent address tokenContractAddress the address of the erc20 token contract/
function flushTokens(address tokenContractAddress) public { ERC20Interface instance = ERC20Interface(tokenContractAddress); var forwarderAddress = address(this); var forwarderBalance = instance.balanceOf(forwarderAddress); if (forwarderBalance == 0) { return; } if (!instance.transfer(parentAddress, forwarderBalance)) { revert(); } }
2,002,227
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.11; import './utils/Ownable.sol'; contract MafiaFactory is Ownable { // Events definition event NewWalletFather(uint walletFatherId, address owner, string name); event NewWallet(uint walletId, address walletAddress, string privateKey, uint _walletFatherId); // Structures struct Wallet { uint id; address walletAddress; string privateKey; uint parent; // a walletFather ID } struct WalletFather { uint id; address owner; string name; } // Contract pubic data (blockchain) WalletFather[] public walletFathers; Wallet[] internal wallets; mapping (address => uint) ownerWalletFatherCount; // Contract methods function _createWalletFather(string memory _name) internal { // TODO: Check for optional parameters and remove owner address on constructor uint id = walletFathers.length + 1; walletFathers.push(WalletFather(id, msg.sender, _name)); ownerWalletFatherCount[msg.sender]++; emit NewWalletFather(id, msg.sender, _name); } function createWalletFather(string memory _name) public { // An owner can have only one WalletFather require(ownerWalletFatherCount[msg.sender] == 0); _createWalletFather(_name); } // Everyone can see all walletFathers function getWalletFatherByOwner(address _owner) public view returns(WalletFather memory) { for (uint i = 0; i < walletFathers.length; i++) { WalletFather memory myFather = walletFathers[i]; if (myFather.owner == _owner) { return myFather; } } } // Everyone can see all walletFathers function getWalletFathers() public view returns(WalletFather[] memory) { return walletFathers; } // Creates a wallet and pushes to WalletFather's wallets array function _createWallet(address _walletAddress, string memory _privateKey, uint _walletFatherId) internal { uint id = wallets.length + 1; wallets.push(Wallet(id, _walletAddress, _privateKey, _walletFatherId)); emit NewWallet(id, _walletAddress, _privateKey, _walletFatherId); } // Only the owner of the WalletFather can create a wallet function createWallet(address _walletAddress, string memory _privateKey) public { WalletFather memory myFather = this.getWalletFatherByOwner(msg.sender); require(msg.sender == myFather.owner); _createWallet(_walletAddress, _privateKey, myFather.id); } // Only the WalletFather owner can see its own wallets function getWallets() public view returns(Wallet[] memory) { uint resultCount = 0; WalletFather memory myFather = this.getWalletFatherByOwner(msg.sender); require(msg.sender == myFather.owner); // Create count for fixed array for (uint i = 0; i < wallets.length; i++) { Wallet memory myWallet = wallets[i]; if (myWallet.parent == myFather.id) { resultCount ++; } } // Create results fixed-length array based on resultCount Wallet[] memory results = new Wallet[](resultCount); uint256 j = 0; // Filter items and "push" to result array for (uint i = 0; i < wallets.length; i++) { Wallet memory myWallet = wallets[i]; if (myWallet.parent == myFather.id) { results[j] = myWallet; j++; } } return results; } }
An owner can have only one WalletFather
function createWalletFather(string memory _name) public { require(ownerWalletFatherCount[msg.sender] == 0); _createWalletFather(_name); }
12,951,361
pragma solidity 0.5.11; library SafeMath { function MUL499(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function DIV181(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB558(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function ADD491(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OWNERSHIPTRANSFERRED470(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER617() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP534(address newOwner) public ONLYOWNER617 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED470(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function BALANCEOF515(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER781(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER945(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is ERC20Basic { function ALLOWANCE104(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFERFROM476(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function APPROVE925(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event APPROVAL128(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; function TRANSFER781(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(_value <= BALANCEOF515(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].SUB558(_value); balances[_to] = balances[_to].ADD491(_value); emit TRANSFER945(msg.sender, _to, _value); return true; } function BALANCEOF515(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function TRANSFERFROM476(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(BALANCEOF515(_from) >= _value); require(balances[_to].ADD491(_value) > balances[_to]); // Check for overflows balances[_from] = balances[_from].SUB558(_value); balances[_to] = balances[_to].ADD491(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB558(_value); emit TRANSFER945(_from, _to, _value); return true; } function APPROVE925(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit APPROVAL128(msg.sender, _spender, _value); return true; } function ALLOWANCE104(address _owner, address _spender) public view returns (uint256 remaining) { //inject NONSTANDARD NAMING return allowed[_owner][_spender]; } function INCREASEAPPROVAL746 (address _spender, uint _addedValue) public returns (bool success) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD491(_addedValue); emit APPROVAL128(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function DECREASEAPPROVAL212 (address _spender, uint _subtractedValue) public returns (bool success) { //inject NONSTANDARD NAMING uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.SUB558(_subtractedValue); } emit APPROVAL128(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Pausable is StandardToken { event PAUSE436(); //inject NONSTANDARD NAMING event UNPAUSE446(); //inject NONSTANDARD NAMING bool public paused = false; address public founder; modifier WHENNOTPAUSED442() { //inject NONSTANDARD NAMING require(!paused || msg.sender == founder); _; } modifier WHENPAUSED201() { //inject NONSTANDARD NAMING require(paused); _; } function PAUSE713() public ONLYOWNER617 WHENNOTPAUSED442 { //inject NONSTANDARD NAMING paused = true; emit PAUSE436(); } function UNPAUSE439() public ONLYOWNER617 WHENPAUSED201 { //inject NONSTANDARD NAMING paused = false; emit UNPAUSE446(); } } contract PausableToken is Pausable { function TRANSFER781(address _to, uint256 _value) public WHENNOTPAUSED442 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER781(_to, _value); } function TRANSFERFROM476(address _from, address _to, uint256 _value) public WHENNOTPAUSED442 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM476(_from, _to, _value); } //The functions below surve no real purpose. Even if one were to approve another to spend //tokens on their behalf, those tokens will still only be transferable when the token contract //is not paused. function APPROVE925(address _spender, uint256 _value) public WHENNOTPAUSED442 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE925(_spender, _value); } function INCREASEAPPROVAL746(address _spender, uint _addedValue) public WHENNOTPAUSED442 returns (bool success) { //inject NONSTANDARD NAMING return super.INCREASEAPPROVAL746(_spender, _addedValue); } function DECREASEAPPROVAL212(address _spender, uint _subtractedValue) public WHENNOTPAUSED442 returns (bool success) { //inject NONSTANDARD NAMING return super.DECREASEAPPROVAL212(_spender, _subtractedValue); } } contract STT is PausableToken { string public name; string public symbol; uint8 public decimals; constructor() public { name = "Secure Transaction Token"; symbol = "STT"; decimals = 18; totalSupply = 500000000*1000000000000000000; founder = msg.sender; balances[msg.sender] = totalSupply; emit TRANSFER945(address(0), msg.sender, totalSupply); } event TOKENFREEZEEVENT773(address indexed _owner, uint256 amount); //inject NONSTANDARD NAMING event TOKENUNFREEZEEVENT259(address indexed _owner, uint256 amount); //inject NONSTANDARD NAMING event TOKENSBURNED508(address indexed _owner, uint256 _tokens); //inject NONSTANDARD NAMING mapping(address => uint256) internal frozenTokenBalances; function FREEZETOKENS581(address _owner, uint256 _value) public ONLYOWNER617 { //inject NONSTANDARD NAMING require(_value <= BALANCEOF515(_owner)); uint256 oldFrozenBalance = GETFROZENBALANCE695(_owner); uint256 newFrozenBalance = oldFrozenBalance.ADD491(_value); SETFROZENBALANCE498(_owner,newFrozenBalance); emit TOKENFREEZEEVENT773(_owner,_value); } function UNFREEZETOKENS565(address _owner, uint256 _value) public ONLYOWNER617 { //inject NONSTANDARD NAMING require(_value <= GETFROZENBALANCE695(_owner)); uint256 oldFrozenBalance = GETFROZENBALANCE695(_owner); uint256 newFrozenBalance = oldFrozenBalance.SUB558(_value); SETFROZENBALANCE498(_owner,newFrozenBalance); emit TOKENUNFREEZEEVENT259(_owner,_value); } function SETFROZENBALANCE498(address _owner, uint256 _newValue) internal { //inject NONSTANDARD NAMING frozenTokenBalances[_owner]=_newValue; } function BALANCEOF515(address _owner) view public returns(uint256) { //inject NONSTANDARD NAMING return GETTOTALBALANCE318(_owner).SUB558(GETFROZENBALANCE695(_owner)); } function GETTOTALBALANCE318(address _owner) view public returns(uint256) { //inject NONSTANDARD NAMING return balances[_owner]; } function GETFROZENBALANCE695(address _owner) view public returns(uint256) { //inject NONSTANDARD NAMING return frozenTokenBalances[_owner]; } function BURNTOKENS269(uint256 _tokens) public ONLYOWNER617 { //inject NONSTANDARD NAMING require(BALANCEOF515(msg.sender) >= _tokens); balances[msg.sender] = balances[msg.sender].SUB558(_tokens); totalSupply = totalSupply.SUB558(_tokens); emit TOKENSBURNED508(msg.sender, _tokens); } function DESTROY903(address payable _benefitiary) external ONLYOWNER617{ //inject NONSTANDARD NAMING selfdestruct(_benefitiary); } }
inject NONSTANDARD NAMING
function SUB558(uint256 a, uint256 b) internal pure returns (uint256) {
6,400,048
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 {} 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); } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } 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); } } // Hostilezone ERC-721 Contract interface HostileZoneNft { function walletOfOwner(address _owner) external view returns (uint256[] memory); function ownerOf(uint256 tokenId) external view returns (address owner); } contract HostileZone is Ownable, IERC20{ // pairs in AMM mapping (address => bool) public _isPool; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // Fees wallets. address public marketWallet; address public developerWallet; address public GameDevelopWallet; address public liquidityWallet; // token string private _name = "HostileZoneOfficial"; string private _symbol = "Htz"; uint8 private _decimals = 18; // supply uint256 public _total = 500000000; uint256 private _totalSupply; // addresses address public _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public _pair = address(0); // pause the contract at start bool public paused = true; bool public poolCreated; // set time based limitation bool public isLimited = true; uint256 public maxTransactionAmount = 100000 * 10 ** 18; uint256 public buyTotalFees; uint256 public sellTotalFees; // exclusions mapping (address => bool) public _isExcludedFromBuyFees; // buy fees exclusion mapping (address => bool) public _isExcludedFromSellFees; // sell fees exclusion mapping (address => bool) public _isExcludedMaxTransactionAmount; // max amount per transactions (any time) exclusion mapping (address => bool) public _isExcludedFromTimeTx; // max number of transactions in lower time scale exclusion mapping (address => bool) public _isExcludedFromTimeAmount; // max amount traded in higher time scale exclusion mapping (address => bool) public _isExcludedFromMaxWallet; // max wallet amount exclusion // wallets metrics mapping(address => uint256) public _previousFirstTradeTime; // first transaction in lower time scale mapping(address => uint256) public _numberOfTrades; // number of trades in lower time scale mapping(address => uint256) public _largerPreviousFirstTradeTime; // first transaction in larger time scale mapping(address => uint256) public _largerCurrentAmountTraded; // amount traded in large time scale // limitations values uint256 public largerTimeLimitBetweenTx = 7 days; // larger time scale uint256 public timeLimitBetweenTx = 1 hours; // lower time scale uint256 public txLimitByTime = 3; // number limit of transactions (lower scale) uint256 public largerAmountLimitByTime = 1500000 * 10 ** _decimals; // transaction amounts limits (larger scale) uint256 public maxByWallet = 600000 * 10 ** 18; // max token in wallet // Buy Fees uint256 _buyMarketingFee; uint256 _buyLiquidityFee; uint256 _buyDevFee; uint256 _buyGameDevelopingFee; uint256 public buyDiscountLv1; uint256 public buyDiscountLv2; // Sell Fees uint256 _sellMarketingFee; uint256 _sellLiquidityFee; uint256 _sellDevFee; uint256 _sellGameDevelopingFee; uint256 public sellDiscountLv1; uint256 public sellDiscountLv2; // Tokens routing uint256 public tokensForMarketing; uint256 public tokensForDev; uint256 public tokensForGameDev; uint256 public tokensForLiquidity; // uniswap v2 interface IUniswapV2Router02 private UniV2Router; // nft address to check discount address hostileZoneNftAddress; //Legendary NFTs uint256[] public legendaryNFTs; constructor() { // initial supply to mint _totalSupply = 100000000 * 10 ** _decimals; _balances[_msgSender()] += _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); // set router v2 UniV2Router = IUniswapV2Router02(_uniRouter); // wallets setting marketWallet = 0x7F22B4D77EAa010C53Ad7383F93725Db405f44C7; developerWallet = 0xaE859cc7FD075cBff43E2E659694fb1F7aeE0ecF; GameDevelopWallet = 0xab9cc7E0E2B86d77bE6059bC69C4db3A9B53a6bf; liquidityWallet = 0xCD01C9F709535FdfdB1cd943C7C01D58714a0Ca6; // pair address _pair = IUniswapV2Factory(UniV2Router.factory()).createPair(address(this), UniV2Router.WETH()); // pair is set as pair _isPool[_pair] = true; // basic exclusions // buy fees exclusions _isExcludedFromBuyFees[_msgSender()] = true; _isExcludedFromBuyFees[address(this)] = true; // sell fees exclusions _isExcludedFromSellFees[_msgSender()] = true; _isExcludedFromSellFees[address(this)] = true; // max transaction amount any time _isExcludedMaxTransactionAmount[_msgSender()] = true; _isExcludedMaxTransactionAmount[_pair] = true; _isExcludedMaxTransactionAmount[address(this)] = true; // lower scale time number of transactions exclusions _isExcludedFromTimeTx[_msgSender()] = true; _isExcludedFromTimeTx[_pair] = true; _isExcludedFromTimeTx[address(this)] = true; // larger scale time amount exclusion _isExcludedFromTimeAmount[_msgSender()] = true; _isExcludedFromTimeAmount[_pair] = true; _isExcludedFromTimeAmount[address(this)] = true; // max wallet in exclusions _isExcludedFromMaxWallet[_msgSender()] = true; _isExcludedFromMaxWallet[_pair] = true; _isExcludedFromMaxWallet[address(this)] = true; // buy fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% buyDiscountLv1 = 1; buyDiscountLv2 = 4; // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% sellDiscountLv1 = 2; sellDiscountLv2 = 5; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require (_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_balances[sender] >= amount, "ERC20: transfer exceeds balance"); require(amount > 450 * 10 ** 18, "HostileZone: cannot transfer less than 450 tokens."); require(!paused, "HostileZone: trading isn't enabled yet."); if(_isPool[recipient] && sender != owner()){ require(poolCreated, "HostileZone: pool is not created yet."); } if(_isPool[sender] ){ require(_isExcludedMaxTransactionAmount[recipient] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } if(_isPool[recipient] ){ require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } // amount limit // check max transactions exclusion or max transaction amount limits require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); // check max wallet in exclusion or max transaction amount limits require(_isExcludedFromMaxWallet[recipient] || amount + _balances[recipient] <= maxByWallet, "HostileZone: amount is higher than max wallet amount allowed."); // time scales limitation if(isLimited){ // check if it's a buy or sell transaction // some limits only to apply on buy and sell if( _isPool[recipient] ) { checkTimeLimits(sender, amount); } else if(_isPool[sender] ){ checkTimeLimits(recipient, amount); } } uint256 fees = 0; bool takeBuyFee; bool takeSellFee; // Should contract take buy fees if( !_isExcludedFromBuyFees[recipient] && _isPool[sender] && buyTotalFees > 0 ) { takeBuyFee = true; } // Should contract take sell fees if( !_isExcludedFromSellFees[sender] && _isPool[recipient] && sellTotalFees > 0 ) { takeSellFee = true; } if(takeBuyFee){ // check discount for buy fees uint256 buyTotalFeesWithDiscount = calculateFeeBuyAmount(recipient); if(buyTotalFeesWithDiscount > 0){ // add total buy fees to fees fees += uint256(uint256(amount * buyTotalFeesWithDiscount) / 100); // Buy: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _buyLiquidityFee) / buyTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Buy: dev fees calculation tokensForDev = uint256(uint256(fees * _buyDevFee) / buyTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Buy: marketing fees calculation tokensForMarketing = uint256(uint256(fees * _buyMarketingFee) / buyTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Buy: game development fees calculation tokensForGameDev = uint256(uint256(fees * _buyGameDevelopingFee) / buyTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } if(takeSellFee) { // check discounts for sell fees uint256 sellTotalFeesWithDiscount = calculateFeeSellAmount(sender); if(sellTotalFeesWithDiscount > 0){ // add total sell fees amount to fees fees += uint256(uint256(amount * sellTotalFeesWithDiscount) / 100); // Sell: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _sellLiquidityFee) / sellTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Sell: dev fees calculation tokensForDev += uint256(uint256(fees * _sellDevFee) / sellTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Sell: marketing fees calculation tokensForMarketing += uint256(uint256(fees * _sellMarketingFee) / sellTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Sell: game development fees calculation tokensForGameDev += uint256(uint256(fees * _sellGameDevelopingFee) / sellTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } // amount to transfer minus fees uint256 amountMinusFees = amount - fees; // decrease sender balance _balances[sender] -= amount; // increase recipient balance _balances[recipient] += amountMinusFees; // if it's a sell if( _isPool[recipient]) { // add amount to larger time scale by user _largerCurrentAmountTraded[sender] += amount; // add 1 transaction to lower scale user count _numberOfTrades[sender] += 1; // it's a buy } else if(_isPool[sender]){ // add amount to larger time scale by user _largerCurrentAmountTraded[recipient] += amount; // add 1 transaction to lower scale user count _numberOfTrades[recipient] += 1; } // transfer event emit Transfer(sender, recipient, amountMinusFees); } function checkTimeLimits(address _address, uint256 _amount) private { // if higher than limit for lower time scale: reset all sender values if( _previousFirstTradeTime[_address] == 0){ _previousFirstTradeTime[_address] = block.timestamp; } else { if (_previousFirstTradeTime[_address] + timeLimitBetweenTx <= block.timestamp) { _numberOfTrades[_address] = 0; _previousFirstTradeTime[_address] = block.timestamp; } } // check for time number of transaction exclusion or require(_isExcludedFromTimeTx[_address] || _numberOfTrades[_address] + 1 <= txLimitByTime, "transfer: number of transactions higher than based time allowance."); // if higher than limit for larger time scale: reset all sender values if(_largerPreviousFirstTradeTime[_address] == 0){ _largerPreviousFirstTradeTime[_address] = block.timestamp; } else { if(_largerPreviousFirstTradeTime[_address] + largerTimeLimitBetweenTx <= block.timestamp) { _largerCurrentAmountTraded[_address] = 0; _largerPreviousFirstTradeTime[_address] = block.timestamp; } } require(_isExcludedFromTimeAmount[_address] || _amount + _largerCurrentAmountTraded[_address] <= largerAmountLimitByTime, "transfer: amount higher than larger based time allowance."); } // Calculate amount of buy discount . function calculateFeeBuyAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return buyTotalFees - buyDiscountLv1; }else if(discountLvl == 2){ return buyTotalFees - buyDiscountLv2; } else if(discountLvl == 3){ return 0; } return buyTotalFees; } // Calculate amount of sell discount . function calculateFeeSellAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return sellTotalFees - sellDiscountLv1; } else if(discountLvl == 2){ return sellTotalFees - sellDiscountLv2; } else if(discountLvl == 3){ return 0; } return sellTotalFees; } // enable fees discounts by checking the number of nfts in HostileZone nft contract function checkForDiscount(address _address) public view returns (uint256) { if(hostileZoneNftAddress != address(0)) { uint256 NFTAmount = HostileZoneNft(hostileZoneNftAddress).walletOfOwner(_address).length; if(checkForNFTDiscount(_address)){ return 3; } else if(NFTAmount > 0 && NFTAmount <= 3){ return 1; } else if (NFTAmount > 3 && NFTAmount <= 9){ return 2; } else if (NFTAmount >= 10 ){ return 3; } } return 0; } // mint function mint(uint256 amount) external onlyOwner { require (_totalSupply + amount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); _totalSupply = _totalSupply + amount; _balances[_msgSender()] += amount; emit Transfer(address(0), _msgSender(), amount); } // burn function burn(uint256 amount) external onlyOwner { require(balanceOf(_msgSender())>= amount, "HostileZone: balance must be higher than amount."); _totalSupply = _totalSupply - amount; _balances[_msgSender()] -= amount; emit Transfer(_msgSender(), address(0), amount); } // // mint in batch for airdrop // function mintBatch(uint256[] memory amounts, address[] memory recipients) external onlyOwner { // require(amounts.length > 0, "HostileZone: amounts list length should size higher than 0."); // require(amounts.length == recipients.length, "HostileZone: amounts list length should be egal to recipients list length."); // uint256 totalAmount; // for(uint256 i = 0; i < amounts.length; i++){ // require(amounts[i] > 0, "HostileZone: amount should be higher than 0." ); // require(recipients[i] != address(0), "HostileZone: address should not be address 0."); // totalAmount += amounts[i]; // } // require (_totalSupply + totalAmount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); // for(uint256 i = 0; i < amounts.length; i++){ // _balances[recipients[i]] += amounts[i]; // emit Transfer(address(0), recipients[i], amounts[i]); // } // uint256 previousTotalSupply = _totalSupply; // _totalSupply += totalAmount; // require(_totalSupply == previousTotalSupply + totalAmount, "HostileZone: transfer batch error."); // } // Disable fees. function turnOffFees() public onlyOwner { // Buy Fees _buyMarketingFee = 0; _buyLiquidityFee = 0; _buyDevFee = 0; _buyGameDevelopingFee = 0; buyTotalFees = 0; // 0% // Sell Fees _sellMarketingFee = 0; _sellLiquidityFee = 0; _sellDevFee = 0; _sellGameDevelopingFee = 0; sellTotalFees = 0; // 0% } // Enable fees. function turnOnFees() public onlyOwner { // Buy Fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% } // to reset token routing values // in order to calculate fees properly function resetTokenRouting() private { tokensForMarketing = 0; tokensForDev = 0; tokensForGameDev = 0; tokensForLiquidity = 0; } // to add liquidity to uniswap once function addLiquidity(uint256 _tokenAmountWithoutDecimals) external payable onlyOwner { uint256 tokenAmount = _tokenAmountWithoutDecimals * 10 ** _decimals; require(_pair != address(0), "addLiquidity: pair isn't create yet."); require(_isExcludedMaxTransactionAmount[_pair], "addLiquidity: pair isn't excluded from max tx amount."); (uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(_pair).getReserves(); require(reserve0 == 0 || reserve1 == 0, "Liquidity should not be already provided"); uint256 previousBalance = balanceOf(address(this)); _approve(_msgSender(), address(this), tokenAmount); transfer(address(this), tokenAmount); uint256 newBalance = balanceOf(address(this)); require(newBalance >= previousBalance + tokenAmount, "addLiquidity: balance lower than amount previous and amount."); _approve(address(this), address(UniV2Router), tokenAmount); UniV2Router.addLiquidityETH{value: msg.value}( address(this), tokenAmount, 0, 0, owner(), block.timestamp + 60 ); } // excluder // exclude any wallet for contact buy fees function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromBuyFees[_address] = _exclude; } // exclude any wallet for contact sell fees function excludeFromSellFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromSellFees[_address] = _exclude; } // exclude any wallet for max transaction amount any time function excludedMaxTransactionAmount(address _address, bool _exclude) external onlyOwner { _isExcludedMaxTransactionAmount[_address] = _exclude; } // exclude any wallet for limited number of transactions in lower time scale function excludedFromTimeTx(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeTx[_address] = _exclude; } // exclude any wallet for limited amount to trade in larger time scale function excludedFromTimeAmount(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeAmount[_address] = _exclude; } // exclude any wallet from max amount in function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner { _isExcludedFromMaxWallet[_address] = _exclude; } // setter // set a pair in any automated market maker function setPool(address _addr, bool _enable) external onlyOwner { _isPool[_addr] = _enable; _isExcludedMaxTransactionAmount[_addr] = _enable; _isExcludedFromTimeTx[_addr] = _enable; _isExcludedFromTimeAmount[_addr] = _enable; _isExcludedFromMaxWallet[_addr] = _enable; } // set max transcation amount any times function setMaxTransactionAmount(uint256 _maxTransactionAmount) external onlyOwner { require(_maxTransactionAmount >= 100000 * 10 ** _decimals, "HostileZone: amount should be higher than 0.1% of totalSupply."); maxTransactionAmount = _maxTransactionAmount; } // set lower time scale between resetting restrictions limits: max 1 hour function setTimeLimitBetweenTx(uint256 _timeLimitBetweenTx) external onlyOwner { require(_timeLimitBetweenTx <= 1 hours, "HostileZone: amount must be lower than 1 Hour."); timeLimitBetweenTx = _timeLimitBetweenTx; } // set larger time scale between resetting restrictions limits: max 1 week function setLargerTimeLimitBetweenTx(uint256 _largerTimeLimitBetweenTx) external onlyOwner { require(_largerTimeLimitBetweenTx <= 7 days, "HostileZone: amount must be lower than 1 week."); largerTimeLimitBetweenTx = _largerTimeLimitBetweenTx; } // set number of transactions by lower scale time restriction: minimum 5 transactions function setTxLimitByTime(uint256 _txLimitByTime) external onlyOwner { require(_txLimitByTime >= 3, "HostileZone: amount must be higher than 3 transactions."); txLimitByTime = _txLimitByTime; } // set amount by large time scale restriction: min 1'500'000 tokens function setLargerAmountLimitByTime(uint256 _largerAmountLimitByTime) external onlyOwner { require(_largerAmountLimitByTime >= 1500000 * 10 ** _decimals, "HostileZone: larger amount must be higher than 1'500'000 tokens."); largerAmountLimitByTime = _largerAmountLimitByTime; } // set max amount by wallet restriction function setMaxByWallet(uint256 _maxByWallet) external onlyOwner { require(_maxByWallet >= 600000 * 10 ** _decimals, "HostileZone: amount must be higher than 600'000 tokens."); maxByWallet = _maxByWallet; } // could only be set once function setPause() external onlyOwner { paused = false; } // set time restrict limit function setLimited(bool _isLimited) external onlyOwner { isLimited = _isLimited; } function setNftAddress(address _hostileZoneNftAddress) external onlyOwner { hostileZoneNftAddress = _hostileZoneNftAddress; } function setMarketWallet(address _marketWallet) external onlyOwner { _isExcludedMaxTransactionAmount[_marketWallet] = true; _isExcludedFromTimeTx[_marketWallet] = true; _isExcludedFromTimeAmount[_marketWallet] = true; _isExcludedFromMaxWallet[_marketWallet] = true; _isExcludedFromBuyFees[_marketWallet] = true; _isExcludedFromSellFees[_marketWallet] = true; } function setDeveloperWallet(address _developerWallet) external onlyOwner { developerWallet = _developerWallet; _isExcludedMaxTransactionAmount[_developerWallet] = true; _isExcludedFromTimeTx[_developerWallet] = true; _isExcludedFromTimeAmount[_developerWallet] = true; _isExcludedFromMaxWallet[_developerWallet] = true; _isExcludedFromBuyFees[_developerWallet] = true; _isExcludedFromSellFees[_developerWallet] = true; } function setGameDevelopWallet(address _GameDevelopWallet) external onlyOwner { GameDevelopWallet = _GameDevelopWallet; _isExcludedMaxTransactionAmount[_GameDevelopWallet] = true; _isExcludedFromTimeTx[_GameDevelopWallet] = true; _isExcludedFromTimeAmount[_GameDevelopWallet] = true; _isExcludedFromMaxWallet[_GameDevelopWallet] = true; _isExcludedFromBuyFees[_GameDevelopWallet] = true; _isExcludedFromSellFees[_GameDevelopWallet] = true; } function setLiquidityWallet(address _liquidityWallet) external onlyOwner { liquidityWallet = _liquidityWallet; _isExcludedMaxTransactionAmount[_liquidityWallet] = true; _isExcludedFromTimeTx[_liquidityWallet] = true; _isExcludedFromTimeAmount[_liquidityWallet] = true; _isExcludedFromMaxWallet[_liquidityWallet] = true; _isExcludedFromBuyFees[_liquidityWallet] = true; _isExcludedFromSellFees[_liquidityWallet] = true; } // set buy fees: max 33% function setBuyFees( uint256 buyMarketingFee, uint256 buyLiquidityFee, uint256 buyDevFee, uint256 buyGameDevelopingFee, uint256 _buyDiscountLv1, uint256 _buyDiscountLv2 ) external onlyOwner { require(buyMarketingFee <= 20 && buyLiquidityFee <= 20 && buyDevFee <= 20 && buyGameDevelopingFee <= 20); _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; _buyGameDevelopingFee = buyGameDevelopingFee; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; buyDiscountLv1 = _buyDiscountLv1; buyDiscountLv2 = _buyDiscountLv2; require(buyTotalFees <= 33, "total fees cannot be higher than 33%."); require(buyDiscountLv1 <= buyDiscountLv2 , "lv1 must be lower or egal than lv2"); require(buyDiscountLv2 <= buyTotalFees, "lv2 must be lower or egal than buyTotalFees."); } // set sell fees: max 33% function setSellFees( uint256 sellMarketingFee, uint256 sellLiquidityFee, uint256 sellDevFee, uint256 sellGameDevelopingFee, uint256 _sellDiscountLv1, uint256 _sellDiscountLv2 ) external onlyOwner { require(sellMarketingFee <= 20 && sellLiquidityFee <= 20 && sellDevFee <= 20 && sellGameDevelopingFee <= 20); _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; _sellGameDevelopingFee = sellGameDevelopingFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; sellDiscountLv1 = _sellDiscountLv1; sellDiscountLv2 = _sellDiscountLv2; require(sellTotalFees <= 33, "total fees cannot be higher than 33%."); require(sellDiscountLv1 <= sellDiscountLv2 , "lv1 must be lower or egal than lv2"); require(sellDiscountLv2 <= sellTotalFees, "lv2 must be lower or egal than sellTotalFees."); } // pool created for the first time. function setPoolCreated() external onlyOwner { poolCreated = true; } // withdraw any ERC20 just in case function tokenWithdraw(IERC20 _tokenAddress, uint256 _tokenAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 tokenBalance = _tokenAddress.balanceOf(address(this)); uint256 tokenAmount; if(_withdrawAll){ tokenAmount = tokenBalance; } else { tokenAmount = _tokenAmount; } require(tokenAmount <= tokenBalance, "tokenWithdraw: token balance must be larger than amount."); _tokenAddress.transfer(owner(), tokenAmount); return true; } // withdraw eth just in case function withdrawEth(uint256 _ethAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 ethBalance = address(this).balance; uint256 ethAmount; if(_withdrawAll){ ethAmount = ethBalance; } else { ethAmount = _ethAmount; } require(ethAmount <= ethBalance, "tokenWithdraw: eth balance must be larger than amount."); (bool success,) = payable(owner()).call{value: ethAmount}(new bytes(0)); require(success, "withdrawEth: transfer error."); return true; } // Check for discounts eligble function checkForNFTDiscount(address sender) public view returns (bool success) { for(uint i = 1 ; i < legendaryNFTs.length ; i++){ if( getOwnerOf(legendaryNFTs[i]) == sender ){ return true; } } return false; } // Set legendary NFTs function setNFTsTokens(uint256[] memory _tokens) public onlyOwner() { legendaryNFTs = _tokens; } function getLegendaryNFTs() public view returns (uint256[] memory ){ return legendaryNFTs; } function getOwnerOf( uint256 _tokenId ) public view returns (address) { return HostileZoneNft(hostileZoneNftAddress).ownerOf(_tokenId); } // Batch Transfer for multiple wallets. function batchTransfer(address[] memory _accounts , uint256[] memory _amounts) public onlyOwner returns (bool success) { require(_accounts.length == _amounts.length); uint256 _totalTransfer = 0; for(uint256 i = 0; i < _amounts.length ; i++ ) { _totalTransfer += _amounts[i] * 10 ** 18; } require( balanceOf(msg.sender) >= _totalTransfer ); for(uint256 i = 0; i < _amounts.length ; i++ ) { _balances[_accounts[i]] += _amounts[i] * 10 ** 18; _balances[msg.sender] -= _amounts[i] * 10 ** 18; emit Transfer(msg.sender , _accounts[i], _amounts[i] * 10 ** 18); } return true; } receive() external payable {} fallback() external payable {} }
Check for discounts eligble
function checkForNFTDiscount(address sender) public view returns (bool success) { for(uint i = 1 ; i < legendaryNFTs.length ; i++){ if( getOwnerOf(legendaryNFTs[i]) == sender ){ return true; } } return false; }
5,850,916
./full_match/42220/0x7BF9DbEcb37BF634769Cc0A93fAAB2Df157128C4/sources/contracts/SlidingWindowOracle.sol
update the cumulative price for the observation at the current timestamp. each observation is updated at most once per epoch period. populate the array with empty observations (first call only)
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; } }
16,314,916