file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents { } contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; address private otherF3D_; uint8 private rSees_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xED8c249B7EB8d5b3cF7e0d6CcFA270249f7C0CeF); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Gold medal winner Official"; string constant public symbol = "Gold"; uint256 private rndExtra_ = 60; // length of the very first ICO uint256 private rndGap_ = 60; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 24 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be address constant private ceo = 0x918b8dc988e3702DA4625d69E3D043E8aA9358e6; address constant private cfo = 0xCC221D6154A5091919240b36d476C2BdeAf246BD; address constant private coo = 0x139aAc9edD31015327394160516C26E8f3Ee06AB; address constant private cto = 0xDe0015b72D1dC1F32768Dc1983788F4c32F70f05; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = electric // 1 = cloud // 2 = thunder // 3 = wind // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(48,0); fees_[1] = F3Ddatasets.TeamFee(28,0); fees_[2] = F3Ddatasets.TeamFee(18,0); fees_[3] = F3Ddatasets.TeamFee(38,0); // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(38,0); potSplit_[1] = F3Ddatasets.PotSplit(28,0); potSplit_[2] = F3Ddatasets.PotSplit(23,0); potSplit_[3] = F3Ddatasets.PotSplit(33,0); } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 100000000000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 0, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 1000000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { uint256 bonus = 0; uint256 count = 0; uint256 l = round_[_rID].lastNum; for(uint i = 0; i<l; i++) { uint _pid = round_[_rID].lastPlys[i]; count += plyr_[_pid].lbks; } bonus = (((round_[_rID].pot).mul(48)) / 100).mul(plyr_[_pID].lbks) / count; return ( (plyr_[_pID].win).add(bonus), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256,uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 plyr_[_pID].laff ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { insertLastPlys(_pID); // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth,round_[_rID].keys); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } if (airdrop(_team) == true) { // gib muni uint256 _prize; _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyr_[_pID].lbks = _keys; plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth,round_[_rID].keys) ); else // rounds over. need keys for new round return ( (_eth).keys(round_[_rID].keys) ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 25); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } payLast(_win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); if (_com > 0) { ceo.transfer( _com.mul(20) / 100); cfo.transfer( _com.mul(20) / 100); coo.transfer( _com.mul(50) / 100); cto.transfer(_com.mul(10) / 100); } // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInit_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop(uint256 _temp) private view returns(bool) { uint8 cc= 0; uint8[5] memory randomNum; if(_temp == 0){ randomNum[0]=6; randomNum[1]=22; randomNum[2]=38; randomNum[3]=59; randomNum[4]=96; cc = 5; }else if(_temp == 1){ randomNum[0]=9; randomNum[1]=25; randomNum[2]=65; randomNum[3]=79; cc = 4; }else if(_temp == 2){ randomNum[0]=2; randomNum[1]=57; randomNum[2]=32; cc = 3; }else if(_temp == 3){ randomNum[0]=44; randomNum[1]=90; cc = 2; } uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); seed = seed - ((seed / 100) * 100); for(uint j=0;j<cc;j++) { if(randomNum[j] == seed) { return(true); } } return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 20% out to community rewards uint256 _com = _eth / 5; // distribute share to affiliate uint256 _aff; _aff = _eth.mul(10) / 100; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { //_com = _com.add(_aff); ceo.transfer(_aff.mul(40) / 100); cfo.transfer(_aff.mul(40) / 100); cto.transfer(_aff.mul(20) / 100); } if (_com > 0) { ceo.transfer(_com.mul(20) / 100); cfo.transfer(_com.mul(20) / 100); coo.transfer( _com.mul(50) / 100); cto.transfer(_com.mul(10) / 100); // set up event data _eventData_.P3DAmount = _com.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 20% into airdrop pot uint256 _air = (_eth.mul(2)/ 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(20)) / 100).add((_eth.mul(12)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0x100d5695a0b35bbb8c044AEFef7C7b278E5843e1, "only team just can activate" ); // make sure that its been linked. //require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0x100d5695a0b35bbb8c044AEFef7C7b278E5843e1, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap // otherF3D_ = otherFoMo3D(_otherF3D); otherF3D_ = _otherF3D; } function insertLastPlys(uint256 _pID) private { uint256 _rID = rID_; if(round_[_rID].lastNum == 0) { round_[_rID].lastPlys[0] = _pID; round_[_rID].lastNum++; //round_[_rID].lastPlys.push(_pID); }else if(round_[_rID].lastNum <10) { if(round_[rID_].lastPlys[round_[_rID].lastNum-1] != _pID) { bool repeat = false; for(uint j=0; j<round_[_rID].lastNum; j++) { if(_pID == round_[rID_].lastPlys[j]) { repeat = true; break; } } if(!repeat){ round_[rID_].lastPlys[round_[_rID].lastNum] = _pID; round_[_rID].lastNum++; //round_[rID_].lastPlys.push(_pID); }else{ for(j; j<round_[_rID].lastNum-1; j++){ round_[rID_].lastPlys[j] = round_[rID_].lastPlys[j+1]; } round_[rID_].lastPlys[round_[_rID].lastNum-1] = _pID; } } }else{ if(round_[rID_].lastPlys[round_[_rID].lastNum-1] != _pID) { round_[_rID].lastNum = 10; for(j=0; j<round_[_rID].lastNum-1; j++){ round_[rID_].lastPlys[j] = round_[rID_].lastPlys[j+1]; } round_[rID_].lastPlys[round_[_rID].lastNum-1] = _pID; } } } function payLast(uint _win) private{ uint256 _rID = rID_; uint l = round_[_rID].lastNum; uint _pid; uint i; uint256 count = 0; for( i = 0; i<l; i++) { _pid = round_[_rID].lastPlys[i]; count += plyr_[_pid].lbks; } for( i = 0; i<l; i++) { _pid = round_[_rID].lastPlys[i]; plyr_[_pid].win = (_win.mul(plyr_[_pid].lbks / count) ).add(plyr_[_pid].win); } } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 lbks; // last buy keys } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256[10] lastPlys; // last player uint256 lastNum; //count lastPlys length } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ /* function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } */ function keysRec(uint256 _curEth, uint256 _newEth,uint256 _curKeys) internal pure returns (uint256) { if(_curKeys<=0){ _curKeys=1000000000000000000; } return (keys(_newEth,_curKeys)); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ /* function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { if(_curKeys<=0){ _curKeys=1000000000000000000; } return eth(_curKeys).mul(_sellKeys)/1000000000000000000; } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ /* function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } */ function keys(uint256 _eth,uint256 _curKeys) internal pure returns(uint256) { uint a =1000000000000000; uint b =2000000000; if(_curKeys<=0){ _curKeys=1000000000000000000; } uint c = a .add((b.mul((_curKeys.sub(1000000000000000000))))/1000000000000000000); return (_eth.mul(1000000000000000000)/(c)); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ /* function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } */ function eth(uint256 _keys) internal pure returns(uint256) { uint a =1000000000000000; uint b =2000000000; uint c = a .add((b.mul((_keys.sub(1000000000000000000))))/1000000000000000000); return c; } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
returns the amount of keys you would get given an amount of eth. -functionhash- 0xce89c80c _rID round ID you want price for _eth amount of eth sent in return keys received/ grab time are we in a round?
function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth,round_[_rID].keys) ); return ( (_eth).keys(round_[_rID].keys) ); }
1,374,361
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner=msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken ,Ownable { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title 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 { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } function goalReached() public view returns (bool) { return weiRaised >= goal; } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return capReached || super.hasEnded(); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return withinCap && super.validPurchase(); } } contract Toplancer is MintableToken { string public constant name = "Toplancer"; string public constant symbol = "TLC"; uint8 public constant decimals = 18; } contract Allocation is Ownable { using SafeMath for uint; uint256 public unlockedAt; Toplancer tlc; mapping (address => uint) founderAllocations; uint256 tokensCreated = 0; //decimal value uint256 public constant decimalFactor = 10 ** uint256(18); uint256 constant public FounderAllocationTokens = 840000000*decimalFactor; //address of the founder storage vault address public founderStorageVault = 0x97763051c517DD3aBc2F6030eac6Aa04576E05E1; function TeamAllocation() { tlc = Toplancer(msg.sender); unlockedAt = now; // 20% tokens from the FounderAllocation founderAllocations[founderStorageVault] = FounderAllocationTokens; } function getTotalAllocation() returns (uint256){ return (FounderAllocationTokens); } function unlock() external payable { require (now >=unlockedAt); if (tokensCreated == 0) { tokensCreated = tlc.balanceOf(this); } //transfer the tokens to the founderStorageAddress tlc.transfer(founderStorageVault, tokensCreated); } } contract TLCMarketCrowdsale is RefundableCrowdsale,CappedCrowdsale { enum State {PRESALE, PUBLICSALE} State public state; //decimal value uint256 public constant decimalFactor = 10 ** uint256(18); uint256 public constant _totalSupply = 2990000000 *decimalFactor; uint256 public presaleCap = 200000000 *decimalFactor; // 7% uint256 public soldTokenInPresale; uint256 public publicSaleCap = 1950000000 *decimalFactor; // 65% uint256 public soldTokenInPublicsale; uint256 public distributionSupply = 840000000 *decimalFactor; // 28% Allocation allocation; // How much ETH each address has invested to this crowdsale mapping (address => uint256) public investedAmountOf; // How many distinct addresses have invested uint256 public investorCount; uint256 public minContribAmount = 0.1 ether; // minimum contribution amount is 0.1 ether // Constructor // Token Creation and presale starts //Start time end time should be given in unix timestamps //goal and cap function TLCMarketCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _goal, uint256 _cap) Crowdsale (_startTime, _endTime, _rate, _wallet) RefundableCrowdsale(_goal*decimalFactor) CappedCrowdsale(_cap*decimalFactor) { state = State.PRESALE; } function createTokenContract() internal returns (MintableToken) { return new Toplancer(); } // low level token purchase function // @notice buyTokens // @param beneficiary The address of the beneficiary // @return the transaction address and send the event as TokenPurchase function buyTokens(address beneficiary) public payable { require(publicSaleCap > 0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); uint256 Bonus = tokens.mul(getTimebasedBonusRate()).div(100); tokens = tokens.add(Bonus); if (state == State.PRESALE) { assert (soldTokenInPresale + tokens <= presaleCap); soldTokenInPresale = soldTokenInPresale.add(tokens); presaleCap=presaleCap.sub(tokens); } else if(state==State.PUBLICSALE){ assert (soldTokenInPublicsale + tokens <= publicSaleCap); soldTokenInPublicsale = soldTokenInPublicsale.add(tokens); publicSaleCap=publicSaleCap.sub(tokens); } if(investedAmountOf[beneficiary] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount); forwardFunds(); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool minContribution = minContribAmount <= msg.value; bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool Publicsale =publicSaleCap !=0; return withinPeriod && minContribution && nonZeroPurchase && Publicsale; } // @return current time function getNow() public constant returns (uint) { return (now); } // Get the time-based bonus rate function getTimebasedBonusRate() internal constant returns (uint256) { uint256 bonusRate = 0; if (state == State.PRESALE) { bonusRate = 100; } else { uint256 nowTime = getNow(); uint256 bonusFirstWeek = startTime + (7 days * 1000); uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000); uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000); uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000); if (nowTime <= bonusFirstWeek) { bonusRate = 30; } else if (nowTime <= bonusSecondWeek) { bonusRate = 30; } else if (nowTime <= bonusThirdWeek) { bonusRate = 15; } else if (nowTime <= bonusFourthWeek) { bonusRate = 15; } } return bonusRate; } //start public sale // @param startTime // @param _endTime function startPublicsale(uint256 _startTime, uint256 _endTime) public onlyOwner { require(state == State.PRESALE && _endTime >= _startTime); state = State.PUBLICSALE; startTime = _startTime; endTime = _endTime; publicSaleCap=publicSaleCap.add(presaleCap); presaleCap=presaleCap.sub(presaleCap); } //it will call when crowdsale unsuccessful if crowdsale completed function finalization() internal { if(goalReached()){ allocation = new Allocation(); token.mint(address(allocation), distributionSupply); distributionSupply=distributionSupply.sub(distributionSupply); } token.finishMinting(); super.finalization(); } //change Starttime // @param startTime function changeStarttime(uint256 _startTime) public onlyOwner { require(_startTime != 0); startTime = _startTime; } //change Edntime // @param _endTime function changeEndtime(uint256 _endTime) public onlyOwner { require(_endTime != 0); endTime = _endTime; } //change token price per 1 ETH // @param _rate function changeRate(uint256 _rate) public onlyOwner { require(_rate != 0); rate = _rate; } //change wallet address // @param wallet address function changeWallet (address _wallet) onlyOwner { wallet = _wallet; } }
vault finalization task, called when owner calls finalize()
function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); }
1,225,865
./full_match/42220/0x2E9f8C5b7d7bC46cB350A3FdCe33538418D114fA/sources/contracts/token/VotingPower.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ XXX_CHANGED: name => _name XXX: added linter disable solhint-disable-next-line not-rely-on-time
function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public override { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(_name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Uni::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Uni::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "Uni::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
16,360,005
./full_match/80001/0xbbfb3a8948216dc467A0Da0CE599375Bc70d023D/sources/contracts/V2.sol
Public function returns the current version of the contract/
function version() external virtual returns (uint256) { return 2; }
9,444,604
./full_match/137/0x088AcC3e5733c12096B64Ac48C04bbe05957Ab30/sources/ERC1155.sol
See {IERC1155-balanceOf}. Requirements: - `account` cannot be the zero address./
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(_exists(id), "ERC1155URIStorage: URI set of nonexistent token"); require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; }
4,751,225
./full_match/1/0xDda46bF18eeb3E06E2F12975A3A184e40581A72f/sources/_prb/math/src/ud2x18/Casting.sol
Casts an UD2x18 number into SD1x18. - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) { uint64 xUint = UD2x18.unwrap(x); pragma solidity >=0.8.13; import { MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { PRBMath_UD2x18_IntoSD1x18_Overflow, PRBMath_UD2x18_IntoUint40_Overflow } from "./Errors.sol"; import { UD2x18 } from "./ValueType.sol"; if (xUint > uint64(uMAX_SD1x18)) { revert PRBMath_UD2x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xUint)); }
3,094,333
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.6; contract Ownable { address public owner; address private nextOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); // modifiers modifier onlyOwner() { require(isOwner(), "caller is not the owner."); _; } modifier onlyNextOwner() { require(isNextOwner(), "current owner must set caller as next owner."); _; } /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor(address owner_) { owner = owner_; emit OwnershipTransferred(address(0), owner); } /** * @dev Initiate ownership transfer by setting nextOwner. */ function transferOwnership(address nextOwner_) external onlyOwner { require(nextOwner_ != address(0), "Next owner is the zero address."); nextOwner = nextOwner_; } /** * @dev Cancel ownership transfer by deleting nextOwner. */ function cancelOwnershipTransfer() external onlyOwner { delete nextOwner; } /** * @dev Accepts ownership transfer by setting owner. */ function acceptOwnership() external onlyNextOwner { delete nextOwner; owner = msg.sender; emit OwnershipTransferred(owner, msg.sender); } /** * @dev Renounce ownership by setting owner to zero address. */ function renounceOwnership() external onlyOwner { owner = address(0); emit OwnershipTransferred(owner, address(0)); } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == owner; } /** * @dev Returns true if the caller is the next owner. */ function isNextOwner() public view returns (bool) { return msg.sender == nextOwner; } } // File contracts/lib/interface/IGovernable.sol interface IGovernable { function changeGovernor(address governor_) external; function isGovernor() external view returns (bool); function governor() external view returns (address); } // File contracts/lib/Governable.sol contract Governable is Ownable, IGovernable { // ============ Mutable Storage ============ // Mirror governance contract. address public override governor; // ============ Modifiers ============ modifier onlyGovernance() { require(isOwner() || isGovernor(), "caller is not governance"); _; } modifier onlyGovernor() { require(isGovernor(), "caller is not governor"); _; } // ============ Constructor ============ constructor(address owner_) Ownable(owner_) {} // ============ Administration ============ function changeGovernor(address governor_) public override onlyGovernance { governor = governor_; } // ============ Utility Functions ============ function isGovernor() public view override returns (bool) { return msg.sender == governor; } } // File contracts/distribution/interface/IDistributionLogic.sol interface IDistributionLogic { function version() external returns (uint256); function distribute(address tributary, uint256 contribution) external; function claim(address claimant) external; function claimable(address claimant) external view returns (uint256); function increaseAwards(address member, uint256 amount) external; } // File contracts/interface/IENS.sol interface IENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeRecord( bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } // File contracts/distribution/interface/IDistributionStorage.sol interface IDistributionStorage { function registered(address claimant) external view returns (uint256); } // File contracts/distribution/DistributionStorage.sol /** * @title DistributionStorage * @author MirrorXYZ */ contract DistributionStorage is IDistributionStorage { // ============ Immutable Storage ============ // The node of the root name (e.g. namehash(mirror.xyz)) bytes32 public immutable rootNode; /** * The address of the public ENS registry. * @dev Dependency-injectable for testing purposes, but otherwise this is the * canonical ENS registry at 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e. */ IENS public immutable ensRegistry; // ============ Mutable Storage ============ // The address for Mirror team and investors. address team; // The address of the governance token that this contract is allowed to mint. address token; // The address that is allowed to distribute. address treasury; // The amount that has been contributed to the treasury. mapping(address => uint256) public contributions; mapping(address => uint256) public awards; // The number of rewards that are created per 1 ETH contribution to the treasury. uint256 contributionsFactor = 1000; // The amount that has been claimed per address. mapping(address => uint256) public claimed; // The block number that an address last claimed mapping(address => uint256) public lastClaimed; // The block number that an address registered mapping(address => uint256) public override registered; // Banned accounts mapping(address => bool) public banned; // The percentage of tokens issued that are taken by the Mirror team. uint256 teamRatio = 40; uint256 public registrationReward = 100 * 1e18; uint256 public registeredMembers; struct DistributionEpoch { uint256 startBlock; uint256 claimablePerBlock; } DistributionEpoch[] public epochs; uint256 numEpochs = 0; constructor(bytes32 rootNode_, address ensRegistry_) { rootNode = rootNode_; ensRegistry = IENS(ensRegistry_); } } // File contracts/lib/upgradable/interface/IBeacon.sol interface IBeacon { /// @notice Logic for this contract. function logic() external view returns (address); /// @notice Emitted when the logic is updated. event Update(address oldLogic, address newLogic); /// @notice Updates logic address. function update(address newLogic) external; } // File contracts/lib/upgradable/BeaconStorage.sol contract BeaconStorage { /// @notice Holds the address of the upgrade beacon address internal immutable beacon; constructor(address beacon_) { beacon = beacon_; } } // File contracts/lib/Pausable.sol interface IPausable { /// @notice Emitted when the pause is triggered by `account`. event Paused(address account); /// @notice Emitted when the pause is lifted by `account`. event Unpaused(address account); function paused() external returns (bool); } contract Pausable is IPausable { bool public override paused; // Modifiers modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } modifier whenPaused() { require(paused, "Pausable: not paused"); _; } /// @notice Initializes the contract in unpaused state. constructor(bool paused_) { paused = paused_; } // ============ Internal Functions ============ function _pause() internal whenNotPaused { paused = true; emit Paused(msg.sender); } function _unpause() internal whenPaused { paused = false; emit Unpaused(msg.sender); } } // File contracts/distribution/DistributionProxy.sol /** * @title DistributionProxy * @author MirrorXYZ */ contract DistributionProxy is BeaconStorage, Governable, DistributionStorage, Pausable { constructor( address beacon_, address owner_, address team_, address token_, bytes32 rootNode_, address ensRegistry_, address treasury_ ) BeaconStorage(beacon_) Governable(owner_) DistributionStorage(rootNode_, ensRegistry_) Pausable(true) { // Initialize the logic, supplying initialization calldata. team = team_; token = token_; treasury = treasury_; } fallback() external payable { address logic = IBeacon(beacon).logic(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), logic, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } receive() external payable {} }
Logged when the owner of a node assigns a new owner to a subnode. Logged when the owner of a node transfers ownership to a new account. Logged when the resolver for a node changes. Logged when the TTL of a node changes Logged when an operator is added or removed.
interface IENS { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); event NewTTL(bytes32 indexed node, uint64 ttl); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeRecord( bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); }
14,560,969
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @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 HtczExchange * @dev Eth <-> HTCZ Exchange supporting contract */ contract HtczExchange is Ownable { using SafeMath for uint256; // ** Events ** // Deposit received -> sent to exchange to HTCZ token event Deposit(address indexed sender, uint eth_amount, uint htcz_amount); // HTCZ token was sent in exchange for Ether event Exchanged(address indexed receiver, uint indexed htcz_tx, uint htcz_amount, uint eth_amount); // HTCZ Reserve amount changed event ReserveChanged(uint indexed htcz_tx, uint old_htcz_amount, uint new_htcz_amount); // Operator changed event OperatorChanged(address indexed new_operator); // ** Contract state ** // HTCZ token (address is in ETZ network) address public htcz_token; // Source of wallet for reserve (address is in ETZ network) address public htcz_cold_wallet; // HTCZ wallet used to exchange (address is in ETZ network) address public htcz_exchange_wallet; // Operator account of the exchange address public operator; // HTCZ amount used for exchange, should not exceed htcz_reserve uint public htcz_exchanged_amount; // HTCZ reserve for exchange uint public htcz_reserve; // ETH -> HTCZ exchange rate uint public exchange_rate; // gas spending on transfer function uint constant GAS_FOR_TRANSFER = 49483; // ** Modifiers ** // Throws if called by any account other than the operator. modifier onlyOperator() { require(msg.sender == operator); _; } constructor( address _htcz_token, address _htcz_cold_wallet, address _htcz_exchange_wallet, address _operator, uint _exchange_rate ) public { require(_htcz_token != address(0)); require(_htcz_cold_wallet != address(0)); require(_htcz_exchange_wallet != address(0)); require(_operator != address(0)); require(_exchange_rate>0); htcz_token = _htcz_token; htcz_cold_wallet = _htcz_cold_wallet; htcz_exchange_wallet = _htcz_exchange_wallet; exchange_rate = _exchange_rate; operator = _operator; } /** * @dev Accepts Ether. * Throws is token balance is not available to issue HTCZ tokens */ function() external payable { require( msg.value > 0 ); uint eth_amount = msg.value; uint htcz_amount = eth_amount.mul(exchange_rate); htcz_exchanged_amount = htcz_exchanged_amount.add(htcz_amount); require( htcz_reserve >= htcz_exchanged_amount ); emit Deposit(msg.sender, eth_amount, htcz_amount); } /** * @dev Transfers ether by operator command in exchange to HTCZ tokens * Calculates gas amount, gasprice and substracts that from the transfered amount. * Note, that smart contracts are not allowed as the receiver. */ function change(address _receiver, uint _htcz_tx, uint _htcz_amount) external onlyOperator { require(_receiver != address(0)); uint gas_value = GAS_FOR_TRANSFER.mul(tx.gasprice); uint eth_amount = _htcz_amount / exchange_rate; require(eth_amount > gas_value); eth_amount = eth_amount.sub(gas_value); require(htcz_exchanged_amount >= _htcz_amount ); htcz_exchanged_amount = htcz_exchanged_amount.sub(_htcz_amount); msg.sender.transfer(gas_value); _receiver.transfer(eth_amount); emit Exchanged(_receiver, _htcz_tx, _htcz_amount, eth_amount); } /** * @dev Increase HTCZ reserve */ function increaseReserve(uint _htcz_tx, uint _amount) external onlyOperator { uint old_htcz_reserve = htcz_reserve; uint new_htcz_reserve = old_htcz_reserve.add(_amount); require( new_htcz_reserve > old_htcz_reserve); htcz_reserve = new_htcz_reserve; emit ReserveChanged(_htcz_tx, old_htcz_reserve, new_htcz_reserve); } /** * @dev Decrease HTCZ reserve */ function decreaseReserve(uint _htcz_tx, uint _amount) external onlyOperator { uint old_htcz_reserve = htcz_reserve; uint new_htcz_reserve = old_htcz_reserve.sub(_amount); require( new_htcz_reserve < old_htcz_reserve); require( new_htcz_reserve >= htcz_exchanged_amount ); htcz_reserve = new_htcz_reserve; emit ReserveChanged(_htcz_tx, old_htcz_reserve, new_htcz_reserve); } /** * @dev Set other operator ( 0 allowed ) */ function changeOperator(address _operator) external onlyOwner { require(_operator != operator); operator = _operator; emit OperatorChanged(_operator); } }
Set other operator ( 0 allowed )/
function changeOperator(address _operator) external onlyOwner { require(_operator != operator); operator = _operator; emit OperatorChanged(_operator); }
2,535,793
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Linked to SYN Marker Interface * * @notice Marks smart contracts which are linked to SyndicateERC20 token instance upon construction, * all these smart contracts share a common syn() address getter * * @notice Implementing smart contracts MUST verify that they get linked to real SyndicateERC20 instance * and that syn() getter returns this very same instance address * */ interface ILinkedToSYN { /** * @notice Getter for a verified SyndicateERC20 instance address * * @return SyndicateERC20 token instance address smart contract is linked to */ function syn() external view returns (address); }
Linked to SYN Marker Interface Marks smart contracts which are linked to SyndicateERC20 token instance upon construction, all these smart contracts share a common syn() address getter Implementing smart contracts MUST verify that they get linked to real SyndicateERC20 instance and that syn() getter returns this very same instance address/
interface ILinkedToSYN { function syn() external view returns (address); pragma solidity 0.8.1; }
12,827,228
./full_match/69/0xa46d600e30D9C718F44F675d85f550eb843601e9/sources/contracts/rubiconPools/BathPair.sol
this throws on a zero value ofliquidity if the asset/quote is overweighted: underlyingBalance / (Proportion of quote allocated to pair) underlyingQuote balance bid at maxSize return dynamic order size return dynamic order size
function getMaxOrderSize(address asset, address bathTokenAddress) public view returns (uint256 maxOrderSize) { require(asset == underlyingAsset || asset == underlyingQuote); int128 shapeCoef = ABDKMath64x64.div(shapeCoefNum, 1000); uint256 underlyingBalance = IERC20(asset).balanceOf(bathTokenAddress); require( underlyingBalance > 0, "no bathToken liquidity to calculate max orderSize permissable" ); if (asset == underlyingAsset) { int128 ratio = ABDKMath64x64.divu( underlyingBalance, IERC20(underlyingQuote).balanceOf(bathQuoteAddress) ); if (ABDKMath64x64.mul(ratio, getMidpointPrice()) > (2**64)) { return maxOrderSizeBPS.mul(underlyingBalance).div(10000); uint256 maxSize = maxOrderSizeBPS.mul(underlyingBalance).div( 10000 ); int128 shapeFactor = ABDKMath64x64.exp( ABDKMath64x64.mul( shapeCoef, ABDKMath64x64.inv( ABDKMath64x64.mul(ratio, getMidpointPrice()) ) ) ); uint256 dynamicSize = ABDKMath64x64.mulu(shapeFactor, maxSize); return dynamicSize; } int128 ratio = ABDKMath64x64.divu( underlyingBalance, IERC20(underlyingAsset).balanceOf(bathAssetAddress) ); if (ABDKMath64x64.div(ratio, getMidpointPrice()) > (2**64)) { return maxOrderSizeBPS.mul(underlyingBalance).div(10000); uint256 maxSize = maxOrderSizeBPS.mul(underlyingBalance).div( 10000 ); int128 shapeFactor = ABDKMath64x64.exp( ABDKMath64x64.mul( shapeCoef, ABDKMath64x64.inv( ABDKMath64x64.div(ratio, getMidpointPrice()) ) ) ); uint256 dynamicSize = ABDKMath64x64.mulu(shapeFactor, maxSize); return dynamicSize; } } }
13,239,144
./partial_match/42/0x9b96b64Abf39A56f80c12821Ee7bCdE0a98d7cD4/sources/ChainAssigner.sol
todo: make _sysMap a generic _metadata bytes array
function assignStarSystem(uint _sysId, address _recipient, uint _sysMap) external { require(msg.sender == address(assigner), "sender should be chain assigner"); bytes4 methodSelector = SidechainAMBMediator(0).assignStarSystem.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _sysId, _recipient, _sysMap);
9,042,068
pragma solidity 0.4.15; /// @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 { // EVENTS event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // PUBLIC FUNCTIONS /// @dev The Ownable constructor sets the original `owner` of the contract to the sender account. function Ownable() { owner = msg.sender; } /// @dev Allows the current owner to transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } // MODIFIERS /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } // FIELDS address public owner; } contract DaoOwnable is Ownable{ address public dao = address(0); event DaoOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the dao. */ modifier onlyDao() { require(msg.sender == dao); _; } modifier onlyDaoOrOwner() { require(msg.sender == dao || msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newDao. * @param newDao The address to transfer ownership to. */ function transferDao(address newDao) onlyOwner { require(newDao != address(0)); dao = newDao; DaoOwnershipTransferred(owner, newDao); } } contract DSPTypeAware { enum DSPType { Gate, Direct } } contract DSPRegistry is DSPTypeAware{ // This is the function that actually insert a record. function register(address key, DSPType dspType, bytes32[5] url, address recordOwner); // Updates the values of the given record. function updateUrl(address key, bytes32[5] url, address sender); function applyKarmaDiff(address key, uint256[2] diff); // Unregister a given record function unregister(address key, address sender); // Transfer ownership of a given record. function transfer(address key, address newOwner, address sender); function getOwner(address key) constant returns(address); // Tells whether a given key is registered. function isRegistered(address key) constant returns(bool); function getDSP(address key) constant returns(address dspAddress, DSPType dspType, bytes32[5] url, uint256[2] karma, address recordOwner); //@dev Get list of all registered dsp //@return Returns array of addresses registered as DSP with register times function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) ; function kill(); } contract DSPRegistryImpl is DSPRegistry, DaoOwnable { uint public creationTime = now; // This struct keeps all data for a DSP. struct DSP { // Keeps the address of this record creator. address owner; // Keeps the time when this record was created. uint time; // Keeps the index of the keys array for fast lookup uint keysIndex; // DSP Address address dspAddress; DSPType dspType; bytes32[5] url; uint256[2] karma; } // This mapping keeps the records of this Registry. mapping(address => DSP) records; // Keeps the total numbers of records in this Registry. uint public numRecords; // Keeps a list of all keys to interate the records. address[] public keys; // This is the function that actually insert a record. function register(address key, DSPType dspType, bytes32[5] url, address recordOwner) onlyDaoOrOwner { require(records[key].time == 0); records[key].time = now; records[key].owner = recordOwner; records[key].keysIndex = keys.length; records[key].dspAddress = key; records[key].dspType = dspType; records[key].url = url; keys.length++; keys[keys.length - 1] = key; numRecords++; } // Updates the values of the given record. function updateUrl(address key, bytes32[5] url, address sender) onlyDaoOrOwner { // Only the owner can update his record. require(records[key].owner == sender); records[key].url = url; } function applyKarmaDiff(address key, uint256[2] diff) onlyDaoOrOwner{ DSP storage dsp = records[key]; dsp.karma[0] += diff[0]; dsp.karma[1] += diff[1]; } // Unregister a given record function unregister(address key, address sender) onlyDaoOrOwner { require(records[key].owner == sender); uint keysIndex = records[key].keysIndex; delete records[key]; numRecords--; keys[keysIndex] = keys[keys.length - 1]; records[keys[keysIndex]].keysIndex = keysIndex; keys.length--; } // Transfer ownership of a given record. function transfer(address key, address newOwner, address sender) onlyDaoOrOwner { require(records[key].owner == sender); records[key].owner = newOwner; } // Tells whether a given key is registered. function isRegistered(address key) constant returns(bool) { return records[key].time != 0; } function getDSP(address key) constant returns(address dspAddress, DSPType dspType, bytes32[5] url, uint256[2] karma, address recordOwner) { DSP storage record = records[key]; dspAddress = record.dspAddress; url = record.url; dspType = record.dspType; karma = record.karma; recordOwner = record.owner; } // Returns the owner of the given record. The owner could also be get // by using the function getDSP but in that case all record attributes // are returned. function getOwner(address key) constant returns(address) { return records[key].owner; } // Returns the registration time of the given record. The time could also // be get by using the function getDSP but in that case all record attributes // are returned. function getTime(address key) constant returns(uint) { return records[key].time; } //@dev Get list of all registered dsp //@return Returns array of addresses registered as DSP with register times function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) { addresses = new address[](numRecords); dspTypes = new DSPType[](numRecords); urls = new bytes32[5][](numRecords); karmas = new uint256[2][](numRecords); recordOwners = new address[](numRecords); uint i; for(i = 0; i < numRecords; i++) { DSP storage dsp = records[keys[i]]; addresses[i] = dsp.dspAddress; dspTypes[i] = dsp.dspType; urls[i] = dsp.url; karmas[i] = dsp.karma; recordOwners[i] = dsp.owner; } } function kill() onlyOwner { selfdestruct(owner); } }
Get list of all registered dspreturn Returns array of addresses registered as DSP with register times
function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) { addresses = new address[](numRecords); dspTypes = new DSPType[](numRecords); urls = new bytes32[5][](numRecords); karmas = new uint256[2][](numRecords); recordOwners = new address[](numRecords); uint i; for(i = 0; i < numRecords; i++) { DSP storage dsp = records[keys[i]]; addresses[i] = dsp.dspAddress; dspTypes[i] = dsp.dspType; urls[i] = dsp.url; karmas[i] = dsp.karma; recordOwners[i] = dsp.owner; } }
12,750,983
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/Sweepable.sol"; import "./assets/erc1155/interfaces/ISuper1155.sol"; import "./assets/erc721/interfaces/ISuper721.sol"; import "./interfaces/IStaker.sol"; import "./interfaces/IMintShop.sol"; import "./libraries/merkle/SuperMerkleAccess.sol"; import "./libraries/DFStorage.sol"; /** @title A Shop contract for selling NFTs via direct minting through particular pools with specific participation requirements. @author Tim Clancy @author Qazawat Zirak @author Rostislav Khlebnikov @author Nikita Elunin This launchpad contract sells new items by minting them into existence. It cannot be used to sell items that already exist. */ contract MintShop1155 is Sweepable, ReentrancyGuard, IMintShop, SuperMerkleAccess { using SafeERC20 for IERC20; /// The public identifier for the right to set the payment receiver. bytes32 public constant SET_PAYMENT_RECEIVER = keccak256("SET_PAYMENT_RECEIVER"); /// The public identifier for the right to lock the payment receiver. bytes32 public constant LOCK_PAYMENT_RECEIVER = keccak256("LOCK_PAYMENT_RECEIVER"); /// The public identifier for the right to update the global purchase limit. bytes32 public constant UPDATE_GLOBAL_LIMIT = keccak256("UPDATE_GLOBAL_LIMIT"); /// The public identifier for the right to lock the global purchase limit. bytes32 public constant LOCK_GLOBAL_LIMIT = keccak256("LOCK_GLOBAL_LIMIT"); /// The public identifier for the right to manage whitelists. bytes32 public constant WHITELIST = keccak256("WHITELIST"); /// The public identifier for the right to manage item pools. bytes32 public constant POOL = keccak256("POOL"); /// The public identifier for the right to set new items. bytes32 public constant SET_ITEMS = keccak256("SET_ITEMS"); /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(type(uint128).max) << 128; /// The maximum amount that can be minted through all collections. uint256 public immutable maxAllocation; /// The item collection contract that minted items are sold from. ISuper1155[] public items; /** The address where the payment from each item buyer is sent. Care must be taken that this address can actually take receipt of the Ether or ERC-20 earnings. */ address public paymentReceiver; /** A flag determining whether or not the `paymentReceiver` may be updated using the `updatePaymentReceiver` function. */ bool public paymentReceiverLocked; /** A limit on the number of items that a particular address may purchase across any number of pools in this shop. */ uint256 public globalPurchaseLimit; /** A flag determining whether or not the `globalPurchaseLimit` may be updated using the `updateGlobalPurchaseLimit` function. */ bool public globalPurchaseLimitLocked; /// A mapping of addresses to the number of items each has purchased globally. mapping (address => uint256) public globalPurchaseCounts; /// The next available ID to be assumed by the next pool added. uint256 public nextPoolId; /// A mapping of pool IDs to pools. mapping (uint256 => Pool) public pools; /** This mapping relates each item group ID to the next item ID within that group which should be issued, minus one. */ mapping (bytes32 => uint256) public nextItemIssues; /** This struct tracks information about a single item pool in the Shop. @param currentPoolVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param config configuration struct PoolInput. @param purchaseCounts A mapping of addresses to the number of items each has purchased from this pool. @param itemCaps A mapping of item group IDs to the maximum number this pool is allowed to mint. @param itemMinted A mapping of item group IDs to the number this pool has currently minted. @param itemPrices A mapping of item group IDs to a mapping of available Price assets available to purchase with. @param itemGroups An array of all item groups currently present in this pool. */ struct Pool { uint256 currentPoolVersion; DFStorage.PoolInput config; mapping (address => uint256) purchaseCounts; mapping (bytes32 => uint256) itemCaps; mapping (bytes32 => uint256) itemMinted; mapping (bytes32 => uint256) itemPricesLength; mapping (bytes32 => mapping (uint256 => DFStorage.Price)) itemPrices; uint256[] itemGroups; Whitelist[] whiteLists; } /** This struct tracks information about a single whitelist known to this shop. Whitelists may be shared across multiple different item pools. @param id Id of the whiteList. @param minted Mapping, which is needed to keep track of whether a user bought an nft or not. */ struct Whitelist { uint256 id; mapping (address => uint256) minted; } /** This struct tracks information about a single item being sold in a pool. @param groupId The group ID of the specific NFT in the collection being sold by a pool. @param cap The maximum number of items that this shop may mint for the specified `groupId`. @param minted The number of items that a pool has currently minted of the specified `groupId`. @param prices The `Price` options that may be used to purchase this item from its pool. A buyer may fulfill the purchase with any price option. */ struct PoolItem { uint256 groupId; uint256 cap; uint256 minted; DFStorage.Price[] prices; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. @param config configuration struct PoolInput @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. */ struct PoolOutput { DFStorage.PoolInput config; string itemMetadataUri; PoolItem[] items; } // /** // This struct contains the information gleaned from the `getPool` and // `getPools` functions; it represents a single pool's data. It also includes // additional information relevant to a user's address lookup. // @param purchaseCount The amount of items purchased from this pool by the // specified address. // @param config configuration struct PoolInput. // @param whitelistStatus Whether or not the specified address is whitelisted // for this pool. // @param itemMetadataUri The metadata URI of the item collection being sold by // this launchpad. // @param items An array of PoolItems representing each item for sale in the // pool. // */ // struct PoolAddressOutput { // uint256 purchaseCount; // DFStorage.PoolInput config; // bool whitelistStatus; // string itemMetadataUri; // PoolItem[] items; // } /** An event to track an update to this shop's `paymentReceiver`. @param updater The calling address which updated the payment receiver. @param oldPaymentReceiver The address of the old payment receiver. @param newPaymentReceiver The address of the new payment receiver. */ event PaymentReceiverUpdated(address indexed updater, address indexed oldPaymentReceiver, address indexed newPaymentReceiver); /** An event to track future changes to `paymentReceiver` being locked. @param locker The calling address which locked down the payment receiver. */ event PaymentReceiverLocked(address indexed locker); /** An event to track an update to this shop's `globalPurchaseLimit`. @param updater The calling address which updated the purchase limit. @param oldPurchaseLimit The value of the old purchase limit. @param newPurchaseLimit The value of the new purchase limit. */ event GlobalPurchaseLimitUpdated(address indexed updater, uint256 indexed oldPurchaseLimit, uint256 indexed newPurchaseLimit); /** An event to track future changes to `globalPurchaseLimit` being locked. @param locker The calling address which locked down the purchase limit. */ event GlobalPurchaseLimitLocked(address indexed locker); /** An event to track a specific whitelist being updated. When emitted this event indicates that a specific whitelist has had its settings completely replaced. @param updater The calling address which updated this whitelist. @param whitelistId The ID of the whitelist being updated. @param timestamp Timestamp of whiteList update. */ event WhitelistUpdated(address indexed updater, uint256 whitelistId, uint256 timestamp); /** An event to track an item pool's data being updated. When emitted this event indicates that a specific item pool's settings have been completely replaced. @param updater The calling address which updated this pool. @param poolId The ID of the pool being updated. @param pool The input data used to update the pool. @param groupIds The groupIds that are now on sale in the item pool. @param caps The caps, keyed to `groupIds`, of the maximum that each groupId may mint up to. @param prices The prices, keyed to `groupIds`, of the arrays for `Price` objects that each item group may be able be bought with. */ event PoolUpdated(address indexed updater, uint256 poolId, DFStorage.PoolInput indexed pool, uint256[] groupIds, uint256[] caps, DFStorage.Price[][] indexed prices); /** An event to track the purchase of items from an item pool. @param buyer The address that bought the item from an item pool. @param poolId The ID of the item pool that the buyer bought from. @param itemIds The array of item IDs that were purchased by the user. @param amounts The keyed array of each amount of item purchased by `buyer`. */ event ItemPurchased(address indexed buyer, uint256 poolId, uint256[] indexed itemIds, uint256[] amounts); /** Construct a new shop which can mint items upon purchase from various pools. @param _paymentReceiver The address where shop earnings are sent. @param _globalPurchaseLimit A global limit on the number of items that a single address may purchase across all item pools in the shop. */ constructor(address _owner, address _paymentReceiver, uint256 _globalPurchaseLimit, uint256 _maxAllocation) { if (_owner != owner()) { transferOwnership(_owner); } // Initialization. paymentReceiver = _paymentReceiver; globalPurchaseLimit = _globalPurchaseLimit; maxAllocation = _maxAllocation; } /** Allow the shop owner or an approved manager to update the payment receiver address if it has not been locked. @param _newPaymentReceiver The address of the new payment receiver. */ function updatePaymentReceiver(address _newPaymentReceiver) external hasValidPermit(UNIVERSAL, SET_PAYMENT_RECEIVER) { require(!paymentReceiverLocked, "XXX" ); emit PaymentReceiverUpdated(_msgSender(), paymentReceiver, _newPaymentReceiver); // address oldPaymentReceiver = paymentReceiver; paymentReceiver = _newPaymentReceiver; } /** Allow the shop owner or an approved manager to set the array of items known to this shop. @param _items The array of Super1155 addresses. */ function setItems(ISuper1155[] calldata _items) external hasValidPermit(UNIVERSAL, SET_ITEMS) { items = _items; } /** Allow the shop owner or an approved manager to lock the payment receiver address against any future changes. */ function lockPaymentReceiver() external hasValidPermit(UNIVERSAL, LOCK_PAYMENT_RECEIVER) { paymentReceiverLocked = true; emit PaymentReceiverLocked(_msgSender()); } /** Allow the shop owner or an approved manager to update the global purchase limit if it has not been locked. @param _newGlobalPurchaseLimit The value of the new global purchase limit. */ function updateGlobalPurchaseLimit(uint256 _newGlobalPurchaseLimit) external hasValidPermit(UNIVERSAL, UPDATE_GLOBAL_LIMIT) { require(!globalPurchaseLimitLocked, "0x0A"); emit GlobalPurchaseLimitUpdated(_msgSender(), globalPurchaseLimit, _newGlobalPurchaseLimit); globalPurchaseLimit = _newGlobalPurchaseLimit; } /** Allow the shop owner or an approved manager to lock the global purchase limit against any future changes. */ function lockGlobalPurchaseLimit() external hasValidPermit(UNIVERSAL, LOCK_GLOBAL_LIMIT) { globalPurchaseLimitLocked = true; emit GlobalPurchaseLimitLocked(_msgSender()); } /** Adds new whiteList restriction for the pool by `_poolId`. @param _poolId id of the pool, where new white list is added. @param whitelist struct for creating a new whitelist. */ function addWhiteList(uint256 _poolId, DFStorage.WhiteListCreate[] calldata whitelist) external hasValidPermit(UNIVERSAL, WHITELIST) { for (uint256 i = 0; i < whitelist.length; i++) { super.setAccessRound(whitelist[i]._accesslistId, whitelist[i]._merkleRoot, whitelist[i]._startTime, whitelist[i]._endTime, whitelist[i]._price, whitelist[i]._token); pools[_poolId].whiteLists.push(); uint256 newIndex = pools[_poolId].whiteLists.length - 1; pools[_poolId].whiteLists[newIndex].id = whitelist[i]._accesslistId; emit WhitelistUpdated(_msgSender(), whitelist[i]._accesslistId, block.timestamp); } } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this shop uses. @param _ids An array of pool IDs to retrieve information about. */ function getPools(uint256[] calldata _ids, uint256 _itemIndex) external view returns (PoolOutput[] memory) { PoolOutput[] memory poolOutputs = new PoolOutput[](_ids.length); for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[id].itemGroups.length); for (uint256 j = 0; j < pools[id].itemGroups.length; j++) { uint256 itemGroupId = pools[id].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[id].config.collection, pools[id].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. DFStorage.Price[] memory itemPrices = new DFStorage.Price[](pools[id].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[id].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[id].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[id].itemCaps[itemKey], minted: pools[id].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. poolOutputs[i] = PoolOutput({ config: pools[id].config, itemMetadataUri: items[_itemIndex].metadataUri(), items: poolItems }); } // Return the pools. return poolOutputs; } /** A function which allows the caller to retrieve the number of items specific addresses have purchased from specific pools. @param _ids The IDs of the pools to check for addresses in `purchasers`. @param _purchasers The addresses to check the purchase counts for. */ function getPurchaseCounts(address[] calldata _purchasers, uint256[] calldata _ids) external view returns (uint256[][] memory) { uint256[][] memory purchaseCounts = new uint256[][](_purchasers.length); for (uint256 i = 0; i < _purchasers.length; i++) { purchaseCounts[i] = new uint256[](_ids.length); for (uint256 j = 0; j < _ids.length; j++) { uint256 id = _ids[j]; address purchaser = _purchasers[i]; purchaseCounts[i][j] = pools[id].purchaseCounts[purchaser]; } } return purchaseCounts; } // /** // A function which allows the caller to retrieve information about specific // pools, the items for sale within, and the collection this launchpad uses. // A provided address differentiates this function from `getPools`; the added // address enables this function to retrieve pool data as well as whitelisting // and purchase count details for the provided address. // @param _ids An array of pool IDs to retrieve information about. // */ // function getPoolsWithAddress(uint256[] calldata _ids) // external view returns (PoolAddressOutput[] memory) { // PoolAddressOutput[] memory poolOutputs = // new PoolAddressOutput[](_ids.length); // for (uint256 i = 0; i < _ids.length; i++) { // uint256 id = _ids[i]; // // Process output for each pool. // PoolItem[] memory poolItems = new PoolItem[](pools[id].itemGroups.length); // for (uint256 j = 0; j < pools[id].itemGroups.length; j++) { // uint256 itemGroupId = pools[id].itemGroups[j]; // bytes32 itemKey = keccak256(abi.encodePacked(pools[id].config.collection, // pools[id].currentPoolVersion, itemGroupId)); // // Parse each price the item is sold at. // DFStorage.Price[] memory itemPrices = // new DFStorage.Price[](pools[id].itemPricesLength[itemKey]); // for (uint256 k = 0; k < pools[id].itemPricesLength[itemKey]; k++) { // itemPrices[k] = pools[id].itemPrices[itemKey][k]; // } // // Track the item. // poolItems[j] = PoolItem({ // groupId: itemGroupId, // cap: pools[id].itemCaps[itemKey], // minted: pools[id].itemMinted[itemKey], // prices: itemPrices // }); // } // // Track the pool. // // uint256 whitelistId = pools[id].config.requirement.whitelistId; // // bytes32 addressKey = keccak256( // // abi.encode(whitelists[whitelistId].currentWhitelistVersion, _address)); // // poolOutputs[i] = PoolAddressOutput({ // // config: pools[id].config, // // itemMetadataUri: items[_itemIndex].metadataUri(), // // items: poolItems, // // purchaseCount: pools[id].purchaseCounts[_address], // // whitelistStatus: whitelists[whitelistId].addresses[addressKey] // // }); // } // // Return the pools. // return poolOutputs; // } /** Allow the owner of the shop or an approved manager to add a new pool of items that users may purchase. @param _pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function addPool(DFStorage.PoolInput calldata _pool, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] calldata _prices) external hasValidPermit(UNIVERSAL, POOL) { updatePool(nextPoolId, _pool, _groupIds, _issueNumberOffsets, _caps, _prices); // Increment the ID which will be used by the next pool added. nextPoolId += 1; } /** Allow the owner of the shop or an approved manager to update an existing pool of items. @param _id The ID of the pool to update. @param _config The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function updatePool(uint256 _id, DFStorage.PoolInput calldata _config, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices) public hasValidPermit(UNIVERSAL, POOL) { require(_id <= nextPoolId && _config.endTime >= _config.startTime && _groupIds.length > 0, "0x1A"); require(_groupIds.length == _caps.length && _caps.length == _prices.length && _issueNumberOffsets.length == _prices.length, "0x4A"); // Immediately store some given information about this pool. Pool storage pool = pools[_id]; pool.config = _config; pool.itemGroups = _groupIds; pool.currentPoolVersion = pools[_id].currentPoolVersion + 1; // Delegate work to a helper function to avoid stack-too-deep errors. _updatePoolHelper(_id, _groupIds, _issueNumberOffsets, _caps, _prices); // Emit an event indicating that a pool has been updated. emit PoolUpdated(_msgSender(), _id, _config, _groupIds, _caps, _prices); } /** A private helper function for `updatePool` to prevent it from running too deep into the stack. This function will store the amount of each item group that this pool may mint. @param _id The ID of the pool to update. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function _updatePoolHelper(uint256 _id, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices) private { for (uint256 i = 0; i < _groupIds.length; i++) { require(_caps[i] > 0, "0x5A"); bytes32 itemKey = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupIds[i])); pools[_id].itemCaps[itemKey] = _caps[i]; // Pre-seed the next item issue IDs given the pool offsets. // We generate a key from collection address and groupId. bytes32 key = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupIds[i])); nextItemIssues[key] = _issueNumberOffsets[i]; // Store future purchase information for the item group. for (uint256 j = 0; j < _prices[i].length; j++) { pools[_id].itemPrices[itemKey][j] = _prices[i][j]; } pools[_id].itemPricesLength[itemKey] = _prices[i].length; } } function updatePoolConfig(uint256 _id, DFStorage.PoolInput calldata _config) external hasValidPermit(UNIVERSAL, POOL){ require(_id <= nextPoolId && _config.endTime >= _config.startTime, "0x1A"); pools[_id].config = _config; } /** Allow a buyer to purchase an item from a pool. @param _id The ID of the particular item pool that the user would like to purchase from. @param _groupId The item group ID that the user would like to purchase. @param _assetIndex The selection of supported payment asset `Price` that the buyer would like to make a purchase with. @param _amount The amount of item that the user would like to purchase. */ function mintFromPool(uint256 _id, uint256 _groupId, uint256 _assetIndex, uint256 _amount, uint256 _itemIndex, DFStorage.WhiteListInput calldata _whiteList) external nonReentrant payable { require(_amount > 0, "0x0B"); require(_id < nextPoolId && pools[_id].config.singlePurchaseLimit >= _amount, "0x1B"); bool whiteListed; if (pools[_id].whiteLists.length != 0) { bytes32 root = keccak256(abi.encodePacked(_whiteList.index, _msgSender(), _whiteList.allowance)); whiteListed = super.verify(_whiteList.whiteListId, _whiteList.index, root, _whiteList.merkleProof) && root == _whiteList.node && pools[_id].whiteLists[_whiteList.whiteListId].minted[_msgSender()] + _amount <= _whiteList.allowance; } require(block.timestamp >= pools[_id].config.startTime && block.timestamp <= pools[_id].config.endTime || whiteListed, "0x4B"); bytes32 itemKey = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupId)); require(_assetIndex < pools[_id].itemPricesLength[itemKey], "0x3B"); // Verify that the pool is running its sale. // Verify that the pool is respecting per-address global purchase limits. uint256 userGlobalPurchaseAmount = _amount + globalPurchaseCounts[_msgSender()]; if (globalPurchaseLimit != 0) { require(userGlobalPurchaseAmount <= globalPurchaseLimit, "0x5B"); // Verify that the pool is respecting per-address pool purchase limits. } uint256 userPoolPurchaseAmount = _amount + pools[_id].purchaseCounts[_msgSender()]; // Verify that the pool is not depleted by the user's purchase. uint256 newCirculatingTotal = pools[_id].itemMinted[itemKey] + _amount; require(newCirculatingTotal <= pools[_id].itemCaps[itemKey], "0x7B"); { uint256 result; for (uint256 i = 0; i < nextPoolId; i++) { for (uint256 j = 0; j < pools[i].itemGroups.length; j++) { result += pools[i].itemMinted[itemKey]; } } require(maxAllocation >= result + _amount, "0x0D"); } require(checkRequirments(_id), "0x8B"); sellingHelper(_id, itemKey, _assetIndex, _amount, whiteListed, _whiteList.whiteListId); mintingHelper(_itemIndex, _groupId, _id, itemKey, _amount, newCirculatingTotal, userPoolPurchaseAmount, userGlobalPurchaseAmount); // Emit an event indicating a successful purchase. } function remainder(DFStorage.WhiteListInput calldata _whiteList, uint256 _id, address _user) public view returns (uint256) { return (pools[_id].whiteLists[_whiteList.whiteListId].minted[_user] < _whiteList.allowance) ? _whiteList.allowance - pools[_id].whiteLists[_whiteList.whiteListId].minted[_user] : 0; } function isEligible(DFStorage.WhiteListInput calldata _whiteList, uint256 _id) public view returns (bool) { return (super.verify(_whiteList.whiteListId, _whiteList.index, keccak256(abi.encodePacked(_whiteList.index, _msgSender(), _whiteList.allowance)), _whiteList.merkleProof)) && pools[_id].whiteLists[_whiteList.whiteListId].minted[_msgSender()] < _whiteList.allowance || (block.timestamp >= pools[_id].config.startTime && block.timestamp <= pools[_id].config.endTime); } function sellingHelper(uint256 _id, bytes32 itemKey, uint256 _assetIndex, uint256 _amount, bool _whiteListPrice, uint256 _accesListId) private { // Process payment for the user, checking to sell for Staker points. if (_whiteListPrice) { SuperMerkleAccess.AccessList storage accessList = SuperMerkleAccess.accessRoots[_accesListId]; uint256 price = accessList.price * _amount; if (accessList.token == address(0)) { require(msg.value >= price, "0x9B"); (bool success, ) = payable(paymentReceiver).call{ value: msg.value }(""); require(success, "0x0C"); pools[_id].whiteLists[_accesListId].minted[_msgSender()] += _amount; } else { require(IERC20(accessList.token).balanceOf(_msgSender()) >= price, "0x1C"); IERC20(accessList.token).safeTransferFrom(_msgSender(), paymentReceiver, price); pools[_id].whiteLists[_accesListId].minted[_msgSender()] += _amount; } } else { DFStorage.Price storage sellingPair = pools[_id].itemPrices[itemKey][_assetIndex]; if (sellingPair.assetType == DFStorage.AssetType.Point) { IStaker(sellingPair.asset).spendPoints(_msgSender(), sellingPair.price * _amount); // Process payment for the user with a check to sell for Ether. } else if (sellingPair.assetType == DFStorage.AssetType.Ether) { uint256 etherPrice = sellingPair.price * _amount; require(msg.value >= etherPrice, "0x9B"); (bool success, ) = payable(paymentReceiver).call{ value: msg.value }(""); require(success, "0x0C"); // Process payment for the user with a check to sell for an ERC-20 token. } else if (sellingPair.assetType == DFStorage.AssetType.Token) { uint256 tokenPrice = sellingPair.price * _amount; require(IERC20(sellingPair.asset).balanceOf(_msgSender()) >= tokenPrice, "0x1C"); IERC20(sellingPair.asset).safeTransferFrom(_msgSender(), paymentReceiver, tokenPrice); // Otherwise, error out because the payment type is unrecognized. } else { revert("0x0"); } } } /** * Private function to avoid a stack-too-deep error. */ function checkRequirments(uint256 _id) private view returns (bool) { // Verify that the user meets any requirements gating participation in this // pool. Verify that any possible ERC-20 requirements are met. uint256 amount; DFStorage.PoolRequirement memory poolRequirement = pools[_id].config.requirement; if (poolRequirement.requiredType == DFStorage.AccessType.TokenRequired) { // bytes data for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += IERC20(poolRequirement.requiredAsset[i]).balanceOf(_msgSender()); } return amount >= poolRequirement.requiredAmount; // Verify that any possible Staker point threshold requirements are met. } else if (poolRequirement.requiredType == DFStorage.AccessType.PointRequired) { // IStaker requiredStaker = IStaker(poolRequirement.requiredAsset[0]); return IStaker(poolRequirement.requiredAsset[0]).getAvailablePoints(_msgSender()) >= poolRequirement.requiredAmount; } // Verify that any possible ERC-1155 ownership requirements are met. if (poolRequirement.requiredId.length == 0) { if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += ISuper1155(poolRequirement.requiredAsset[i]).totalBalances(_msgSender()); } return amount >= poolRequirement.requiredAmount; } else if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired721) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += ISuper721(poolRequirement.requiredAsset[i]).balanceOf(_msgSender()); } // IERC721 requiredItem = IERC721(poolRequirement.requiredAsset[0]); return amount >= poolRequirement.requiredAmount; } } else { if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired) { // ISuper1155 requiredItem = ISuper1155(poolRequirement.requiredAsset[0]); for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { for (uint256 j = 0; j < poolRequirement.requiredAsset.length; j++) { amount += ISuper1155(poolRequirement.requiredAsset[i]).balanceOf(_msgSender(), poolRequirement.requiredId[j]); } } return amount >= poolRequirement.requiredAmount; } else if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired721) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { for (uint256 j = 0; j < poolRequirement.requiredAsset.length; j++) { amount += ISuper721(poolRequirement.requiredAsset[i]).balanceOfGroup(_msgSender(), poolRequirement.requiredId[j]); } } return amount >= poolRequirement.requiredAmount; } } return true; } /** * Private function to avoid a stack-too-deep error. */ function mintingHelper(uint256 _itemIndex, uint256 _groupId, uint256 _id, bytes32 _itemKey, uint256 _amount, uint256 _newCirculatingTotal, uint256 _userPoolPurchaseAmount, uint256 _userGlobalPurchaseAmount) private { // If payment is successful, mint each of the user's purchased items. uint256[] memory itemIds = new uint256[](_amount); uint256[] memory amounts = new uint256[](_amount); bytes32 key = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupId)); uint256 nextIssueNumber = nextItemIssues[key]; { uint256 shiftedGroupId = _groupId << 128; for (uint256 i = 1; i <= _amount; i++) { uint256 itemId = (shiftedGroupId + nextIssueNumber) + i; itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } // Update the tracker for available item issue numbers. nextItemIssues[key] = nextIssueNumber + _amount; // Update the count of circulating items from this pool. pools[_id].itemMinted[_itemKey] = _newCirculatingTotal; // Update the pool's count of items that a user has purchased. pools[_id].purchaseCounts[_msgSender()] = _userPoolPurchaseAmount; // Update the global count of items that a user has purchased. globalPurchaseCounts[_msgSender()] = _userGlobalPurchaseAmount; // Mint the items. items[_itemIndex].mintBatch(_msgSender(), itemIds, amounts, ""); emit ItemPurchased(_msgSender(), _id, itemIds, amounts); } } // 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 (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: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../access/PermitControl.sol"; /** @title A base contract which supports an administrative sweep function wherein authorized callers may transfer ERC-20 tokens out of this contract. @author Tim Clancy @author Qazawat Zirak This is a base contract designed with the intent to support rescuing ERC-20 tokens which users might have wrongly sent to a contract. */ contract Sweepable is PermitControl { using SafeERC20 for IERC20; /// The public identifier for the right to sweep tokens. bytes32 public constant SWEEP = keccak256("SWEEP"); /// The public identifier for the right to lock token sweeps. bytes32 public constant LOCK_SWEEP = keccak256("LOCK_SWEEP"); /// A flag determining whether or not the `sweep` function may be used. bool public sweepLocked; /** An event to track a token sweep event. @param sweeper The calling address which triggered the sweeep. @param token The specific ERC-20 token being swept. @param amount The amount of the ERC-20 token being swept. @param recipient The recipient of the swept tokens. */ event TokenSweep(address indexed sweeper, IERC20 indexed token, uint256 amount, address indexed recipient); /** An event to track future use of the `sweep` function being locked. @param locker The calling address which locked down sweeping. */ event SweepLocked(address indexed locker); /** Return a version number for this contract's interface. */ function version() external virtual override pure returns (uint256) { return 1; } /** Allow the owner or an approved manager to sweep all of a particular ERC-20 token from the contract and send it to another address. This function exists to allow the shop owner to recover tokens that are otherwise sent directly to this contract and get stuck. Provided that sweeping is not locked, this is a useful tool to help buyers recover otherwise-lost funds. @param _token The token to sweep the balance from. @param _amount The amount of token to sweep. @param _address The address to send the swept tokens to. */ function sweep(IERC20 _token, uint256 _amount, address _address) external hasValidPermit(UNIVERSAL, SWEEP) { require(!sweepLocked, "Sweep: the sweep function is locked"); _token.safeTransfer(_address, _amount); emit TokenSweep(_msgSender(), _token, _amount, _address); } /** Allow the shop owner or an approved manager to lock the contract against any future token sweeps. */ function lockSweep() external hasValidPermit(UNIVERSAL, LOCK_SWEEP) { sweepLocked = true; emit SweepLocked(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; import "../../../libraries/DFStorage.sol"; /** @title An interface for the `Super1155` ERC-1155 item collection contract. @author 0xthrpw @author Tim Clancy August 12th, 2021. */ interface ISuper1155 { /// The public identifier for the right to set this contract's metadata URI. function SET_URI () external view returns (bytes32); /// The public identifier for the right to set this contract's proxy registry. function SET_PROXY_REGISTRY () external view returns (bytes32); /// The public identifier for the right to configure item groups. function CONFIGURE_GROUP () external view returns (bytes32); /// The public identifier for the right to mint items. function MINT () external view returns (bytes32); /// The public identifier for the right to burn items. function BURN () external view returns (bytes32); /// The public identifier for the right to set item metadata. function SET_METADATA () external view returns (bytes32); /// The public identifier for the right to lock the metadata URI. function LOCK_URI () external view returns (bytes32); /// The public identifier for the right to lock an item's metadata. function LOCK_ITEM_URI () external view returns (bytes32); /// The public identifier for the right to disable item creation. function LOCK_CREATION () external view returns (bytes32); /// The public name of this contract. function name () external view returns (string memory); /** The ERC-1155 URI for tracking item metadata, supporting {id} substitution. For example: https://token-cdn-domain/{id}.json. See the ERC-1155 spec for more details: https://eips.ethereum.org/EIPS/eip-1155#metadata. */ function metadataUri () external view returns (string memory); /// A proxy registry address for supporting automatic delegated approval. function proxyRegistryAddress () external view returns (address); /// A mapping from each group ID to per-address balances. function groupBalances (uint256, address) external view returns (uint256); /// A mapping from each address to a collection-wide balance. function totalBalances (address) external view returns (uint256); /// A mapping of data for each item group. // function itemGroups (uint256) external view returns (ItemGroup memory); /* function itemGroups (uint256) external view returns (bool initialized, string memory _name, uint8 supplyType, uint256 supplyData, uint8 itemType, uint256 itemData, uint8 burnType, uint256 burnData, uint256 _circulatingSupply, uint256 _mintCount, uint256 _burnCount); */ /// A mapping of circulating supplies for each individual token. function circulatingSupply (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been minted. function mintCount (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been burnt. function burnCount (uint256) external view returns (uint256); /** A mapping of token ID to a boolean representing whether the item's metadata has been explicitly frozen via a call to `lockURI(string calldata _uri, uint256 _id)`. Do note that it is possible for an item's mapping here to be false while still having frozen metadata if the item collection as a whole has had its `uriLocked` value set to true. */ function metadataFrozen (uint256) external view returns (bool); /** A public mapping of optional on-chain metadata for each token ID. A token's on-chain metadata is unable to be changed if the item's metadata URI has been permanently fixed or if the collection's metadata URI as a whole has been frozen. */ function metadata (uint256) external view returns (string memory); /// Whether or not the metadata URI has been locked to future changes. function uriLocked () external view returns (bool); /// Whether or not the item collection has been locked to all further minting. function locked () external view returns (bool); /** Return a version number for this contract's interface. */ function version () external view returns (uint256); /** Return the item collection's metadata URI. This implementation returns the same URI for all tokens within the collection and relies on client-side ID substitution per https://eips.ethereum.org/EIPS/eip-1155#metadata. Per said specification, clients calling this function must replace the {id} substring with the actual token ID in hex, not prefixed by 0x, and padded to 64 characters in length. @return The metadata URI string of the item with ID `_itemId`. */ function uri (uint256) external view returns (string memory); /** Allow the item collection owner or an approved manager to update the metadata URI of this collection. This implementation relies on a single URI for all items within the collection, and as such does not emit the standard URI event. Instead, we emit our own event to reflect changes in the URI. @param _uri The new URI to update to. */ function setURI (string memory _uri) external; /** Allow the item collection owner or an approved manager to update the proxy registry address handling delegated approval. @param _proxyRegistryAddress The address of the new proxy registry to update to. */ function setProxyRegistry (address _proxyRegistryAddress) external; /** Retrieve the balance of a particular token `_id` for a particular address `_owner`. @param _owner The owner to check for this token balance. @param _id The ID of the token to check for a balance. @return The amount of token `_id` owned by `_owner`. */ function balanceOf (address _owner, uint256 _id) external view returns (uint256); /** Retrieve in a single call the balances of some mulitple particular token `_ids` held by corresponding `_owners`. @param _owners The owners to check for token balances. @param _ids The IDs of tokens to check for balances. @return the amount of each token owned by each owner. */ function balanceOfBatch (address[] memory _owners, uint256[] memory _ids) external view returns (uint256[] memory); /** This function returns true if `_operator` is approved to transfer items owned by `_owner`. This approval check features an override to explicitly whitelist any addresses delegated in the proxy registry. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. @return Whether `_operator` may transfer items owned by `_owner`. */ function isApprovedForAll (address _owner, address _operator) external view returns (bool); /** Enable or disable approval for a third party `_operator` address to manage (transfer or burn) all of the caller's tokens. @param _operator The address to grant management rights over all of the caller's tokens. @param _approved The status of the `_operator`'s approval for the caller. */ function setApprovalForAll (address _operator, bool _approved) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _amount The amount of the specific `_id` to transfer. @param _data Additional call data to send with this transfer. */ function safeTransferFrom (address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function safeBatchTransferFrom (address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** Create a new NFT item group or configure an existing one. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param _groupId The ID of the item group to create or configure. @param _data The `ItemGroup` data input. */ function configureGroup (uint256 _groupId, DFStorage.ItemGroupInput calldata _data) external; /** Mint a batch of tokens into existence and send them to the `_recipient` address. In order to mint an item, its item group must first have been created. Minting an item must obey both the fungibility and size cap of its group. @param _recipient The address to receive all NFTs within the newly-minted group. @param _ids The item IDs for the new items to create. @param _amounts The amount of each corresponding item ID to create. @param _data Any associated data to use on items minted in this transaction. */ function mintBatch (address _recipient, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** This function allows an address to destroy some of its items. @param _burner The address whose item is burning. @param _id The item ID to burn. @param _amount The amount of the corresponding item ID to burn. */ function burn (address _burner, uint256 _id, uint256 _amount) external; /** This function allows an address to destroy multiple different items in a single call. @param _burner The address whose items are burning. @param _ids The item IDs to burn. @param _amounts The amounts of the corresponding item IDs to burn. */ function burnBatch (address _burner, uint256[] memory _ids, uint256[] memory _amounts) external; /** Set the on-chain metadata attached to a specific token ID so long as the collection as a whole or the token specifically has not had metadata editing frozen. @param _id The ID of the token to set the `_metadata` for. @param _metadata The metadata string to store on-chain. */ function setMetadata (uint256 _id, string memory _metadata) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on the entire collection to future changes. @param _uri The value of the URI to lock for `_id`. */ function lockURI(string calldata _uri) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on an item to future changes. @param _uri The value of the URI to lock for `_id`. @param _id The token ID to lock a metadata URI value into. */ function lockURI(string calldata _uri, uint256 _id) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on a group of items to future changes. @param _uri The value of the URI to lock for `groupId`. @param groupId The group ID to lock a metadata URI value into. */ function lockGroupURI(string calldata _uri, uint256 groupId) external; /** Allow the item collection owner or an associated manager to forever lock this contract to further item minting. */ function lock() external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; /** @title Super721 interface Interface for interacting with Super721 contract */ interface ISuper721 { /** Returns amount of NFTs, which are owned by `_owner` in some group `_id`. @param _owner address of NFTs owner. @param _id group id of collection. */ function balanceOfGroup(address _owner, uint256 _id) external view returns (uint256); /** Returns overall amount of NFTs, which are owned by `_owner`. @param _owner address of NFTs owner. */ function balanceOf(address _owner) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; /// @title interface for interacting with Staker contract. interface IStaker { /** Allows an approved spender of points to spend points on behalf of a user. @param _user The user whose points are being spent. @param _amount The amount of the user's points being spent. */ function spendPoints(address _user, uint256 _amount) external; /** Return the number of points that the user has available to spend. @return the number of points that the user has available to spend. */ function getAvailablePoints(address _user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; import "../assets/erc1155/interfaces/ISuper1155.sol"; /** @title Interface for interaction with MintShop contract. */ interface IMintShop { /** Allow the owner of the shop or an approved manager to add a new pool of items that users may purchase. @param _pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function addPool( DFStorage.PoolInput calldata _pool, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices ) external; /** Adds new whiteList restriction for the pool by `_poolId`. @param _poolId id of the pool, where new white list is added. @param whitelist struct for creating a new whitelist. */ function addWhiteList(uint256 _poolId, DFStorage.WhiteListCreate[] calldata whitelist) external; /** Allow the shop owner or an approved manager to set the array of items known to this shop. @param _items The array of Super1155 addresses. */ function setItems(ISuper1155[] memory _items) external; /// The public identifier for the right to set new items. function SET_ITEMS() external view returns (bytes32); /// The public identifier for the right to manage item pools. function POOL() external view returns (bytes32); /// The public identifier for the right to manage whitelists. function WHITELIST() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./MerkleCore.sol"; import "../../interfaces/IMerkle.sol"; /** @title A merkle tree based access control. @author Qazawat Zirak This contract replaces the traditional whitelists for access control by using a merkle tree, storing the root on-chain instead of all the addressses. The merkle tree alongside the whitelist is kept off-chain for lookups and creating proofs to validate an access. This code is inspired by and modified from incredible work of RicMoo. https://github.com/ricmoo/ethers-airdrop/blob/master/AirDropToken.sol October 12th, 2021. */ abstract contract SuperMerkleAccess is MerkleCore { /// The public identifier for the right to set a root for a round. bytes32 public constant SET_ACCESS_ROUND = keccak256("SET_ACCESS_ROUND"); /** A struct containing information about the AccessList. @param merkleRoot the proof stored on chain to verify against. @param startTime the start time of validity for the accesslist. @param endTime the end time of validity for the accesslist. @param round the number times the accesslist has been set. @param price the amount of ether/token required for the access. @param token the address of the token, paid as a price. A price with zero token address is ether. */ struct AccessList { bytes32 merkleRoot; uint256 startTime; uint256 endTime; uint256 round; uint256 price; address token; } /// MerkleRootId to 'Accesslist', each containing a merkleRoot. mapping (uint256 => AccessList) public accessRoots; /** Set a new round for the accesslist. @param _accesslistId the accesslist id containg the merkleRoot. @param _merkleRoot the new merkleRoot for the round. @param _startTime the start time of the new round. @param _endTime the end time of the new round. @param _price the access price. @param _token the token address for access price. */ function setAccessRound(uint256 _accesslistId, bytes32 _merkleRoot, uint256 _startTime, uint256 _endTime, uint256 _price, address _token) public virtual hasValidPermit(UNIVERSAL, SET_ACCESS_ROUND) { AccessList memory accesslist = AccessList({ merkleRoot: _merkleRoot, startTime: _startTime, endTime: _endTime, round: accessRoots[_accesslistId].round + 1, price: _price, token: _token }); accessRoots[_accesslistId] = accesslist; } /** Verify an access against a targetted markleRoot on-chain. @param _accesslistId the id of the accesslist containing the merkleRoot. @param _index index of the hashed node from off-chain list. @param _node the actual hashed node which needs to be verified. @param _merkleProof required merkle hashes from off-chain merkle tree. */ function verify(uint256 _accesslistId, uint256 _index, bytes32 _node, bytes32[] calldata _merkleProof) public virtual view returns(bool) { if (accessRoots[_accesslistId].merkleRoot == 0) { return false; } else if (block.timestamp < accessRoots[_accesslistId].startTime) { return false; } else if (block.timestamp > accessRoots[_accesslistId].endTime) { return false; } else if (getRootHash(_index, _node, _merkleProof) != accessRoots[_accesslistId].merkleRoot) { return false; } return true; } } pragma solidity 0.8.8; library DFStorage { /** @notice This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startTime The timestamp when this pool begins allowing purchases. @param endTime The timestamp after which this pool disallows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param singlePurchaseLimit The maximum number of items a single address may purchase from this pool in a single transaction. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startTime; uint256 endTime; uint256 purchaseLimit; uint256 singlePurchaseLimit; PoolRequirement requirement; address collection; } /** @notice This enumeration type specifies the different access rules that may be applied to pools in this shop. Access to a pool may be restricted based on the buyer's holdings of either tokens or items. @param Public This specifies a pool which requires no special asset holdings to buy from. @param TokenRequired This specifies a pool which requires the buyer to hold some amount of ERC-20 tokens to buy from. @param ItemRequired This specifies a pool which requires the buyer to hold some amount of an ERC-1155 item to buy from. @param PointRequired This specifies a pool which requires the buyer to hold some amount of points in a Staker to buy from. */ enum AccessType { Public, TokenRequired, ItemRequired, PointRequired, ItemRequired721 } /** @notice This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType The `AccessType` being applied to gate buyers from participating in this pool. See `requiredAsset` for how additional data can apply to the access type. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is `TokenRequired`, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is `ItemRequired`, we use this address to find the item contract that we should be specifically requiring holdings of. If the `requiredType` is `PointRequired`, we treat this address as the address of a Staker contract. Do note that in order for this to work, the Staker must have approved this shop as a point spender. @param requiredAmount The amount of the specified `requiredAsset` required for the buyer to purchase from this pool. @param requiredId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` also apply. An ID of 0 is a sentinel value for no whitelist required. */ struct PoolRequirement { AccessType requiredType; address[] requiredAsset; uint256 requiredAmount; uint256[] requiredId; } /** @notice This enumeration type specifies the different assets that may be used to complete purchases from this mint shop. @param Point This specifies that the asset being used to complete this purchase is non-transferrable points from a `Staker` contract. @param Ether This specifies that the asset being used to complete this purchase is native Ether currency. @param Token This specifies that the asset being used to complete this purchase is an ERC-20 token. */ enum AssetType { Point, Ether, Token } /** @notice This struct tracks information about a single asset with the associated price that an item is being sold in the shop for. It also includes an `asset` field which is used to convey optional additional data about the asset being used to purchase with. @param assetType The `AssetType` type of the asset being used to buy. @param asset Some more specific information about the asset to charge in. If the `assetType` is Point, we use this address to find the specific Staker whose points are used as the currency. If the `assetType` is Ether, we ignore this field. If the `assetType` is Token, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct Price { AssetType assetType; address asset; uint256 price; } /** This enumeration lists the various supply types that each item group may use. In general, the administrator of this collection or those permissioned to do so may move from a more-permissive supply type to a less-permissive. For example: an uncapped or flexible supply type may be converted to a capped supply type. A capped supply type may not be uncapped later, however. @param Capped There exists a fixed cap on the size of the item group. The cap is set by `supplyData`. @param Uncapped There is no cap on the size of the item group. The value of `supplyData` cannot be set below the current circulating supply but is otherwise ignored. @param Flexible There is a cap which can be raised or lowered (down to circulating supply) freely. The value of `supplyData` cannot be set below the current circulating supply and determines the cap. */ enum SupplyType { Capped, Uncapped, Flexible } /** This enumeration lists the various item types that each item group may use. In general, these are static once chosen. @param Nonfungible The item group is truly nonfungible where each ID may be used only once. The value of `itemData` is ignored. @param Fungible The item group is truly fungible and collapses into a single ID. The value of `itemData` is ignored. @param Semifungible The item group may be broken up across multiple repeating token IDs. The value of `itemData` is the cap of any single token ID in the item group. */ enum ItemType { Nonfungible, Fungible, Semifungible } /** This enumeration lists the various burn types that each item group may use. These are static once chosen. @param None The items in this group may not be burnt. The value of `burnData` is ignored. @param Burnable The items in this group may be burnt. The value of `burnData` is the maximum that may be burnt. @param Replenishable The items in this group, once burnt, may be reminted by the owner. The value of `burnData` is ignored. */ enum BurnType { None, Burnable, Replenishable } /** This struct is a source of mapping-free input to the `configureGroup` function. It defines the settings for a particular item group. @param supplyData An optional integer used by some `supplyType` values. @param itemData An optional integer used by some `itemType` values. @param burnData An optional integer used by some `burnType` values. @param name A name for the item group. @param supplyType The supply type for this group of items. @param itemType The type of item represented by this item group. @param burnType The type of burning permitted by this item group. */ struct ItemGroupInput { uint256 supplyData; uint256 itemData; uint256 burnData; SupplyType supplyType; ItemType itemType; BurnType burnType; string name; } /** This structure is used at the moment of NFT purchase. @param whiteListId Id of a whiteList. @param index Element index in the original array @param allowance The quantity is available to the user for purchase. @param node Base hash of the element. @param merkleProof Proof that the user is on the whitelist. */ struct WhiteListInput { uint256 whiteListId; uint256 index; uint256 allowance; bytes32 node; bytes32[] merkleProof; } /** This structure is used at the moment of NFT purchase. @param _accesslistId Id of a whiteList. @param _merkleRoot Hash root of merkle tree. @param _startTime The start date of the whitelist @param _endTime The end date of the whitelist @param _price The price that applies to the whitelist @param _token Token with which the purchase will be made */ struct WhiteListCreate { uint256 _accesslistId; bytes32 _merkleRoot; uint256 _startTime; uint256 _endTime; uint256 _price; address _token; } } // 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: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** @title An advanced permission-management contract. @author Tim Clancy This contract allows for a contract owner to delegate specific rights to external addresses. Additionally, these rights can be gated behind certain sets of circumstances and granted expiration times. This is useful for some more finely-grained access control in contracts. The owner of this contract is always a fully-permissioned super-administrator. August 23rd, 2021. */ abstract contract PermitControl is Ownable { using Address for address; /// A special reserved constant for representing no rights. bytes32 public constant ZERO_RIGHT = hex"00000000000000000000000000000000"; /// A special constant specifying the unique, universal-rights circumstance. bytes32 public constant UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /* A special constant specifying the unique manager right. This right allows an address to freely-manipulate the `managedRight` mapping. **/ bytes32 public constant MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /** A mapping of per-address permissions to the circumstances, represented as an additional layer of generic bytes32 data, under which the addresses have various permits. A permit in this sense is represented by a per-circumstance mapping which couples some right, represented as a generic bytes32, to an expiration time wherein the right may no longer be exercised. An expiration time of 0 indicates that there is in fact no permit for the specified address to exercise the specified right under the specified circumstance. @dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF... max-integer circumstance. Perpetual rights may be given an expiry time of max-integer. */ mapping( address => mapping( bytes32 => mapping( bytes32 => uint256 ))) public permissions; /** An additional mapping of managed rights to manager rights. This mapping represents the administrator relationship that various rights have with one another. An address with a manager right may freely set permits for that manager right's managed rights. Each right may be managed by only one other right. */ mapping( bytes32 => bytes32 ) public managerRight; /** An event emitted when an address has a permit updated. This event captures, through its various parameter combinations, the cases of granting a permit, updating the expiration time of a permit, or revoking a permit. @param updator The address which has updated the permit. @param updatee The address whose permit was updated. @param circumstance The circumstance wherein the permit was updated. @param role The role which was updated. @param expirationTime The time when the permit expires. */ event PermitUpdated( address indexed updator, address indexed updatee, bytes32 circumstance, bytes32 indexed role, uint256 expirationTime ); // /** // A version of PermitUpdated for work with setPermits() function. // @param updator The address which has updated the permit. // @param updatees The addresses whose permit were updated. // @param circumstances The circumstances wherein the permits were updated. // @param roles The roles which were updated. // @param expirationTimes The times when the permits expire. // */ // event PermitsUpdated( // address indexed updator, // address[] indexed updatees, // bytes32[] circumstances, // bytes32[] indexed roles, // uint256[] expirationTimes // ); /** An event emitted when a management relationship in `managerRight` is updated. This event captures adding and revoking management permissions via observing the update history of the `managerRight` value. @param manager The address of the manager performing this update. @param managedRight The right which had its manager updated. @param managerRight The new manager right which was updated to. */ event ManagementUpdated( address indexed manager, bytes32 indexed managedRight, bytes32 indexed managerRight ); /** A modifier which allows only the super-administrative owner or addresses with a specified valid right to perform a call. @param _circumstance The circumstance under which to check for the validity of the specified `right`. @param _right The right to validate for the calling address. It must be non-expired and exist within the specified `_circumstance`. */ modifier hasValidPermit( bytes32 _circumstance, bytes32 _right ) { require(_msgSender() == owner() || hasRight(_msgSender(), _circumstance, _right), "P1"); _; } /** Return a version number for this contract's interface. */ function version() external virtual pure returns (uint256) { return 1; } /** Determine whether or not an address has some rights under the given circumstance, and if they do have the right, until when. @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return The timestamp in seconds when the `_right` expires. If the timestamp is zero, we can assume that the user never had the right. */ function hasRightUntil( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (uint256) { return permissions[_address][_circumstance][_right]; } /** Determine whether or not an address has some rights under the given circumstance, @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return true or false, whether user has rights and time is valid. */ function hasRight( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (bool) { return permissions[_address][_circumstance][_right] > block.timestamp; } /** Set the permit to a specific address under some circumstances. A permit may only be set by the super-administrative contract owner or an address holding some delegated management permit. @param _address The address to assign the specified `_right` to. @param _circumstance The circumstance in which the `_right` is valid. @param _right The specific right to assign. @param _expirationTime The time when the `_right` expires for the provided `_circumstance`. */ function setPermit( address _address, bytes32 _circumstance, bytes32 _right, uint256 _expirationTime ) public virtual hasValidPermit(UNIVERSAL, managerRight[_right]) { require(_right != ZERO_RIGHT, "P2"); permissions[_address][_circumstance][_right] = _expirationTime; emit PermitUpdated(_msgSender(), _address, _circumstance, _right, _expirationTime); } // /** // Version of setPermit() that works with multiple addresses in one transaction. // @param _addresses The array of addresses to assign the specified `_right` to. // @param _circumstances The array of circumstances in which the `_right` is // valid. // @param _rights The array of specific rights to assign. // @param _expirationTimes The array of times when the `_rights` expires for // the provided _circumstance`. // */ // function setPermits( // address[] memory _addresses, // bytes32[] memory _circumstances, // bytes32[] memory _rights, // uint256[] memory _expirationTimes // ) public virtual { // require((_addresses.length == _circumstances.length) // && (_circumstances.length == _rights.length) // && (_rights.length == _expirationTimes.length), // "leghts of input arrays are not equal" // ); // bytes32 lastRight; // for(uint i = 0; i < _rights.length; i++) { // if (lastRight != _rights[i] || (i == 0)) { // require(_msgSender() == owner() || hasRight(_msgSender(), _circumstances[i], _rights[i]), "P1"); // require(_rights[i] != ZERO_RIGHT, "P2"); // lastRight = _rights[i]; // } // permissions[_addresses[i]][_circumstances[i]][_rights[i]] = _expirationTimes[i]; // } // emit PermitsUpdated( // _msgSender(), // _addresses, // _circumstances, // _rights, // _expirationTimes // ); // } /** Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the specified `_managedRight`. @param _managedRight The right which is to have its manager set to `_managerRight`. @param _managerRight The right whose `UNIVERSAL` holders may manage `_managedRight`. */ function setManagerRight( bytes32 _managedRight, bytes32 _managerRight ) external virtual hasValidPermit(UNIVERSAL, MANAGER) { require(_managedRight != ZERO_RIGHT, "P3"); managerRight[_managedRight] = _managerRight; emit ManagementUpdated(_msgSender(), _managedRight, _managerRight); } } // 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 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "../../base/Sweepable.sol"; /** @title A merkle tree root finder. @author Qazawat Zirak This contract is meant for calculating a root hash from any given valid index, valid node at that index, and valid merkle proofs. October 12th, 2021. */ abstract contract MerkleCore is Sweepable { /** Calculate a root hash from given parameters. @param _index index of the hashed node from the list. @param _node the hashed node at that index. @param _merkleProof array of one required merkle hash per level. @return a root hash from given parameters. */ function getRootHash(uint256 _index, bytes32 _node, bytes32[] calldata _merkleProof) internal pure returns(bytes32) { uint256 path = _index; for (uint256 i = 0; i < _merkleProof.length; i++) { if ((path & 0x01) == 1) { _node = keccak256(abi.encodePacked(_merkleProof[i], _node)); } else { _node = keccak256(abi.encodePacked(_node, _merkleProof[i])); } path /= 2; } return _node; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; /** Interface for interacting with contract inheriting from SuperMerkleAccess contract */ interface IMerkle { /** Set a new round for the accesslist. @param _accesslistId the accesslist id containg the merkleRoot. @param _merkleRoot the new merkleRoot for the round. @param _startTime the start time of the new round. @param _endTime the end time of the new round. @param _price the access price. @param _token the token address for access price. */ function setAccessRound(uint256 _accesslistId, bytes32 _merkleRoot, uint256 _startTime, uint256 _endTime, uint256 _price, address _token) external; }
/ Verify that the pool is respecting per-address pool purchase limits.
function mintFromPool(uint256 _id, uint256 _groupId, uint256 _assetIndex, uint256 _amount, uint256 _itemIndex, DFStorage.WhiteListInput calldata _whiteList) external nonReentrant payable { require(_amount > 0, "0x0B"); require(_id < nextPoolId && pools[_id].config.singlePurchaseLimit >= _amount, "0x1B"); bool whiteListed; if (pools[_id].whiteLists.length != 0) { bytes32 root = keccak256(abi.encodePacked(_whiteList.index, _msgSender(), _whiteList.allowance)); whiteListed = super.verify(_whiteList.whiteListId, _whiteList.index, root, _whiteList.merkleProof) && root == _whiteList.node && pools[_id].whiteLists[_whiteList.whiteListId].minted[_msgSender()] + _amount <= _whiteList.allowance; } require(block.timestamp >= pools[_id].config.startTime && block.timestamp <= pools[_id].config.endTime || whiteListed, "0x4B"); bytes32 itemKey = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupId)); require(_assetIndex < pools[_id].itemPricesLength[itemKey], "0x3B"); _amount + globalPurchaseCounts[_msgSender()]; if (globalPurchaseLimit != 0) { require(userGlobalPurchaseAmount <= globalPurchaseLimit, "0x5B"); } uint256 userPoolPurchaseAmount = _amount + pools[_id].purchaseCounts[_msgSender()]; require(newCirculatingTotal <= pools[_id].itemCaps[itemKey], "0x7B"); { uint256 result; for (uint256 i = 0; i < nextPoolId; i++) { for (uint256 j = 0; j < pools[i].itemGroups.length; j++) { result += pools[i].itemMinted[itemKey]; } } require(maxAllocation >= result + _amount, "0x0D"); } require(checkRequirments(_id), "0x8B"); sellingHelper(_id, itemKey, _assetIndex, _amount, whiteListed, _whiteList.whiteListId); mintingHelper(_itemIndex, _groupId, _id, itemKey, _amount, newCirculatingTotal, userPoolPurchaseAmount, userGlobalPurchaseAmount);
15,800,865
./partial_match/4/0x1B8f7C42531b5a5D2B89B83E7A23920075040f47/sources/OptionFactory.sol
set member variables to avoid stack too deep error TODO: cleaner way to do this?
function createMarket( address _baseToken, address _quoteToken, address _oracle, uint256[] memory _strikePrices, uint256 _expiryTime, uint256 _alpha, bool _isPut, uint256 _tradingFee, uint256 _balanceCap, uint256 _totalSupplyCap ) external returns (address market) { oracle = _oracle; strikePrices = _strikePrices; expiryTime = _expiryTime; alpha = _alpha; isPut = _isPut; tradingFee = _tradingFee; balanceCap = _balanceCap; totalSupplyCap = _totalSupplyCap; market = createClone(optionMarketLibrary); address baseToken = isPut ? _quoteToken : _baseToken; uint8 decimals = IERC20(baseToken).isETH() ? 18 : ERC20UpgradeSafe(baseToken).decimals(); string memory underlyingSymbol = IERC20(_baseToken).isETH() ? "ETH" : ERC20UpgradeSafe(_baseToken).symbol(); string memory symbol; address[] memory longTokens = new address[](strikePrices.length); address[] memory shortTokens = new address[](strikePrices.length); for (uint256 i = 0; i < strikePrices.length; i++) { longTokens[i] = createClone(optionTokenLibary); shortTokens[i] = createClone(optionTokenLibary); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, true); OptionToken(longTokens[i]).initialize(market, symbol, symbol, decimals); symbol = getSymbol(underlyingSymbol, strikePrices[i], expiryTime, isPut, false); OptionToken(shortTokens[i]).initialize(market, symbol, symbol, decimals); } OptionMarket(market).initialize( baseToken, oracle, longTokens, shortTokens, strikePrices, expiryTime, alpha, isPut, tradingFee, balanceCap, totalSupplyCap ); OptionMarket(market).transferOwnership(msg.sender); markets.push(market); }
16,961,212
// SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "./VolmexProtocol.sol"; import "../library/VolmexSafeERC20.sol"; /** * @title Protocol Contract with Precision * @author volmex.finance [[email protected]] * * This protocol is used for decimal values less than 18. */ contract VolmexProtocolWithPrecision is VolmexProtocol { using VolmexSafeERC20 for IERC20Modified; // This is the ratio of standard ERC20 tokens decimals by custom token decimals // Calculation for USDC: 10^18 / 10^6 = 10^12 // Where 10^18 represent precision of volatility token decimals and 10^6 represent USDC (collateral) decimals uint256 public precisionRatio; /** * @dev Makes the protocol `active` at deployment * @dev Sets the `minimumCollateralQty` * @dev Makes the collateral token as `collateral` * @dev Assign position tokens * @dev Sets the `volatilityCapRatio` * * @param _collateralTokenAddress is address of collateral token typecasted to IERC20Modified * @param _volatilityToken is address of volatility index token typecasted to IERC20Modified * @param _inverseVolatilityToken is address of inverse volatility index token typecasted to IERC20Modified * @param _minimumCollateralQty is the minimum qty of tokens need to mint 0.1 volatility and inverse volatility tokens * @param _volatilityCapRatio is the cap for volatility * @param _ratio Ratio of standard ERC20 token decimals (18) by custom token */ function initializePrecision( IERC20Modified _collateralTokenAddress, IERC20Modified _volatilityToken, IERC20Modified _inverseVolatilityToken, uint256 _minimumCollateralQty, uint256 _volatilityCapRatio, uint256 _ratio ) external initializer { initialize( _collateralTokenAddress, _volatilityToken, _inverseVolatilityToken, _minimumCollateralQty, _volatilityCapRatio ); precisionRatio = _ratio; } /** * @notice Add collateral to the protocol and mint the position tokens * @param _collateralQty Quantity of the collateral being deposited * * @dev Added precision ratio to calculate the effective collateral qty * * NOTE: Collateral quantity should be at least required minimum collateral quantity * * Calculation: Get the quantity for position token * Mint the position token for `msg.sender` * */ function collateralize(uint256 _collateralQty) external virtual override onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); // Mechanism to calculate the collateral qty using the increase in balance // of protocol contract to counter USDT's fee mechanism, which can be enabled in future uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 effectiveCollateralQty = _collateralQty * precisionRatio; uint256 qtyToBeMinted = effectiveCollateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); } function _redeem( uint256 _collateralQtyRedeemed, uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) internal virtual override { require( _collateralQtyRedeemed > precisionRatio, "Volmex: Collateral qty is less" ); uint256 effectiveCollateralQty = _collateralQtyRedeemed / precisionRatio; uint256 fee; if (redeemFees > 0) { fee = (_collateralQtyRedeemed * redeemFees) / (precisionRatio * 10000); effectiveCollateralQty = effectiveCollateralQty - fee; accumulatedFees = accumulatedFees + fee; } volatilityToken.burn(msg.sender, _volatilityIndexTokenQty); inverseVolatilityToken.burn( msg.sender, _inverseVolatilityIndexTokenQty ); collateral.safeTransfer(msg.sender, effectiveCollateralQty); emit Redeemed( msg.sender, effectiveCollateralQty, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty, fee ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IERC20Modified.sol"; import "../library/VolmexSafeERC20.sol"; /** * @title Protocol Contract * @author volmex.finance [[email protected]] */ contract VolmexProtocol is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using VolmexSafeERC20 for IERC20Modified; event ToggleActivated(bool isActive); event UpdatedVolatilityToken( address indexed positionToken, bool isVolatilityIndexToken ); event UpdatedFees(uint256 issuanceFees, uint256 redeemFees); event UpdatedMinimumCollateral(uint256 newMinimumCollateralQty); event ClaimedFees(uint256 fees); event ToggledVolatilityTokenPause(bool isPause); event Settled(uint256 settlementPrice); event Collateralized( address indexed sender, uint256 collateralLock, uint256 positionTokensMinted, uint256 fees ); event Redeemed( address indexed sender, uint256 collateralReleased, uint256 volatilityIndexTokenBurned, uint256 inverseVolatilityIndexTokenBurned, uint256 fees ); // Has the value of minimum collateral qty required uint256 public minimumCollateralQty; // Has the boolean state of protocol bool public active; // Has the boolean state of protocol settlement bool public isSettled; // Volatility tokens IERC20Modified public volatilityToken; IERC20Modified public inverseVolatilityToken; // Only ERC20 standard functions are used by the collateral defined here. // Address of the acceptable collateral token. IERC20Modified public collateral; // Used to calculate collateralize fee uint256 public issuanceFees; // Used to calculate redeem fee uint256 public redeemFees; // Total fee amount for call of collateralize and redeem uint256 public accumulatedFees; // Percentage value is upto two decimal places, so we're dividing it by 10000 // Set the max fee as 5%, i.e. 500/10000. uint256 constant MAX_FEE = 500; // No need to add 18 decimals, because they are already considered in respective token qty arguments. uint256 public volatilityCapRatio; // This is the price of volatility index, ranges from 0 to volatilityCapRatio, // and the inverse can be calculated by subtracting volatilityCapRatio by settlementPrice. uint256 public settlementPrice; /** * @notice Used to check contract is active */ modifier onlyActive() { require(active, "Volmex: Protocol not active"); _; } /** * @notice Used to check contract is not settled */ modifier onlyNotSettled() { require(!isSettled, "Volmex: Protocol settled"); _; } /** * @notice Used to check contract is settled */ modifier onlySettled() { require(isSettled, "Volmex: Protocol not settled"); _; } /** * @dev Makes the protocol `active` at deployment * @dev Sets the `minimumCollateralQty` * @dev Makes the collateral token as `collateral` * @dev Assign position tokens * @dev Sets the `volatilityCapRatio` * * @param _collateralTokenAddress is address of collateral token typecasted to IERC20Modified * @param _volatilityToken is address of volatility index token typecasted to IERC20Modified * @param _inverseVolatilityToken is address of inverse volatility index token typecasted to IERC20Modified * @param _minimumCollateralQty is the minimum qty of tokens need to mint 0.1 volatility and inverse volatility tokens * @param _volatilityCapRatio is the cap for volatility */ function initialize( IERC20Modified _collateralTokenAddress, IERC20Modified _volatilityToken, IERC20Modified _inverseVolatilityToken, uint256 _minimumCollateralQty, uint256 _volatilityCapRatio ) public initializer { __Ownable_init(); __ReentrancyGuard_init(); require( _minimumCollateralQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); active = true; minimumCollateralQty = _minimumCollateralQty; collateral = _collateralTokenAddress; volatilityToken = _volatilityToken; inverseVolatilityToken = _inverseVolatilityToken; volatilityCapRatio = _volatilityCapRatio; } /** * @notice Toggles the active variable. Restricted to only the owner of the contract. */ function toggleActive() external virtual onlyOwner { active = !active; emit ToggleActivated(active); } /** * @notice Update the `minimumCollateralQty` * @param _newMinimumCollQty Provides the new minimum collateral quantity */ function updateMinimumCollQty(uint256 _newMinimumCollQty) external virtual onlyOwner { require( _newMinimumCollQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); minimumCollateralQty = _newMinimumCollQty; emit UpdatedMinimumCollateral(_newMinimumCollQty); } /** * @notice Update the {Volatility Token} * @param _positionToken Address of the new position token * @param _isVolatilityIndexToken Type of the position token, { VolatilityIndexToken: true, InverseVolatilityIndexToken: false } */ function updateVolatilityToken( address _positionToken, bool _isVolatilityIndexToken ) external virtual onlyOwner { _isVolatilityIndexToken ? volatilityToken = IERC20Modified(_positionToken) : inverseVolatilityToken = IERC20Modified(_positionToken); emit UpdatedVolatilityToken(_positionToken, _isVolatilityIndexToken); } /** * @notice Add collateral to the protocol and mint the position tokens * @param _collateralQty Quantity of the collateral being deposited * * NOTE: Collateral quantity should be at least required minimum collateral quantity * * Calculation: Get the quantity for position token * Mint the position token for `msg.sender` * */ function collateralize(uint256 _collateralQty) external virtual onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); // Mechanism to calculate the collateral qty using the increase in balance // of protocol contract to counter USDT's fee mechanism, which can be enabled in future uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 qtyToBeMinted = _collateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); } /** * @notice Redeem the collateral from the protocol by providing the position token * * @param _positionTokenQty Quantity of the position token that the user is surrendering * * Amount of collateral is `_positionTokenQty` by the volatilityCapRatio. * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeem(uint256 _positionTokenQty) external virtual onlyActive onlyNotSettled { uint256 collQtyToBeRedeemed = _positionTokenQty * volatilityCapRatio; _redeem(collQtyToBeRedeemed, _positionTokenQty, _positionTokenQty); } /** * @notice Redeem the collateral from the protocol after settlement * * @param _volatilityIndexTokenQty Quantity of the volatility index token that the user is surrendering * @param _inverseVolatilityIndexTokenQty Quantity of the inverse volatility index token that the user is surrendering * * Amount of collateral is `_volatilityIndexTokenQty` by the settlementPrice and `_inverseVolatilityIndexTokenQty` * by volatilityCapRatio - settlementPrice * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeemSettled( uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) external virtual onlyActive onlySettled { uint256 collQtyToBeRedeemed = (_volatilityIndexTokenQty * settlementPrice) + (_inverseVolatilityIndexTokenQty * (volatilityCapRatio - settlementPrice)); _redeem( collQtyToBeRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty ); } /** * @notice Settle the contract, preventing new minting and providing individual token redemption * * @param _settlementPrice The price of the volatility index after settlement * * The inverse volatility index token at settlement is worth volatilityCapRatio - volatility index settlement price */ function settle(uint256 _settlementPrice) external virtual onlyOwner onlyNotSettled { require( _settlementPrice <= volatilityCapRatio, "Volmex: _settlementPrice should be less than equal to volatilityCapRatio" ); settlementPrice = _settlementPrice; isSettled = true; emit Settled(settlementPrice); } /** * @notice Recover tokens accidentally sent to this contract */ function recoverTokens( address _token, address _toWhom, uint256 _howMuch ) external virtual nonReentrant onlyOwner { require( _token != address(collateral), "Volmex: Collateral token not allowed" ); IERC20Modified(_token).safeTransfer(_toWhom, _howMuch); } /** * @notice Update the percentage of `issuanceFees` and `redeemFees` * * @param _issuanceFees Percentage of fees required to collateralize the collateral * @param _redeemFees Percentage of fees required to redeem the collateral */ function updateFees(uint256 _issuanceFees, uint256 _redeemFees) external virtual onlyOwner { require( _issuanceFees <= MAX_FEE && _redeemFees <= MAX_FEE, "Volmex: issue/redeem fees should be less than MAX_FEE" ); issuanceFees = _issuanceFees; redeemFees = _redeemFees; emit UpdatedFees(_issuanceFees, _redeemFees); } /** * @notice Safely transfer the accumulated fees to owner */ function claimAccumulatedFees() external virtual onlyOwner { uint256 claimedAccumulatedFees = accumulatedFees; delete accumulatedFees; collateral.safeTransfer(owner(), claimedAccumulatedFees); emit ClaimedFees(claimedAccumulatedFees); } /** * @notice Pause/unpause volmex position token. * * @param _isPause Boolean value to pause or unpause the position token { true = pause, false = unpause } */ function togglePause(bool _isPause) external virtual onlyOwner { if (_isPause) { volatilityToken.pause(); inverseVolatilityToken.pause(); } else { volatilityToken.unpause(); inverseVolatilityToken.unpause(); } emit ToggledVolatilityTokenPause(_isPause); } function _redeem( uint256 _collateralQtyRedeemed, uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) internal virtual { uint256 fee; if (redeemFees > 0) { fee = (_collateralQtyRedeemed * redeemFees) / 10000; _collateralQtyRedeemed = _collateralQtyRedeemed - fee; accumulatedFees = accumulatedFees + fee; } volatilityToken.burn(msg.sender, _volatilityIndexTokenQty); inverseVolatilityToken.burn( msg.sender, _inverseVolatilityIndexTokenQty ); collateral.safeTransfer(msg.sender, _collateralQtyRedeemed); emit Redeemed( msg.sender, _collateralQtyRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty, fee ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title VolmexSafeERC20 * @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 VolmexSafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. * * NOTE: Inspired from Openzeppelin's SafeERC20 library. */ library VolmexSafeERC20 { 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), "VolmexSafeERC20: 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 {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 = functionCall(address(token), data, "VolmexSafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "VolmexSafeERC20: ERC20 operation did not succeed"); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "VolmexSafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: 0 }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @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; } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Modified Interface of the OpenZeppelin's IERC20 extra functions to add features in position token. */ interface IERC20Modified is IERC20 { function symbol() external view returns (string memory); function mint(address _toWhom, uint256 amount) external; function burn(address _whose, uint256 amount) external; function grantRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function pause() external; function unpause() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.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); }
Add collateral to the protocol and mint the position tokens _collateralQty Quantity of the collateral being deposited Added precision ratio to calculate the effective collateral qty NOTE: Collateral quantity should be at least required minimum collateral quantity Calculation: Get the quantity for position token Mint the position token for `msg.sender`/ Mechanism to calculate the collateral qty using the increase in balance of protocol contract to counter USDT's fee mechanism, which can be enabled in future
function collateralize(uint256 _collateralQty) external virtual override onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 effectiveCollateralQty = _collateralQty * precisionRatio; uint256 qtyToBeMinted = effectiveCollateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); }
9,919,638
./full_match/80001/0x950b1756c44c95a4469e915484b6AEdFA134F434/sources/project_/contracts/Traductores.sol
Función para minar los tokens de 1 address en concretoemit ValorTraductoresModificado(valorTraductores);
function MintONETraductores(uint _nuevoValorTraductores, address _traductoraddress) external onlyOwner { valorTraductores = _nuevoValorTraductores; GovernanceToken(GovernanceTokenContract).mint(_traductoraddress, _nuevoValorTraductores); } DatosHolders memory datos = DatosHolders(cantidad + amount); datosHolders[msg.sender] = datos; if(s_claimedTokens[msg.sender] != true)
9,538,194
pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } uint256[49] private __gap; } pragma solidity ^0.6.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); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGo { /// @notice Returns the address of the UniqueIdentity contract. function uniqueIdentity() external view returns (address); function go(address account) external view returns (bool); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function investJunior(ITranchedPool pool, uint256 amount) public virtual; function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256); function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function drawdown(uint256 amount) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./CreditLine.sol"; import "../../interfaces/ICreditLine.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title The Accountant * @notice Library for handling key financial calculations, such as interest and principal accrual. * @author Goldfinch */ library Accountant { using SafeMath for uint256; using FixedPoint for FixedPoint.Signed; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for int256; using FixedPoint for uint256; // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled uint256 public constant FP_SCALING_FACTOR = 10**18; uint256 public constant INTEREST_DECIMALS = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365); struct PaymentAllocation { uint256 interestPayment; uint256 principalPayment; uint256 additionalBalancePayment; } function calculateInterestAndPrincipalAccrued( CreditLine cl, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 balance = cl.balance(); // gas optimization uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp); return (interestAccrued, principalAccrued); } function calculateInterestAndPrincipalAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued( ICreditLine cl, uint256 balance, uint256 timestamp ) public view returns (uint256) { // If we've already accrued principal as of the term end time, then don't accrue more principal uint256 termEndTime = cl.termEndTime(); if (cl.interestAccruedAsOf() >= termEndTime) { return 0; } if (timestamp >= termEndTime) { return balance; } else { return 0; } } function calculateWritedownFor( ICreditLine cl, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate); } function calculateWritedownForPrincipal( ICreditLine cl, uint256 principal, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl); if (amountOwedPerDay.isEqual(0)) { return (0, 0); } FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays); FixedPoint.Unsigned memory daysLate; // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to // calculate the periods later. uint256 totalOwed = cl.interestOwed().add(cl.principalOwed()); daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay); if (timestamp > cl.termEndTime()) { uint256 secondsLate = timestamp.sub(cl.termEndTime()); daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY)); } FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate); FixedPoint.Unsigned memory writedownPercent; if (daysLate.isLessThanOrEqual(fpGracePeriod)) { // Within the grace period, we don't have to write down, so assume 0% writedownPercent = FixedPoint.fromUnscaledUint(0); } else { writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate)); } FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR); // This will return a number between 0-100 representing the write down percent with no decimals uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue; return (unscaledWritedownPercent, writedownAmount.rawValue); } function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { // Determine theoretical interestOwed for one full day uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; } function calculateInterestAccrued( CreditLine cl, uint256 balance, uint256 timestamp, uint256 lateFeeGracePeriodInDays ) public view returns (uint256) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numSecondsElapsed. Typically this shouldn't be possible, because // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing // we allow this function to be called with a past timestamp, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this function's purpose is just to normalize balances, and handing in a past timestamp // will necessarily return zero interest accrued (because zero elapsed time), which is correct. uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays); } function calculateInterestAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriodInDays ) public view returns (uint256 interestOwed) { uint256 secondsElapsed = endTime.sub(startTime); uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) { uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS); uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); interestOwed = interestOwed.add(additionalLateFeeInterest); } return interestOwed; } function lateFeeApplicable( CreditLine cl, uint256 timestamp, uint256 gracePeriodInDays ) public view returns (bool) { uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime()); return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY); } function allocatePayment( uint256 paymentAmount, uint256 balance, uint256 interestOwed, uint256 principalOwed ) public pure returns (PaymentAllocation memory) { uint256 paymentRemaining = paymentAmount; uint256 interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint256 principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint256 balanceRemaining = balance.sub(principalPayment); uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IGoldfinchFactory.sol"; import "../../interfaces/IGo.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(gfiAddress(config)); } function getGo(GoldfinchConfig config) internal view returns (IGo) { return IGo(goAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function gfiAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GFI)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function goAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Go)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation, GFI, Go } function getNumberName(uint256 number) public pure returns (string memory) { Numbers numberName = Numbers(number); if (Numbers.TransactionLimit == numberName) { return "TransactionLimit"; } if (Numbers.TotalFundsLimit == numberName) { return "TotalFundsLimit"; } if (Numbers.MaxUnderwriterLimit == numberName) { return "MaxUnderwriterLimit"; } if (Numbers.ReserveDenominator == numberName) { return "ReserveDenominator"; } if (Numbers.WithdrawFeeDenominator == numberName) { return "WithdrawFeeDenominator"; } if (Numbers.LatenessGracePeriodInDays == numberName) { return "LatenessGracePeriodInDays"; } if (Numbers.LatenessMaxDays == numberName) { return "LatenessMaxDays"; } if (Numbers.DrawdownPeriodInSeconds == numberName) { return "DrawdownPeriodInSeconds"; } if (Numbers.TransferRestrictionPeriodInDays == numberName) { return "TransferRestrictionPeriodInDays"; } if (Numbers.LeverageRatio == numberName) { return "LeverageRatio"; } revert("Unknown value passed to getNumberName"); } function getAddressName(uint256 addressKey) public pure returns (string memory) { Addresses addressName = Addresses(addressKey); if (Addresses.Pool == addressName) { return "Pool"; } if (Addresses.CreditLineImplementation == addressName) { return "CreditLineImplementation"; } if (Addresses.GoldfinchFactory == addressName) { return "GoldfinchFactory"; } if (Addresses.CreditDesk == addressName) { return "CreditDesk"; } if (Addresses.Fidu == addressName) { return "Fidu"; } if (Addresses.USDC == addressName) { return "USDC"; } if (Addresses.TreasuryReserve == addressName) { return "TreasuryReserve"; } if (Addresses.ProtocolAdmin == addressName) { return "ProtocolAdmin"; } if (Addresses.OneInch == addressName) { return "OneInch"; } if (Addresses.TrustedForwarder == addressName) { return "TrustedForwarder"; } if (Addresses.CUSDCContract == addressName) { return "CUSDCContract"; } if (Addresses.PoolTokens == addressName) { return "PoolTokens"; } if (Addresses.TranchedPoolImplementation == addressName) { return "TranchedPoolImplementation"; } if (Addresses.SeniorPool == addressName) { return "SeniorPool"; } if (Addresses.SeniorPoolStrategy == addressName) { return "SeniorPoolStrategy"; } if (Addresses.MigratedTranchedPoolImplementation == addressName) { return "MigratedTranchedPoolImplementation"; } if (Addresses.BorrowerImplementation == addressName) { return "BorrowerImplementation"; } if (Addresses.GFI == addressName) { return "GFI"; } if (Addresses.Go == addressName) { return "Go"; } revert("Unknown value passed to getAddressName"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "./BaseUpgradeablePausable.sol"; import "./Accountant.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICreditLine.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; /** * @title CreditLine * @notice A contract that represents the agreement between Backers and * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed. * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not * operate in any standalone capacity. It should generally be considered internal to the TranchedPool. * @author Goldfinch */ // solhint-disable-next-line max-states-count contract CreditLine is BaseUpgradeablePausable, ICreditLine { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; event GoldfinchConfigUpdated(address indexed who, address configAddress); // Credit line terms address public override borrower; uint256 public override limit; uint256 public override interestApr; uint256 public override paymentPeriodInDays; uint256 public override termInDays; uint256 public override lateFeeApr; // Accounting variables uint256 public override balance; uint256 public override interestOwed; uint256 public override principalOwed; uint256 public override termEndTime; uint256 public override nextDueTime; uint256 public override interestAccruedAsOf; uint256 public override lastFullPaymentTime; uint256 public totalInterestAccrued; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public initializer { require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); borrower = _borrower; limit = _limit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; interestAccruedAsOf = block.timestamp; // Unlock owner, which is a TranchedPool, for infinite amount bool success = config.getUSDC().approve(owner, uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Updates the internal accounting to track a drawdown as of current block timestamp. * Does not move any money * @param amount The amount in USDC that has been drawndown */ function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= limit, "Cannot drawdown more than the limit"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!isLate(timestamp), "Cannot drawdown when payments are past due"); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin { lateFeeApr = newLateFeeApr; } function setLimit(uint256 newAmount) external onlyAdmin { limit = newAmount; } function termStartTime() external view returns (uint256) { return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays)); } function setTermEndTime(uint256 newTermEndTime) public onlyAdmin { termEndTime = newTermEndTime; } function setNextDueTime(uint256 newNextDueTime) public onlyAdmin { nextDueTime = newNextDueTime; } function setBalance(uint256 newBalance) public onlyAdmin { balance = newBalance; } function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin { totalInterestAccrued = _totalInterestAccrued; } function setInterestOwed(uint256 newInterestOwed) public onlyAdmin { interestOwed = newInterestOwed; } function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin { principalOwed = newPrincipalOwed; } function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin { interestAccruedAsOf = newInterestAccruedAsOf; } function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin { lastFullPaymentTime = newLastFullPaymentTime; } /** * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied * towards the interest and principal. * @return Any amount remaining after applying payments towards the interest and principal * @return Amount applied towards interest * @return Amount applied towards principal */ function assess() public onlyAdmin returns ( uint256, uint256, uint256 ) { // Do not assess until a full period has elapsed or past due require(balance > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < nextDueTime && !isLate(currentTime())) { return (0, 0, 0); } uint256 timeToAssess = calculateNextDueTime(); setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } return handlePayment(getUSDCBalance(address(this)), timeToAssess); } function calculateNextDueTime() internal view returns (uint256) { uint256 newNextDueTime = nextDueTime; uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (newNextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* newNextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= newNextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); newNextDueTime = newNextDueTime.add(secondsToAdvance); return Math.min(newNextDueTime, termEndTime); } // You're paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && newNextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < newNextDueTime) { return newNextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function isLate(uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime); return secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param paymentAmount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function handlePayment(uint256 paymentAmount, uint256 timestamp) internal returns ( uint256, uint256, uint256 ) { (uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, balance, newInterestOwed, newPrincipalOwed ); uint256 newBalance = balance.sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = balance.sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( newBalance, newInterestOwed.sub(pa.interestPayment), newPrincipalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( this, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. setInterestAccruedAsOf(timestamp); totalInterestAccrued = totalInterestAccrued.add(interestAccrued); } return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued)); } function updateCreditLineAccounting( uint256 newBalance, uint256 newInterestOwed, uint256 newPrincipalOwed ) internal nonReentrant { setBalance(newBalance); setInterestOwed(newInterestOwed); setPrincipalOwed(newPrincipalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 _nextDueTime = nextDueTime; if (newInterestOwed == 0 && _nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < _nextDueTime) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = _nextDueTime; } setLastFullPaymentTime(mostRecentLastDueTime); } setNextDueTime(calculateNextDueTime()); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig(address _initialConfig) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < 10; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < 11; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } }
/ Interface of the ERC20 standard as defined in the EIP./
interface IERC20withDec is IERC20 { function decimals() external view returns (uint8); }
470,010
./partial_match/97/0x737189D306111F2F336F9aCF6C5ba86eBd1bc734/sources/BatchExchange.sol
a solver facing function called for auction settlement batchId index of auction solution is referring to owners array of addresses corresponding to touched orders orderIds array of order indices used in parallel with owners to identify touched order buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays prices list of prices for touched tokens indexed by next parameter tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] return the computed objective value of the solution Requirements: - Solutions for this `batchId` are currently being accepted. - Claimed objetive value is a great enough improvement on the current winning solution - Fee Token price is non-zero - `tokenIdsForPrice` is sorted. - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. - Each touched order is valid at current `batchId`. - Each touched order's `executedSellAmount` does not exceed its remaining amount. - Limit Price of each touched order is respected. - Solution's objective evaluation must be positive. Sub Requirements: Those nested within other functions - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought/ Further assumptions are: owners.length == orderIds.length && owners.length == buyVolumes.length && prices.length == tokenIdsForPrice.length These assumptions are not checked explicitly, as violations of these constraints can not be used to create a beneficial situation Ensure executed price is not lower than the order price: executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator accumulate utility before updateRemainingOrder, but after limitPrice verified! Perform all subtractions after additions to avoid negative valuesfee taker rewards
function submitSolution( uint32 batchId, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchId), "Not accepted"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "No improvement" ); require(verifyAmountThreshold(prices), "Too low price"); require(tokenIdsForPrice.checkPriceOrdering(), "Not sorted"); require(owners.length <= MAX_TOUCHED_ORDERS, "Too many orders"); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; delete latestSolution.feeRewards; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchId), "Invalid order"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "Too low buy amount"); require(executedSellAmount >= AMOUNT_MINIMUM, "Too low sell amount"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "Invalid executed sell amount"); require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "Limit price not satisfied" ); utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], order.sellToken, order.buyToken, executedSellAmount, executedBuyAmount); } for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 objectiveValue = utility.sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { latestSolution.feeRewards.push(uint256(tokenConservation.tokenImbalance(tokenIdsForPrice[i], tokenIdsForPrice))); addBalanceAndBlockWithdrawForThisBatch(feeTaker, tokenIdToAddressMap(tokenIdsForPrice[i]), latestSolution.feeRewards[i]); } documentTrades(batchId, owners, orderIds, buyVolumes, tokenIdsForPrice); emit SolutionSubmission( msg.sender, utility, disregardedUtility, prices, tokenIdsForPrice ); return (objectiveValue); }
11,464,699
./partial_match/1/0x8BB4aEf8dBdBfCBB31bc1a8A176d8ccb82513035/sources/ERC20Store.sol
PRIVATE FUNCTIONS reject ‘null’ results from the map lookup this can only be the case if an unknown `_lockId` is received
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; require(changeRequest.proposedNew != 0); return changeRequest.proposedNew; } event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian ); event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
4,328,643
pragma solidity 0.4.26; import "../../ETO/ETOCommitment.sol"; contract MockETOCommitment is ETOCommitment { //////////////////////// // Constructor //////////////////////// /// anyone may be a deployer, the platform acknowledges the contract by adding it to Universe Commitment collection constructor( Universe universe, address nominee, address companyLegalRep, ETOTerms etoTerms, IEquityToken equityToken ) ETOCommitment( universe, nominee, companyLegalRep, etoTerms, equityToken ) public { } //////////////////////// // Mocked functions //////////////////////// // moves all timestamps towards the past function _mockShiftBackTime(uint256 delta) public { for(uint256 ii = 0; ii<_pastStateTransitionTimes.length; ii += 1) { if(_pastStateTransitionTimes[ii] > 0) { assert(_pastStateTransitionTimes[ii] >= delta); _pastStateTransitionTimes[ii] -= uint32(delta); } } } // convenience function for moving all timestampts towards the past // such that the next state transition will occur in delta seconds // @dev maximum to be shifted is to three days before state transition function _shiftToBeforeNextState(uint32 delta) public { require(delta < 86400, "NF_MOCK_INVALID_DELTA"); ETOState s = state(); uint256 nextTransition = startOfInternal(ETOState(uint(s) + 1)); require(nextTransition != 0 && nextTransition > now + delta, "NF_MOCK_INVALID_TRANSITION_TIME"); _mockShiftBackTime(nextTransition - now - delta); // generate set start date if still in setup if (s == ETOState.Setup) { emit LogETOStartDateSet(msg.sender, nextTransition, nextTransition - delta); } } function _mockPastTime(uint256 idx, uint256 timestamp) public { _pastStateTransitionTimes[idx] = uint32(timestamp); } function _mockStartDate( ETOTerms etoTerms, IEquityToken equityToken, uint256 startDate, uint256 logStartDate ) external { assert(startDate < 0xFFFFFFFF); uint256 startAt = startOfInternal(ETOState.Whitelist); EQUITY_TOKEN = equityToken; runStateMachine(uint32(startDate)); if (startAt == 0) { // log set terms only once emit LogTermsSet(msg.sender, address(etoTerms), address(equityToken)); } emit LogETOStartDateSet(msg.sender, startAt, logStartDate); } // // Override IAgreement internal interface to allow mocking up agreements for fixtures // function mCanAmend(address /*legalRepresentative*/) internal returns (bool) { return true; } }
moves all timestamps towards the past
function _mockShiftBackTime(uint256 delta) public { for(uint256 ii = 0; ii<_pastStateTransitionTimes.length; ii += 1) { if(_pastStateTransitionTimes[ii] > 0) { assert(_pastStateTransitionTimes[ii] >= delta); _pastStateTransitionTimes[ii] -= uint32(delta); } } }
895,507
./full_match/80001/0xc2d5075203a878f4bb571ab1d0D44B10Ef89CB7c/sources/Token.sol
Pays out all Factory ERC20 token balance to owners address _tokenAddress is an address of the ERC20 token to payout
function payoutToken(address _tokenAddress) external { IERC20Lib token = IERC20Lib(_tokenAddress); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Nothing to payout"); token.transfer(owner, amount); }
5,619,485
./full_match/80001/0xc04e87bCd09B1821db562fc2f5748DD193713a67/sources/contracts/TradeableCashflow.sol
If a new stream is opened, or an existing one is opened This will give me the new flowRate, as it is called in after callbacks If inFlowRate === 0, then delete existing flow. if inFlowRate is zero, delete outflow. If there is no existing outflow, then create new flow to equal inflow
function _updateOutflow(bytes calldata ctx) private returns (bytes memory newCtx) { newCtx = ctx; int96 netFlowRate = _cfa.getNetFlow(_acceptedToken, address(this)); (,int96 outFlowRate,,) = _cfa.getFlow(_acceptedToken, address(this), _receiver); int96 inFlowRate = netFlowRate + outFlowRate; if (inFlowRate < 0 ) { } if (inFlowRate == int96(0)) { newCtx = cfaV1.deleteFlowWithCtx(newCtx,address(this), _receiver, _acceptedToken); } else if (outFlowRate != int96(0)){ newCtx = cfaV1.updateFlowWithCtx(ctx, _receiver, _acceptedToken, inFlowRate); } else { newCtx = cfaV1.createFlowWithCtx(ctx, _receiver, _acceptedToken, inFlowRate); } }
9,464,072
./full_match/1/0x6aB144f647ED05E6f7c0b76C5cD7F1D90D64A950/sources/contracts/Contract.sol
To launch $FKS 24 hours after presale ends
function launch() external onlyOwner { launchTime = block.timestamp; }
9,707,703
./full_match/3/0xED4717a7C5c363Af896F64fA4B67C3E2816111fC/sources/contracts/Web3_payment/ETH/Merchant.sol
Include a token in receiving whitelist Only callable by owner/
function includeInRecTokenWhitelist(address _token) public onlyOwner { require(_token != address(0), "Invalid token"); recTokenWhitelist[_token] = true; }
8,194,752
/** *Submitted for verification at Etherscan.io on 2022-02-17 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { 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); } 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); } 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); } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string public _baseURI; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } function baseURI() internal view virtual returns (string memory) { return _baseURI; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } 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); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } 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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } 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]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } 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); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } } contract FMfers is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; uint public constant _TOTALSUPPLY = 10000; uint public maxPerTxn = 10; // 10 uint public maxPerWallet = 10; // 10 - initial 1k , none - public uint256 public price = 0 ether; uint public status = 0; //0 - pause , 1- public bool public revealed = false; string public unrevealedUri = "https://gateway.pinata.cloud/ipfs/QmaL3MmRdotFRRxoixuPx7hq8E39iD6Ppt5WFWDGbw9JFF"; constructor() ERC721("Fuzzy Mfers", "FMfers") { setBaseURI(""); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setunrevealedUri(string memory baseURI) public onlyOwner { unrevealedUri = baseURI; } function setPrice(uint256 _newPrice) public onlyOwner() { price = _newPrice; } function setRevealed(string memory baseURI) public onlyOwner() { revealed = !revealed; setBaseURI(baseURI); } function setMaxxQtPerTx(uint256 _quantity) public onlyOwner { maxPerTxn=_quantity; } function setMaxxQtPerWallet(uint256 _quantity) public onlyOwner { maxPerWallet=_quantity; } function giveaway(address a, uint q) public onlyOwner{ for(uint i=0; i<q; i++) _safeMint(a, totalsupply()+1); } modifier isSaleOpen{ require(totalSupply() < _TOTALSUPPLY, "Sale end"); _; } function setStatus(uint s) public onlyOwner { status = s; } function getStatus() public view returns (uint256) { return status; } function getPrice() public view returns (uint256) { return price ; } function mint(uint chosenAmount) public payable isSaleOpen{ require( (status == 1) , "Sale is not active at the moment" ); require( totalSupply() + chosenAmount <= _TOTALSUPPLY , "Quantity must be lesser then MaxSupply" ); require( chosenAmount > 0 , "Number of tokens can not be less than or equal to 0" ); require( chosenAmount <= maxPerTxn , "Chosen Amount exceeds MaxQuantity" ); require( totalSupply() > 1000 || ( chosenAmount + balanceOf( msg.sender ) <= maxPerWallet ) , "Chosen Amount exceeds MaxQuantity" ); require( price.mul(chosenAmount) == msg.value, "Sent ether value is incorrect" ); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()+1); } if(totalSupply() >= 1000) setPrice(0.03 ether); } function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory result = new uint256[](count); for (uint256 index = 0; index < count; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } function withdraw() public onlyOwner { uint balance = address(this).balance; //5% 0x86fc9DbcE9e909c7AB4D5D94F07e70742E2d144A //95% to owner uint256 split = balance / 100; split = split * 5; payable(0x86fc9DbcE9e909c7AB4D5D94F07e70742E2d144A).transfer(split); balance = balance - split; payable(msg.sender).transfer(balance); } function totalsupply() private view returns (uint) { return super.totalSupply(); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); if(revealed) return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; else return unrevealedUri; } function contractURI() public view returns (string memory) { return "https://gateway.pinata.cloud/ipfs/QmUeUgkeFkyLFoEcXgWR8taQ6obkjCnFAqgqrWa77tWCtL"; } }
5% 0x86fc9DbcE9e909c7AB4D5D94F07e70742E2d144A95% to owner
function withdraw() public onlyOwner { uint balance = address(this).balance; uint256 split = balance / 100; split = split * 5; payable(0x86fc9DbcE9e909c7AB4D5D94F07e70742E2d144A).transfer(split); balance = balance - split; payable(msg.sender).transfer(balance); }
14,472,758
/// #require z > 1; /// #try msg.sender == address(0x0); contract Foo { uint z; /// #require x > 2; /// #try x < 10; function bar(uint x) public { /// #require x > 10; /// #try x == 9; uint z = x + 1; } function boo() public {} function baz() internal {} }
require x > 2; try x < 10;
function bar(uint x) public { uint z = x + 1;
5,386,363
pragma solidity ^0.5.10; pragma experimental ABIEncoderV2; import "@airswap/types/contracts/Types.sol"; import "openzeppelin-solidity/contracts/introspection/ERC165Checker.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import "@airswap/tokens/contracts/interfaces/IERC1155.sol"; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/transfers/contracts/TransferHandlerRegistry.sol"; import "@airswap/tokens/contracts/interfaces/IWETH.sol"; import "@airswap/tokens/contracts/interfaces/IAdaptedKittyERC721.sol"; import "@airswap/delegate/contracts/interfaces/IDelegate.sol"; /** * @title Validator: Helper contract to Swap protocol * @notice contains several helper methods that check whether * a Swap.order is well-formed and counterparty criteria is met */ contract Validator { using ERC165Checker for address; bytes internal constant DOM_NAME = "SWAP"; bytes internal constant DOM_VERSION = "2"; bytes4 internal constant ERC1155_INTERFACE_ID = 0xd9b67a26; bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd; bytes4 internal constant ERC20_INTERFACE_ID = 0x36372b07; bytes4 internal constant CK_INTERFACE_ID = 0x9a20483d; IWETH public wethContract; // size of fixed array that holds max returning error messages uint256 internal constant MAX_ERROR_COUNT = 25; // size of fixed array that holds errors from delegate contract checks uint256 internal constant MAX_DELEGATE_ERROR_COUNT = 10; /** * @notice Contract Constructor * @param validatorWethContract address */ constructor(address validatorWethContract) public { wethContract = IWETH(validatorWethContract); } /** * @notice If order is going through wrapper to a delegate * @param order Types.Order * @param delegate IDelegate * @param wrapper address * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function checkWrappedDelegate( Types.Order calldata order, IDelegate delegate, address wrapper ) external view returns (uint256, bytes32[] memory) { address swap = order.signature.validator; (uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order); ( uint256 delegateErrorCount, bytes32[] memory delegateErrors ) = coreDelegateChecks(order, delegate); if (delegateErrorCount > 0) { // copies over errors from coreDelegateChecks for (uint256 i = 0; i < delegateErrorCount; i++) { errors[i + errorCount] = delegateErrors[i]; } errorCount += delegateErrorCount; } // Check valid token registry handler for sender if (order.sender.kind == ERC20_INTERFACE_ID) { // Check the order sender balance and allowance if (!hasBalance(order.sender)) { errors[errorCount] = "SENDER_BALANCE_LOW"; errorCount++; } // Check their approval if (!isApproved(order.sender, swap)) { errors[errorCount] = "SENDER_ALLOWANCE_LOW"; errorCount++; } } // Check valid token registry handler for signer if (order.signer.kind == ERC20_INTERFACE_ID) { if (order.signer.token != address(wethContract)) { // Check the order signer token balance if (!hasBalance(order.signer)) { errors[errorCount] = "SIGNER_BALANCE_LOW"; errorCount++; } } else { if ((order.signer.wallet).balance < order.signer.amount) { errors[errorCount] = "SIGNER_ETHER_LOW"; errorCount++; } } // Check their approval if (!isApproved(order.signer, swap)) { errors[errorCount] = "SIGNER_ALLOWANCE_LOW"; errorCount++; } } // ensure that sender wallet if receiving weth has approved // the wrapper to transfer weth and deliver eth to the sender if (order.sender.token == address(wethContract)) { uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper); if (allowance < order.sender.amount) { errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW"; errorCount++; } } return (errorCount, errors); } /** * @notice If order is going through wrapper to swap * @param order Types.Order * @param fromAddress address * @param wrapper address * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function checkWrappedSwap( Types.Order calldata order, address fromAddress, address wrapper ) external view returns (uint256, bytes32[] memory) { address swap = order.signature.validator; (uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order); if (order.sender.wallet != fromAddress) { errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER"; errorCount++; } // ensure that sender has approved wrapper contract on swap if ( swap != address(0x0) && !ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper) ) { errors[errorCount] = "SENDER_UNAUTHORIZED"; errorCount++; } // signature must be filled in order to use the Wrapper if (order.signature.v == 0) { errors[errorCount] = "SIGNATURE_MUST_BE_SENT"; errorCount++; } // if sender has WETH token, ensure sufficient ETH balance if (order.sender.token == address(wethContract)) { if ((order.sender.wallet).balance < order.sender.amount) { errors[errorCount] = "SENDER_ETHER_LOW"; errorCount++; } } // ensure that sender wallet if receiving weth has approved // the wrapper to transfer weth and deliver eth to the sender if (order.signer.token == address(wethContract)) { uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper); if (allowance < order.signer.amount) { errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW"; errorCount++; } } // Check valid token registry handler for sender if (hasValidKind(order.sender.kind, swap)) { // Check the order sender if (order.sender.wallet != address(0)) { // The sender was specified // Check if sender kind interface can correctly check balance if (!hasValidInterface(order.sender.token, order.sender.kind)) { errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH"; errorCount++; } else { // Check the order sender token balance when sender is not WETH if (order.sender.token != address(wethContract)) { //do the balance check if (!hasBalance(order.sender)) { errors[errorCount] = "SENDER_BALANCE_LOW"; errorCount++; } } // Check their approval if (!isApproved(order.sender, swap)) { errors[errorCount] = "SENDER_ALLOWANCE_LOW"; errorCount++; } } } } else { errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN"; errorCount++; } // Check valid token registry handler for signer if (hasValidKind(order.signer.kind, swap)) { // Check if signer kind interface can correctly check balance if (!hasValidInterface(order.signer.token, order.signer.kind)) { errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH"; errorCount++; } else { // Check the order signer token balance if (!hasBalance(order.signer)) { errors[errorCount] = "SIGNER_BALANCE_LOW"; errorCount++; } // Check their approval if (!isApproved(order.signer, swap)) { errors[errorCount] = "SIGNER_ALLOWANCE_LOW"; errorCount++; } } } else { errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN"; errorCount++; } return (errorCount, errors); } /** * @notice Takes in an order and outputs any * errors that Swap would revert on * @param order Types.Order Order to settle * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function checkSwap(Types.Order memory order) public view returns (uint256, bytes32[] memory) { address swap = order.signature.validator; (uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order); // Check valid token registry handler for sender if (hasValidKind(order.sender.kind, swap)) { // Check the order sender if (order.sender.wallet != address(0)) { // The sender was specified // Check if sender kind interface can correctly check balance if (!hasValidInterface(order.sender.token, order.sender.kind)) { errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH"; errorCount++; } else { // Check the order sender token balance //do the balance check if (!hasBalance(order.sender)) { errors[errorCount] = "SENDER_BALANCE_LOW"; errorCount++; } // Check their approval if (!isApproved(order.sender, swap)) { errors[errorCount] = "SENDER_ALLOWANCE_LOW"; errorCount++; } } } } else { errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN"; errorCount++; } // Check valid token registry handler for signer if (hasValidKind(order.signer.kind, swap)) { // Check if signer kind interface can correctly check balance if (!hasValidInterface(order.signer.token, order.signer.kind)) { errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH"; errorCount++; } else { // Check the order signer token balance if (!hasBalance(order.signer)) { errors[errorCount] = "SIGNER_BALANCE_LOW"; errorCount++; } // Check their approval if (!isApproved(order.signer, swap)) { errors[errorCount] = "SIGNER_ALLOWANCE_LOW"; errorCount++; } } } else { errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN"; errorCount++; } return (errorCount, errors); } /** * @notice If order is going through delegate via provideOrder * ensure necessary checks are set * @param order Types.Order * @param delegate IDelegate * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function checkDelegate(Types.Order memory order, IDelegate delegate) public view returns (uint256, bytes32[] memory) { (uint256 errorCount, bytes32[] memory errors) = checkSwap(order); ( uint256 delegateErrorCount, bytes32[] memory delegateErrors ) = coreDelegateChecks(order, delegate); if (delegateErrorCount > 0) { // copies over errors from coreDelegateChecks for (uint256 i = 0; i < delegateErrorCount; i++) { errors[i + errorCount] = delegateErrors[i]; } errorCount += delegateErrorCount; } return (errorCount, errors); } /** * @notice Condenses swap specific checks while excluding * token balance or approval checks * @param order Types.Order * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function coreSwapChecks(Types.Order memory order) public view returns (uint256, bytes32[] memory) { address swap = order.signature.validator; bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap); // max size of the number of errors bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT); uint256 errorCount; // Check self transfer if (order.signer.wallet == order.sender.wallet) { errors[errorCount] = "SELF_TRANSFER_INVALID"; errorCount++; } // Check expiry if (order.expiry < block.timestamp) { errors[errorCount] = "ORDER_EXPIRED"; errorCount++; } if (swap != address(0x0)) { ISwap swapContract = ISwap(swap); if ( swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00 ) { errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED"; errorCount++; } if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) { errors[errorCount] = "NONCE_TOO_LOW"; errorCount++; } if (order.signature.signatory != order.signer.wallet) { if ( !swapContract.signerAuthorizations( order.signer.wallet, order.signature.signatory ) ) { errors[errorCount] = "SIGNER_UNAUTHORIZED"; errorCount++; } } } else { errors[errorCount] = "VALIDATOR_INVALID"; errorCount++; } // check if ERC721 or ERC20 only amount or id set for sender if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) { errors[errorCount] = "SENDER_INVALID_ID"; errorCount++; } else if ( (order.sender.kind == ERC721_INTERFACE_ID || order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0 ) { errors[errorCount] = "SENDER_INVALID_AMOUNT"; errorCount++; } // check if ERC721 or ERC20 only amount or id set for signer if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) { errors[errorCount] = "SIGNER_INVALID_ID"; errorCount++; } else if ( (order.signer.kind == ERC721_INTERFACE_ID || order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0 ) { errors[errorCount] = "SIGNER_INVALID_AMOUNT"; errorCount++; } if (!isValid(order, domainSeparator)) { errors[errorCount] = "SIGNATURE_INVALID"; errorCount++; } return (errorCount, errors); } /** * @notice Condenses Delegate specific checks * and excludes swap or balance related checks * @param order Types.Order * @param delegate IDelegate Delegate to interface with * @return uint256 errorCount if any * @return bytes32[] memory array of error messages */ function coreDelegateChecks(Types.Order memory order, IDelegate delegate) public view returns (uint256, bytes32[] memory) { IDelegate.Rule memory rule = delegate.rules( order.sender.token, order.signer.token ); bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT); uint256 errorCount; address swap = order.signature.validator; // signature must be filled in order to use the Delegate if (order.signature.v == 0) { errors[errorCount] = "SIGNATURE_MUST_BE_SENT"; errorCount++; } // check that the sender.wallet == tradewallet if (order.sender.wallet != delegate.tradeWallet()) { errors[errorCount] = "SENDER_WALLET_INVALID"; errorCount++; } // ensure signer kind is ERC20 if (order.signer.kind != ERC20_INTERFACE_ID) { errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20"; errorCount++; } // ensure sender kind is ERC20 if (order.sender.kind != ERC20_INTERFACE_ID) { errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20"; errorCount++; } // ensure that token pair is active with non-zero maxSenderAmount if (rule.maxSenderAmount == 0) { errors[errorCount] = "TOKEN_PAIR_INACTIVE"; errorCount++; } if (order.sender.amount > rule.maxSenderAmount) { errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX"; errorCount++; } // calls the getSenderSize quote to determine how much needs to be paid uint256 senderAmount = delegate.getSenderSideQuote( order.signer.amount, order.signer.token, order.sender.token ); if (senderAmount == 0) { errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE"; errorCount++; } else if (order.sender.amount > senderAmount) { errors[errorCount] = "PRICE_INVALID"; errorCount++; } // ensure that tradeWallet has approved delegate contract on swap if ( swap != address(0x0) && !ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate)) ) { errors[errorCount] = "SENDER_UNAUTHORIZED"; errorCount++; } return (errorCount, errors); } /** * @notice Checks if kind is found in * Swap's Token Registry * @param kind bytes4 token type to search for * @param swap address Swap contract address * @return bool whether kind inserted is valid */ function hasValidKind(bytes4 kind, address swap) internal view returns (bool) { if (swap != address(0x0)) { TransferHandlerRegistry tokenRegistry = ISwap(swap).registry(); return (address(tokenRegistry.transferHandlers(kind)) != address(0)); } else { return false; } } /** * @notice Checks token has valid interface * @param tokenAddress address potential valid interface * @return bool whether address has valid interface */ function hasValidInterface(address tokenAddress, bytes4 interfaceID) internal view returns (bool) { // ERC20s don't normally implement this method if (interfaceID != ERC20_INTERFACE_ID) { return (tokenAddress._supportsInterface(interfaceID)); } return true; } /** * @notice Check a party has enough balance to swap * for supported token types * @param party Types.Party party to check balance for * @return bool whether party has enough balance */ function hasBalance(Types.Party memory party) internal view returns (bool) { if (party.kind == ERC721_INTERFACE_ID || party.kind == CK_INTERFACE_ID) { address owner = IERC721(party.token).ownerOf(party.id); return (owner == party.wallet); } else if (party.kind == ERC1155_INTERFACE_ID) { uint256 balance = IERC1155(party.token).balanceOf(party.wallet, party.id); return (balance >= party.amount); } else { uint256 balance = IERC20(party.token).balanceOf(party.wallet); return (balance >= party.amount); } } /** * @notice Check a party has enough allowance to swap * for ERC721, CryptoKitties, and ERC20 tokens * @param party Types.Party party to check allowance for * @param swap address Swap address * @return bool whether party has sufficient allowance */ function isApproved(Types.Party memory party, address swap) internal view returns (bool) { if (party.kind == ERC721_INTERFACE_ID) { address approved = IERC721(party.token).getApproved(party.id); return (swap == approved); } else if (party.kind == CK_INTERFACE_ID) { address approved = IAdaptedKittyERC721(party.token).kittyIndexToApproved( party.id ); return (swap == approved); } else if (party.kind == ERC1155_INTERFACE_ID) { return IERC1155(party.token).isApprovedForAll(party.wallet, swap); } else { uint256 allowance = IERC20(party.token).allowance(party.wallet, swap); return (allowance >= party.amount); } } /** * @notice Check order signature is valid * @param order Types.Order Order to validate * @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712) * @return bool True if order has a valid signature */ function isValid(Types.Order memory order, bytes32 domainSeparator) internal pure returns (bool) { if (order.signature.v == 0) { return true; } if (order.signature.version == bytes1(0x01)) { return order.signature.signatory == ecrecover( Types.hashOrder(order, domainSeparator), order.signature.v, order.signature.r, order.signature.s ); } if (order.signature.version == bytes1(0x45)) { return order.signature.signatory == ecrecover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", Types.hashOrder(order, domainSeparator) ) ), order.signature.v, order.signature.r, order.signature.s ); } return false; } }
Takes in an order and outputs any errors that Swap would revert on order Types.Order Order to settle return uint256 errorCount if any return bytes32[] memory array of error messages/ Check valid token registry handler for sender Check the order sender The sender was specified Check if sender kind interface can correctly check balance Check the order sender token balancedo the balance check Check their approval Check valid token registry handler for signer Check if signer kind interface can correctly check balance Check the order signer token balance Check their approval
function checkSwap(Types.Order memory order) public view returns (uint256, bytes32[] memory) { address swap = order.signature.validator; (uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order); if (hasValidKind(order.sender.kind, swap)) { if (order.sender.wallet != address(0)) { if (!hasValidInterface(order.sender.token, order.sender.kind)) { errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH"; errorCount++; if (!hasBalance(order.sender)) { errors[errorCount] = "SENDER_BALANCE_LOW"; errorCount++; } if (!isApproved(order.sender, swap)) { errors[errorCount] = "SENDER_ALLOWANCE_LOW"; errorCount++; } } } errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN"; errorCount++; } if (hasValidKind(order.signer.kind, swap)) { if (!hasValidInterface(order.signer.token, order.signer.kind)) { errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH"; errorCount++; if (!hasBalance(order.signer)) { errors[errorCount] = "SIGNER_BALANCE_LOW"; errorCount++; } if (!isApproved(order.signer, swap)) { errors[errorCount] = "SIGNER_ALLOWANCE_LOW"; errorCount++; } } errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN"; errorCount++; } return (errorCount, errors); }
944,040
./full_match/1/0x025030BdAa159f281cAe63873E68313a703725A5/sources/contracts/user_proxies/gelato_user_proxy/interfaces/IGelatoUserProxyFactory.sol
==================== CREATE ======================================= Gelato Task Cycle consists of 1 or more Tasks that automatically submit Gelato Task Cycle consists of 1 or more Tasks that automatically submit that should have occured once the cycle is complete: ==================== CREATE 2 ======================================= ==================== GETTERS =======================================
interface IGelatoUserProxyFactory { event LogCreation( address indexed user, GelatoUserProxy indexed userProxy, uint256 funding ); function create() external payable returns (GelatoUserProxy userProxy); function createExecActions(Action[] calldata _actions) external payable returns (GelatoUserProxy userProxy); function createSubmitTasks( Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable returns (GelatoUserProxy userProxy); function createExecActionsSubmitTasks( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable returns(GelatoUserProxy userProxy); function createExecActionsSubmitTaskCycle( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external payable returns(GelatoUserProxy userProxy); function createExecActionsSubmitTaskChain( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external payable returns(GelatoUserProxy userProxy); function createTwo(uint256 _saltNonce) external payable returns (GelatoUserProxy userProxy); function createTwoExecActions(uint256 _saltNonce, Action[] calldata _actions) external payable returns (GelatoUserProxy userProxy); function createTwoSubmitTasks( uint256 _saltNonce, Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable returns (GelatoUserProxy userProxy); function createTwoExecActionsSubmitTasks( uint256 _saltNonce, Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable returns(GelatoUserProxy userProxy); function createTwoExecActionsSubmitTaskCycle( uint256 _saltNonce, Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external payable returns(GelatoUserProxy userProxy); function createTwoExecActionsSubmitTaskChain( uint256 _saltNonce, Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external payable returns(GelatoUserProxy userProxy); function predictProxyAddress(address _user, uint256 _saltNonce) external view returns(address); function userByGelatoProxy(GelatoUserProxy _userProxy) external view returns(address); function gelatoProxiesByUser(address _user) external view returns(GelatoUserProxy[] memory); function getGelatoUserProxyByIndex(address _user, uint256 _index) external view returns(GelatoUserProxy); function isGelatoUserProxy(address _userProxy) external view returns(bool); function isGelatoProxyUser(address _user, GelatoUserProxy _userProxy) external view returns(bool); function gelatoCore() external pure returns(address); function proxyCreationCode() external pure returns(bytes memory); pragma solidity ^0.6.10; import {GelatoUserProxy} from "../GelatoUserProxy.sol"; import {Action, Provider, Task} from "../../../gelato_core/interfaces/IGelatoCore.sol"; }
9,651,298
./partial_match/1/0xc231EA5C3F934b3a9C502e50fDf66fAb5B179CD4/sources/Aptozeum.sol
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 {APZ-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "APZ: decreased allowance below zero")); return true; }
2,603,772
// ICO Platform Demo smart contract. // Developed by Phenom.Team <[email protected]> pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal constant returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal constant returns(uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal constant returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal constant returns(uint) { uint c = a + b; assert(c >= a); return c; } } /** * @title ERC20 * @dev Standart ERC20 token interface */ contract ERC20 { uint public totalSupply = 0; mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowed; function balanceOf(address _owner) constant returns (uint); function transfer(address _to, uint _value) returns (bool); function transferFrom(address _from, address _to, uint _value) returns (bool); function approve(address _spender, uint _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title PhenomTeam contract - takes funds and issues tokens */ contract PhenomTeam { // PHN - Phenom Demo Token contract using SafeMath for uint; PhenomDemoToken public PHN = new PhenomDemoToken(this); // rateEth can be changed only by Oracle uint public rateEth = 878; // Rate USD per ETH // Output ethereum addresses address public Company; address public Manager; // Manager controls contract address public Controller_Address1; // First address that is used to buy tokens for other cryptos address public Controller_Address2; // Second address that is used to buy tokens for other cryptos address public Controller_Address3; // Third address that is used to buy tokens for other cryptos address public Oracle; // Oracle address // Possible ICO statuses enum StatusICO { Created, Started, Paused, Finished } StatusICO statusICO = StatusICO.Created; // Events Log event LogStartICO(); event LogPause(); event LogFinishICO(); event LogBuyForInvestor(address investor, uint DTRCValue, string txHash); // Modifiers // Allows execution by the manager only modifier managerOnly { require( msg.sender == Manager ); _; } // Allows execution by the oracle only modifier oracleOnly { require(msg.sender == Oracle); _; } // Allows execution by the one of controllers only modifier controllersOnly { require( (msg.sender == Controller_Address1)|| (msg.sender == Controller_Address2)|| (msg.sender == Controller_Address3) ); _; } /** * @dev Contract constructor function */ function PhenomTeam( address _Company, address _Manager, address _Controller_Address1, address _Controller_Address2, address _Controller_Address3, address _Oracle ) public { Company = _Company; Manager = _Manager; Controller_Address1 = _Controller_Address1; Controller_Address2 = _Controller_Address2; Controller_Address3 = _Controller_Address3; Oracle = _Oracle; } /** * @dev Function to set rate of ETH * @param _rateEth current ETH rate */ function setRate(uint _rateEth) external oracleOnly { rateEth = _rateEth; } /** * @dev Function to start ICO * Sets ICO status to Started */ function startIco() external managerOnly { require(statusICO == StatusICO.Created || statusICO == StatusICO.Paused); statusICO = StatusICO.Started; LogStartICO(); } /** * @dev Function to pause ICO * Sets ICO status to Paused */ function pauseIco() external managerOnly { require(statusICO == StatusICO.Started); statusICO = StatusICO.Paused; LogPause(); } /** * @dev Function to finish ICO */ function finishIco() external managerOnly { require(statusICO == StatusICO.Started || statusICO == StatusICO.Paused); statusICO = StatusICO.Finished; LogFinishICO(); } /** * @dev Fallback function calls buy(address _investor, uint _PHNValue) function to issue tokens * when investor sends ETH to address of ICO contract */ function() external payable { buy(msg.sender, msg.value.mul(rateEth)); } /** * @dev Function to issues tokens for investors who made purchases in other cryptocurrencies * @param _investor address the tokens will be issued to * @param _txHash transaction hash of investor's payment * @param _PHNValue number of PHN tokens */ function buyForInvestor( address _investor, uint _PHNValue, string _txHash ) external controllersOnly { buy(_investor, _PHNValue); LogBuyForInvestor(_investor, _PHNValue, _txHash); } /** * @dev Function to issue tokens for investors who paid in ether * @param _investor address which the tokens will be issued tokens * @param _PHNValue number of PHN tokens */ function buy(address _investor, uint _PHNValue) internal { require(statusICO == StatusICO.Started); PHN.mintTokens(_investor, _PHNValue); } /** * @dev Function to enable token transfers */ function unfreeze() external managerOnly { PHN.defrost(); } /** * @dev Function to disable token transfers */ function freeze() external managerOnly { PHN.frost(); } /** * @dev Function to change withdrawal address * @param _Company new withdrawal address */ function setWithdrawalAddress(address _Company) external managerOnly { Company = _Company; } /** * @dev Allows Company withdraw investments */ function withdrawEther() external managerOnly { Company.transfer(this.balance); } } /** * @title PhenomDemoToken * @dev Phenom Demo Token contract */ contract PhenomDemoToken is ERC20 { using SafeMath for uint; string public name = "ICO Platform Demo | https://Phenom.Team "; string public symbol = "PHN"; uint public decimals = 18; // Ico contract address address public ico; // Tokens transfer ability status bool public tokensAreFrozen = true; // Allows execution by the owner only modifier icoOnly { require(msg.sender == ico); _; } /** * @dev Contract constructor function sets Ico address * @param _ico ico address */ function PhenomDemoToken(address _ico) public { ico = _ico; } /** * @dev Function to mint tokens * @param _holder beneficiary address the tokens will be issued to * @param _value number of tokens to issue */ function mintTokens(address _holder, uint _value) external icoOnly { require(_value > 0); balances[_holder] = balances[_holder].add(_value); totalSupply = totalSupply.add(_value); Transfer(0x0, _holder, _value); } /** * @dev Function to enable token transfers */ function defrost() external icoOnly { tokensAreFrozen = false; } /** * @dev Function to disable token transfers */ function frost() external icoOnly { tokensAreFrozen = true; } /** * @dev Get balance of tokens holder * @param _holder holder's address * @return balance of investor */ function balanceOf(address _holder) constant returns (uint) { return balances[_holder]; } /** * @dev Send coins * throws on any error rather then return a false flag to minimize * user errors * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transfer(address _to, uint _amount) public returns (bool) { require(!tokensAreFrozen); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * @dev An account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transferFrom(address _from, address _to, uint _amount) public returns (bool) { require(!tokensAreFrozen); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } /** * @dev Allows another account/contract to spend some tokens on its behalf * throws on any error rather then return a false flag to minimize user errors * * also, to minimize the risk of the approve/transferFrom attack vector * approve has to be called twice in 2 separate transactions - once to * change the allowance to 0 and secondly to change it to the new allowance * value * * @param _spender approved address * @param _amount allowance amount * * @return true if the approval was successful */ function approve(address _spender, uint _amount) public returns (bool) { require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * * @param _owner the address which owns the funds * @param _spender the address which will spend the funds * * @return the amount of tokens still avaible for the spender */ function allowance(address _owner, address _spender) constant returns (uint) { return allowed[_owner][_spender]; } }
Function to enable token transfers/
function unfreeze() external managerOnly { PHN.defrost(); }
15,813,719
// SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "../thirdparty/opensea/OpenSeaGasFreeListing.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** @notice An ERC721 contract with common functionality: - OpenSea gas-free listings - OpenZeppelin Pausable - OpenZeppelin Pausable with functions exposed to Owner only */ contract ERC721Common is Context, ERC721Pausable, OwnerPausable { constructor(string memory name, string memory symbol) ERC721(name, symbol) {} /// @notice Requires that the token exists. modifier tokenExists(uint256 tokenId) { require(ERC721._exists(tokenId), "ERC721Common: Token doesn't exist"); _; } /// @notice Requires that msg.sender owns or is approved for the token. modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Common: Not approved nor owner" ); _; } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** @notice Returns true if either standard isApprovedForAll() returns true or the operator is the OpenSea proxy for the owner. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return super.isApprovedForAll(owner, operator) || OpenSeaGasFreeListing.isApprovedForAll(owner, operator); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; // Inspired by BaseOpenSea by Simon Fremaux (@dievardump) but without the need // to pass specific addresses depending on deployment network. // https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/ import "./ProxyRegistry.sol"; /// @notice Library to achieve gas-free listings on OpenSea. library OpenSeaGasFreeListing { /** @notice Returns whether the operator is an OpenSea proxy for the owner, thus allowing it to list without the token owner paying gas. @dev ERC{721,1155}.isApprovedForAll should be overriden to also check if this function returns true. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { address proxy = proxyFor(owner); return proxy != address(0) && proxy == operator; } /** @notice Returns the OpenSea proxy address for the owner. */ function proxyFor(address owner) internal view returns (address) { address registry; uint256 chainId; assembly { chainId := chainid() switch chainId // Production networks are placed higher to minimise the number of // checks performed and therefore reduce gas. By the same rationale, // mainnet comes before Polygon as it's more expensive. case 1 { // mainnet registry := 0xa5409ec958c83c3f309868babaca7c86dcb077c1 } case 137 { // polygon registry := 0x58807baD0B376efc12F5AD86aAc70E78ed67deaE } case 4 { // rinkeby registry := 0xf57b2c51ded3a29e6891aba85459d600256cf317 } case 80001 { // mumbai registry := 0xff7Ca10aF37178BdD056628eF42fD7F799fAc77c } case 1337 { // The geth SimulatedBackend iff used with the ethier // openseatest package. This is mocked as a Wyvern proxy as it's // more complex than the 0x ones. registry := 0xE1a2bbc877b29ADBC56D2659DBcb0ae14ee62071 } } // Unlike Wyvern, the registry itself is the proxy for all owners on 0x // chains. if (registry == address(0) || chainId == 137 || chainId == 80001) { return registry; } return address(ProxyRegistry(registry).proxies(owner)); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; /// @notice A minimal interface describing OpenSea's Wyvern proxy registry. contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @dev This pattern of using an empty contract is cargo-culted directly from OpenSea's example code. TODO: it's likely that the above mapping can be changed to address => address without affecting anything, but further investigation is needed (i.e. is there a subtle reason that OpenSea released it like this?). */ contract OwnableDelegateProxy { } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @notice A Pausable contract that can only be toggled by the Owner. contract OwnerPausable is Ownable, Pausable { /// @notice Pauses the contract. function pause() public onlyOwner { Pausable._pause(); } /// @notice Unpauses the contract. function unpause() public onlyOwner { Pausable._unpause(); } } // 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/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // Copyright (c) 2022 the aura.lol authors // Author David Huber (@cxkoda) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@divergencetech/ethier/contracts/erc721/ERC721Common.sol"; import "./Renderers/IManifestRenderer.sol"; import "./TokenData.sol"; import "./utils/ERC2981SinglePercentual.sol"; // \ | | _ \ \ | _ \ | // _ \ | | | | _ \ | | | | // ___ \ | | __ < ___ \ | | | | // _/ _\\___/ _| \_\_/ _\_)_____|\___/ _____| // ________aura.lol________Constant_Dullaart_2022_| // // A generative, dynamic in-chain manifest, with physical off-chain interaction, with a max of 8 (or 9 lol) iterations. // // The word "aura" is a reference to the concept referring to the unique aesthetic authority of a work of art, as defined by Walter Benjamin in "The Work of Art in the Age of Mechanical Reproduction" // Where the idea of registering a mechanically reproducible work using decentralised ledger technology would be replacing the sense of 'aura' and making it a commodity. // // // 97 110 100 32 115 111 32 105 116 32 98 101 103 105 110 115 // contract AuraLol is ERC721Common, ERC2981SinglePercentual { using Address for address payable; using EnumerableSet for EnumerableSet.AddressSet; /// @notice Price for minting uint256 public mintPrice = 0.3 ether; /// @notice Total maximum amount of tokens uint16 public constant MAX_NUM_TOKENS = 512; /// @notice Token data used by renderes mapping(uint256 => TokenData) internal tokenData; /// @notice Splits minting fees and royalties between DEVs address payable immutable paymentSplitter; /// @notice The renderer used to visualize the token /// @dev tokenURI will be delegeted to this contract IManifestRenderer internal renderer; /// @notice Contracts with the ability to modify token data EnumerableSet.AddressSet internal mutators; /// @notice Only address that is allowed to call ownerMint. address internal ownerMinter; /// @notice Currently minted supply of tokens uint16 public totalSupply = 0; /// @notice Remaining mints for {mint} uint16 public remainingSales = 256; constructor( address newOwner, address payable paymentSplitter_, address ownerMinter_ ) ERC721Common("aura.lol", "MANI") { paymentSplitter = paymentSplitter_; ownerMinter = ownerMinter_; _setRoyaltyReceiver(paymentSplitter); _setRoyaltyPercentage(500); transferOwnership(newOwner); } // ------------------------------------------------------------------------- // // Minting // // ------------------------------------------------------------------------- /// @notice Sets the amount of remaining minting slots and price function setSalesParameters(uint16 remainingSales_, uint256 mintPrice_) external onlyOwner { remainingSales = remainingSales_; mintPrice = mintPrice_; } /// @dev Disallow all contracts modifier onlyEOA() { if (tx.origin != msg.sender) revert OnlyEOA(); _; } /// @notice Mints tokens to a given address. /// @dev The minter might be different than the receiver. /// @param to Token receiver function mint(address to, uint16 num) external payable onlyEOA { if (num > remainingSales) revert InsufficientTokensRemanining(); if (num * mintPrice != msg.value) revert InvalidPayment(); remainingSales -= num; _processPayment(); _processMint(to, num); } /// @notice Mints tokens to a given address (only for ownerMinter). /// @dev The minter might be different than the receiver. /// @param to Token receiver function ownerMint(address to, uint16 num) external { if (msg.sender != ownerMinter) revert OnlyOwnerMinter(); if (num > remainingSales) revert InsufficientTokensRemanining(); remainingSales -= num; _processMint(to, num); } /// @notice Mints new tokens for the recipient. function _processMint(address to, uint16 num) private { if (num + totalSupply > MAX_NUM_TOKENS) revert InsufficientTokensRemanining(); uint256 tokenId = totalSupply; totalSupply += num; for (uint256 i = 0; i < num; i++) { tokenData[tokenId] = TokenData({ originalOwner: to, generation: 0, mintTimestamp: block.timestamp, data: new bytes[](0) }); ERC721._safeMint(to, tokenId, ""); ++tokenId; } } /// @notice Sets the minter that can access `ownerMint` function setOwnerMinter(address ownerMinter_) external onlyOwner { ownerMinter = ownerMinter_; } // ------------------------------------------------------------------------- // // Payment // // ------------------------------------------------------------------------- /// @notice Default function for receiving funds /// @dev This enable the contract to be used as splitter for royalties. receive() external payable { _processPayment(); } function _processPayment() private { paymentSplitter.sendValue(msg.value); } /// @dev Sets the ERC2981 royalty percentage in units of 0.01% function setRoyaltyPercentage(uint96 percentage) external onlyOwner { _setRoyaltyPercentage(percentage); } // ------------------------------------------------------------------------- // // Mutators // // ------------------------------------------------------------------------- /// @notice Adds a mutator contract to the allow list function addMutator(address mutator) external onlyOwner { mutators.add(mutator); } /// @notice Removes a mutator contract from the allow list function removeMutator(address mutator) external onlyOwner { mutators.remove(mutator); } /// @dev Allows only msg.senders from the mutator allow list modifier onlyMutators() { if (!mutators.contains(msg.sender)) revert OnlyMutators(); _; } /// @notice Modifies tokenData for a certain tokenId /// @dev Only callable by allowlisted mutator contracts function setTokenData(uint256 tokenId, TokenData memory tokenData_) external onlyMutators tokenExists(tokenId) { tokenData[tokenId] = tokenData_; } /// @notice Returns the token data for a certain tokenId function getTokenData(uint256 tokenId) external view tokenExists(tokenId) returns (TokenData memory) { return tokenData[tokenId]; } // ------------------------------------------------------------------------- // // Metadata // // ------------------------------------------------------------------------- /// @notice Changes the current renderer for tokens function setRenderer(address renderer_) external onlyOwner { renderer = IManifestRenderer(renderer_); } /// @notice Returns the URI for token. function tokenURI(uint256 tokenId) public view override tokenExists(tokenId) returns (string memory) { return renderer.tokenURI(tokenId, tokenData[tokenId]); } /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Common, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } // ------------------------------------------------------------------------- // // Errors // // ------------------------------------------------------------------------- error MintDisabled(); error OnlyEOA(); error InsufficientTokensRemanining(); error InvalidPayment(); error OnlyMutators(); error OnlyOwnerMinter(); } // // 35303437363833303632353737373262343336613738366635613537343636623530363736663637343934343738333036313538353237333561353433353534363434373536366535393537333537363561333334613638363334373638333534393435333937353632343736633735356135343737373636343437366333303632343735353262343336393431363735303437373837303632366437333637363336643536373335303533346137613634343836633733356135383465366635613537353633303439363934323666363336643536366435303533346136663634343835323737363337613666373634633332333136383635343734653662363236393335363936323332333933303633333335323739353935383432366135613437333437353539333233393734346333323461373636323333353237613634343834613638363334333338376134633661346437353464353333393661363333333464373635393664333937363634343834653330363336643436373734633664333137303632363933353661363333333464363935303637366633383463333236383663353935373531326234333661373836393632333235323335353036373666363734393434373836623631353835393637353933323738363836333333346433393439366434653736363236653532363836313537333536633633363934393262343336393431363734393433343133383561343736633332343934373465373335393538346537613530353334613737353935373634366334633537363836633539353735323663363336393439326234333639343136373439343334313637343934343738366634643534333535343634343735363665353935373335373635613333346136383633343736383335343934353339373536323437366337353561353437373736363134343435326234333639343136373439343334313338346333323532373036343661333434623433363934313637343934333431333836343537373736373539333237383638363333333464333934393664333536383634363934323735353935383539373436343437343636393633373934393637363135373531333934393665353236383539366534643639343934373532363836343437343537343634343734363639363337613330363936343437343636393633373934393262343336393431363734393433343136373439343437383733363135333432373936323332373836633530353334613737363336643536376135613537333533303539353835323730363233323334363934393437346537333539353834653761353035333461363835393333353237303634366435353639353036393431333835393533343236663633366435363664353035333439366135613537333536613632333235323663343936393432366235393538353236383463353835323736356133323634373335613534333036393634343734363639343936613335343636323664346537363561343735353338346333323435326235303433333937333631353433343462343934333431363734393433343136373530343737383730343934383461373636323437353533393439366534323739356135383465366336323665353236383634343736633736363236393439326234393434373836383439343736383739356135373539333934393639346536623561353734653736356134373535363934393437353236383634343734353734363434373339366535613332373836633530353334613330353935373439363935303662353236633539333233393662356135343737373635393534333433383463333237383730353036373666363734393433343136373530343333393331363234343334346234333639343136373439343334313338356134373663333234393437366336623530353334613734363535333331333035393537343937343539333233393735363434373536373536343433343936373539333237383638363333333464333934393665353236383539363933313661363233323335333035613537333533303439366133343462343934333431363734393433343136373530343735323730363436393432366136323437343637613633376133303639363434373436363934633538343236383632366435353637353935373465333036313538356136633439363934323730356134343330363935613537333536613632333235323663343936613334346234393433343136373439343334313637343934333431333835613437366333323530363736663637343934333431363734393433343136373439343334313637353034373637373935303662353637353539333233393662356135333432373435613538346537613539353736343663353034333339366634643661333434623439343334313637343934333431363734393433343136373439343437383737343934373465373335393538346537613530353334613638363234373536373936343433343236383632343735363739363434333331373036323664356137363439366133343462343934333431363734393433343136373439343334313637343934333431363735363437333836373561353733353661363233323532366334393437343536373632353735363761363333323436366535613533343237303632366535323736343934373436373534393437366337343539353736343663346334333432366136313437333937363633333235353637363434373638366334393437366337343539353736343663343934383663373636343533343233333539353733353330343934383532373634393438353637613561353337373637356135373335333035613538343936373635353733393331363336393432333035613538363833303439343734363735356134333432366636313538353136373634343736383663343934343738376136343438346137363632366436333262353235373335366136323332353236633530343333393761363434383461373636323664363332623439343734613331363434383532373636323639333436373530343734613739346337613334346234393433343136373439343334313637343934333431363734393433343136373535333234363332356135333432333036313437353536373632343734363761363434333432373036323537343636653561353337373637363135383531363736343332366337333632343334323661363233323335333035393537366337353439343836633736363435383439363736313437366336623561343735363735343934373331366336333333346536383561333235353735343934343738363936333639333832623433363934313637343934333431363734393433343136373439343334313637343934363461366336323537353637343539366435363739346334333432333036313437353536373632353733393739356135333432333035613538363833303439343836633736363435333432333335393537333533303439343835323736343934373638373035613437353537333439343835323666356135333432373335393538346136653561353834393637363434373638366334393437366337343539353736343663343934373638363836333739343233303632373934323639356135333334363735333537333436373539333234363761356135333432333536323333353536373539333236383736363333323535363735393537333436373631353733313638356133323535363736343437363836383634343334323730363337393432333036323332333836373633333233313638363234373737363736343437333836373631343733393733356134333432333536323333353637393439343733313663363333333465363835613332353536373635353733393331343934383634373036323437373736373539366435353637363135373335366436323333346137343561353735313735353034373461373934633761333433383539366534393736353036373666363734393433343136373439343334313637343934333431363734393433343234663561353736633330363134373536373934393438353236663561353334323730363235373436366535613533343237353632333334393637363434373638366334393437333136633633333334653638356133323535363736353537333933313439343736383730356134373535363736343332366337333632343334323639356135333432363836343433343236383632366536623637363235373339373435613537333533303439343835323739353935373335376136323537366333303634343735363662343934373339333235613538343936373634343736383663343934383634366335393639373736373539353737383733343934383532366635613533343237343539353736343730353937393432366635393538343237373561353733353761343934383634373036343437363837303632363934323335363233333536373934393437346137393632333336343761356135383439373534333639343136373439343334313637343934333431363734393433343133383463333334313262343336393431363734393433343136373439343334313637343934333431333835613664333937393632353334323661363234373436376136333761333036393561366433393739363235333439326234333639343136373439343334313637343934333431363734393433343136373439343437383662363135383539363735393332373836383633333334643339343936643561373636333664333037343561333334613736363435383431363935303637366636373439343334313637343934333431363734393433343136373439343334313637343934343738373036323665343233313634343334323661363234373436376136333761333036393561366433393739363235333331366136323332333533303633366433393733343936393432333036353538343236633530353334613664363135373738366334393639343237353539353733313663353035333461363935393538346536633532366436633733356135333439363736323332333536613631343734363735356133323535333934393665343237393561353835613730356135383634343636323664346537363561343735363461363235373436366535613533363737303439366133343462343934333431363734393433343136373439343334313637343934333431363735303433333936623631353835393262343336373666363734393433343136373439343334313637343934333431363734393433343133383561343736633332343934373465373335393538346537613530353334613664363233333461373434633537363437393632333335363737343936613334346234393433343136373439343334313637343934333431363734393433343136373439343334313338363434373536333436343437343637393561353734353637353933323738363836333333346433393439366435613736363336643330373435393332333937353634343834613736363234333432373435613538346537613539353736343663343936393432373936323333363437613530353334393761343936393432373736323437343636613561353736383736363234373532366336333661333036393532353733353330356135383439363736353537333933313633363934323734356135383465376135393537363436633439343736383663363336643535363935303661373737363634343735363334363434373436373935613537343532623433363934313637343934333431363734393433343136373439343334313637343934343737373635613437366333323530363736663462343934333431363734393433343136373439343334313637343934333431363735303437353237303634363934323661363234373436376136333761333036393561366433393739363235333331366536333664333933313633343334393262343336393431363734393433343136373439343334313637343934333431363734393433343136373530343734613331363434383532373636323639343236613632343734363761363337613330363935613537333536613632333235323663343934373461333036323639343236393634343733343734356134373536366435393538353637333634343334323737363435373738373334633538346137303561333236383330343936393432373636323664346537333631353734653732353035333461366336323664346537363561343735363465356135383465376135393537363436633462343336623639353036623536373535393332333936623561353437373736353936653536333036343437333937353530363736663637343934333431363734393433343136373439343334313637343934333431333834633332353237303634366133343462343934333431363734393433343136373439343334313637343934343737373635613664333937393632353433343462343934333431363734393433343136373439343334313637343934343738366236313538353936373539333237383638363333333464333934393664346537333561353734363739356136643663333434393661333433383463333235323730363436613334346234393433343136373439343334313637343934333431333834633332353237303634366133343462343336393431363734393433343136373439343334313637353034373532373036343639343236613632343734363761363337613330363935613538346137393632333334393639343934383465333036353537373836633530353334613662363135383465373736323437343633353466363934323735363233323335366334663739343932623530343333393662363135383539326234333639343136373439343334313637343934333431363735303437353237303634363934323661363234373436376136333761333036393539366436633735353935383461333534393639343237613634343836633733356135343330363935613437366337613633343737383638363535343666363736323664333937353561353437333639353036373666363734393433343136373439343334313637343934333431363735303437363737613530366234613730363236643436373936353533343237393561353834323739356135383465366336323665353236383634343736633736363236393432373635613639343233353632333335363739343934373331366336333333346536383561333235353338346333323637376135303637366636373439343334313637343934333431363734393433343136373530343835323663363534383532363836333664353636383439343734653733353935383465376135303533346136643632333334613734346335373465373636323665353237393632333237373637363235373536376136333332343636653561353334393637363333333532333536323437353533393439366536343736363336643531373436343333346136383633343437303639363336643536363836313739333133333632333334613662346637393439326234333639343136373439343334313637343934333431363734393433343133383463333335323663363534383532363836333664353636383530363736663637343934333431363734393433343136373439343437373736356134373663333235303637366636373439343334313637343934333431363734393434373836623631353835393637353933323738363836333333346433393439366436633734353935373634366336333739343936373633333335323335363234373535333934393664353237303633333334323733353935383662333634393437333537363632366435353337343936613334346234393433343136373439343334313637343934333431363734393434373836623631353835393637353933323738363836333333346433393439366433393739363135373634373036323664343637333439363934323761363434383663373335613534333036393561343736633761363334373738363836353534366636373632366433393735356135343733363935303637366636373439343334313637343934333431363734393433343136373439343334313338363134343464326235343333346137303561333236633735353935373737333834633332363737613530363736663637343934333431363734393433343136373439343334313637343934333431333835393332343637353634366434363761353036613737373635393332343637353634366434363761353036373666363734393433343136373439343334313637343934333431363735303433333936623631353835393262343336393431363734393433343136373439343334313637343934333431333835613437366333323439343734653733353935383465376135303533346137353634353737383733356135373531363934393438346533303635353737383663353035333461366236313538346537373632343734363335346636393432373536323332333536633466373934393262343336393431363734393433343136373439343334313637343934333431363734393434373836663464376133353466363233333461373435393537373837303635366435363662353034333339366634643761333434623439343334313637343934333431363734393433343136373439343334313637353034373465363836323665356136383633376133343338346333323465363836323665356136383633376133343462343934333431363734393433343136373439343334313637343934343737373635613437366333323530363736663637343934333431363734393433343136373439343334313637353034373532373036343639343236613632343734363761363337613330363936323537353637613633333234363665356135333439363736333333353233353632343735353339343936643532373036333333343237333539353836623336343934373335373636323664353533373439366133343462343934333431363734393433343136373439343334313637343934333431363735303437363737613530366233313663363333333465363835613332353536373631343736633662356134373536373534393437366337353439343736633734353935373634366334393433363837393631353736343666363434333432366136323437366336613631373934313338363333333432363836323639343236613632343734363761363337613330363935613332373833353633343736383730353933323339373534393437363437333635353834323666363135373465373636323639333136383633366534613736363437393331373936313537363436663634343334393262353034333339376136333437343637353530363934323761353935383561366334393437343637613462353437373736363134343464326234333639343136373439343334313637343934333431363734393433343136373439343437383661353935373335333235393538346432623530343333393661353935373335333235393538346432623433363934313637343934333431363734393433343136373439343334313338346333323532373036343661333434623439343334313637343934333431363734393433343133383463333235323730363436613334346234393433343136373439343334313637353034333339366236313538353932623433363736663637343934333431363734393433343133383561343736633332343934373465373335393538346537613530353334613330353935373439373436333437343637353561353334393637363135373531333934393664353236633539333233393662356135333439326234333639343136373439343334313637343934333431363735303437353237303634366133343462343934333431363734393433343136373439343334313637343934343738366634643661333534353561353734653736356134373535363736313537333136383561333235353338346333323637373935303637366636373439343334313637343934333431363734393433343136373530343834313637353933323738363836333333346433393439366434363733356135383461333034393437343637333561353834613330346335373663373535613664333836393530363736663637343934333431363734393433343136373439343334313637343934333432353536323739343236623561353734653736356134373535363735393533343236663631353735323662356135373334363736323537353637613633333234363665356135333432366436333664333937343439343734363735343934373663373435393537363436633463343334323731363435383465333034393437346536663632333233393761356135333432363836323639343237303632353734363665356135333432363836323664353136373631343736633330343934383532366635613533343133383633333335323739363233323335366535303662353236633539333233393662356135343737373636333333353237393632333233353665353036393432363936343538353233303632333233343735353034373461373934633761333433383539366534393736353036373666363734393433343136373439343334313637343934333431363734393433343234663561353736633330363134373536373934393438353236663561353334323730363235373436366535613533343237353632333334393637363434373638366334393437333136633633333334653638356133323535363736343437363836383634343334323666353935383464363735393664353636633632363934323666363135373532366235613537333436373634333236633733363234333432363935613533343236383634343334323638363236653662363736323537333937343561353733353330343934383532373935393537333537613632353736633330363434373536366234393437333933323561353834393637363434373638366334393438363436633539363937373637353935373738373334393438353236663561353334323734353935373634373035393739343236663539353834323737356135373335376134393438363437303634343736383730363236393432333536323333353637393439343734613739363233333634376135613538343937353433363934313637343934333431363734393433343136373439343334313338346333333431326234333639343136373439343334313637343934333431363734393433343133383561366433393739363235333432366136323437343637613633376133303639356136643339373936323533343932623433363934313637343934333431363734393433343136373439343334313637343934343738366236313538353936373539333237383638363333333464333934393664356137363633366433303734356133333461373636343538343136393530363736663637343934333431363734393433343136373439343334313637343934333431363734393434373837303632366534323331363434333432366136323437343637613633376133303639356136643339373936323533333136613632333233353330363336643339373334393639343233303635353834323663353035333461366436313537373836633439363934323735353935373331366335303533346136623561353734653736356134373536343736313537373836633439363934323736363236643465366635393537333536653561353433303639363334383461366336343664366336633634333035323663353933323339366235613535366337343539353736343663346234333662363935303637366636373439343334313637343934333431363734393433343136373439343334313338346333323532373036343661333434623439343334313637343934333431363734393433343136373439343334313637353034373532373036343639343236613632343734363761363337613330363935613664333937393632353333313665363336643339333136333433343932623433363934313637343934333431363734393433343136373439343334313637343934333431363735303437346133313634343835323736363236393432366136323437343637613633376133303639356134373536366136323332353236633439343734613330363236393432363936343437333437343561343735363664353935383536373336343433343237373634353737383733346335383461373035613332363833303439363934323736363236643465373336313537346537323530353334613662356135373465373635613437353634653561353834653761353935373634366334623433366236393530366235323663353933323339366235613534373737363539366535363330363434373339373535303637366636373439343334313637343934333431363734393433343136373439343334313338346333323532373036343661333434623439343334313637343934333431363734393433343136373439343437373736356136643339373936323534333434623439343334313637343934333431363734393433343136373439343437383662363135383539363735393332373836383633333334643339343936643465373335613537343637393561366436633334343936613334333834633332353237303634366133343462343934333431363734393433343136373439343334313338346333323532373036343661333434623439343334313637343934333431363734393433343133383561343736633332343934373465373335393538346537613530353334613639363135373335363836333665366237343561343735363661363233323532366334393639343237613634343836633733356135343330363935613437366337613633343737383638363535343666363736323664333937353561353437333639353036373666363734393433343136373439343334313637343934333431363735303437363737613530366236383730356134373532366336323639343237343561353834653761353935373634366335303433333936663464376133343462343934333431363734393433343136373439343334313637343934343738333035613538363833303539353834613663353935333432366136323437343637613633376133303639356136643339373936323533333136613632333233353330363336643339373334393437333136633633333334653638356133323535363934393438346533303635353737383663353035333461333336323333346136623463353836343739353935383431333635393665346136633539353737333734363433323339373935613434373336393530363736663637343934333431363734393433343136373439343334313637353034333339333035613538363833303539353834613663353935343334346234393433343136373439343334313637343934333431333834633332353237303634366133343462343934333431363734393433343136373439343334313338356134373663333234393437346537333539353834653761353035333461366235613537346537363561343735353639343934383465333036353537373836633530353334613662363135383465373736323437343633353466363934323735363233323335366334663739343932623433363934313637343934333431363734393433343136373439343334313338363134343464326235333537333537373634353835313338346333323637376135303637366636373439343334313637343934333431363734393433343136373530343734653638363236653561363836333761333433383463333234653638363236653561363836333761333434623439343334313637343934333431363734393433343133383463333235323730363436613334346234393433343136373439343334313637353034333339366236313538353932623433363736663637343934333431363735303433333936623631353835393262343336373666363734393433343136373530343735613736363233333532366336333639343237613634343836633733356135343330363936343437353633343634343333313638363234373663366536323661366636373539333235363735363434373536373934663739343237343539353834613665363135373334373436343437333937373466363934313739346434383432333434663739343237343539353834613665363135373334373435393664333933303634343733393734346636393431373834643438343233343466373934393262343336393431363734393433343136373439343335613661363233333432333534663739343137393464343434353330343934373461333534393434373836383439343736383739356135373539333934393664333136383631353737383330363237613730376136343438366337333561353834653331363534383638343135613332333136383631353737373735353933323339373434393661333537613634343836633733356135383465333136353438363733383463333234353262343336393431363734393433343133383463333235613736363233333532366336333661333434623439343334313338346333323532373036343661333434623433363934313637353034383465333036353537373836633530363736663637343934333431363735393332343637353634366434363761343934383733346234393433343136373439343334313637363235373436333434633538363437303561343835323666346636393431373834643434343136633466373736663637343934333431363736363531366636373439343437373736363333333532333536323437353532623433363736663637343934343738376135393333346137303633343835313637363333333461366135303533346136663634343835323737363337613666373634633332343637313539353836373735356133323339373635613332373836633539353834323730363337393335366136323332333037363539353737303638363534333339373336313537346137613463333237303738363435373536373936353533333837383463366134353738346336613435373636313665343633313561353834613335346336643331373036323639333537313633373934393262353034333339376135393333346137303633343835313262343336393431363735303438346536613633366436633737363434333432376136333664346433393439366436383330363434383432376134663639333837363632353734363334353933323532373534633664346137363632333335323761363434383461363836333437346536623632363933353661363233323330373635393664333937363634343834653330363336643436373734633761346437353464373933343738346333323730376134633332346137363632333335323761363434383461363836333433333537343631353733343735363136653464363935303661373737363633333234653739363135383432333035303637366636373439343437383761353933333461373036333438353136373634343836633737356135343330363936343437353633343634343333393462353935383561363835353332346537393631353834323330343936393432376136333664346433393439366534653661363336643663373736343433333537313633373934393262353034333339376135393333346137303633343835313262343336613737373635393664333936623635353433343462353034333339366636343437333137333530363736663364 // SPDX-License-Identifier: MIT // Copyright (c) 2022 the aura.lol authors // Author David Huber (@cxkoda) pragma solidity >=0.8.0 <0.9.0; import "../TokenData.sol"; interface IManifestRenderer { /// @notice Returns the metadata uri for a given token function tokenURI(uint256 tokenId, TokenData memory tokenData) external pure returns (string memory); } // SPDX-License-Identifier: MIT // Copyright (c) 2022 the aura.lol authors // Author David Huber (@cxkoda) pragma solidity >=0.8.0 <0.9.0; /// @dev Data struct that will be passed to the rendering contract struct TokenData { uint256 mintTimestamp; uint96 generation; address originalOwner; bytes[] data; } // SPDX-License-Identifier: MIT // Copyright 2021 David Huber (@cxkoda) pragma solidity >=0.8.0 <0.9.0; import "./IERC2981.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @notice ERC2981 royalty info base contract * @dev Implements `supportsInterface` */ abstract contract ERC2981 is IERC2981, ERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // Copyright 2021 David Huber (@cxkoda) pragma solidity >=0.8.0 <0.9.0; import "./ERC2981.sol"; /** * @notice ERC2981 royalty info implementation for a single beneficiary * receving a percentage of sales prices. * @author David Huber (@cxkoda) */ contract ERC2981SinglePercentual is ERC2981 { /** * @dev The royalty percentage (in units of 0.01%) */ uint96 _percentage; /** * @dev The address to receive the royalties */ address _receiver; /** * @dev See {IERC2981-royaltyInfo}. */ function royaltyInfo(uint256, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { royaltyAmount = (salePrice / 10000) * _percentage; receiver = _receiver; } /** * @dev Sets the royalty percentage (in units of 0.01%) */ function _setRoyaltyPercentage(uint96 percentage_) internal { _percentage = percentage_; } /** * @dev Sets the address to receive the royalties */ function _setRoyaltyReceiver(address receiver_) internal { _receiver = receiver_; } } // SPDX-License-Identifier: None pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard * @author Taken from https://eips.ethereum.org/EIPS/eip-2981 */ interface IERC2981 is IERC165 { /** * @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); }
Mints new tokens for the recipient.
function _processMint(address to, uint16 num) private { if (num + totalSupply > MAX_NUM_TOKENS) revert InsufficientTokensRemanining(); uint256 tokenId = totalSupply; totalSupply += num; for (uint256 i = 0; i < num; i++) { tokenData[tokenId] = TokenData({ originalOwner: to, generation: 0, mintTimestamp: block.timestamp, data: new bytes[](0) }); ERC721._safeMint(to, tokenId, ""); ++tokenId; } }
1,449,871
// 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; 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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.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 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../dispatcher/IDispatcher.sol"; /// @title AddressListRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A contract for creating and updating lists of addresses contract AddressListRegistry { enum UpdateType {None, AddOnly, RemoveOnly, AddAndRemove} event ItemAddedToList(uint256 indexed id, address item); event ItemRemovedFromList(uint256 indexed id, address item); event ListAttested(uint256 indexed id, string description); event ListCreated( address indexed creator, address indexed owner, uint256 id, UpdateType updateType ); event ListOwnerSet(uint256 indexed id, address indexed nextOwner); event ListUpdateTypeSet( uint256 indexed id, UpdateType prevUpdateType, UpdateType indexed nextUpdateType ); struct ListInfo { address owner; UpdateType updateType; mapping(address => bool) itemToIsInList; } address private immutable DISPATCHER; ListInfo[] private lists; modifier onlyListOwner(uint256 _id) { require(__isListOwner(msg.sender, _id), "Only callable by list owner"); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; // Create the first list as completely empty and immutable, to protect the default `id` lists.push(ListInfo({owner: address(0), updateType: UpdateType.None})); } // EXTERNAL FUNCTIONS /// @notice Adds items to a given list /// @param _id The id of the list /// @param _items The items to add to the list function addToList(uint256 _id, address[] calldata _items) external onlyListOwner(_id) { UpdateType updateType = getListUpdateType(_id); require( updateType == UpdateType.AddOnly || updateType == UpdateType.AddAndRemove, "addToList: Cannot add to list" ); __addToList(_id, _items); } /// @notice Attests active ownership for lists and (optionally) a description of each list's content /// @param _ids The ids of the lists /// @param _descriptions The descriptions of the lists' content /// @dev Since UserA can create a list on behalf of UserB, this function provides a mechanism /// for UserB to attest to their management of the items therein. It will not be visible /// on-chain, but will be available in event logs. function attestLists(uint256[] calldata _ids, string[] calldata _descriptions) external { require(_ids.length == _descriptions.length, "attestLists: Unequal arrays"); for (uint256 i; i < _ids.length; i++) { require( __isListOwner(msg.sender, _ids[i]), "attestLists: Only callable by list owner" ); emit ListAttested(_ids[i], _descriptions[i]); } } /// @notice Creates a new list /// @param _owner The owner of the list /// @param _updateType The UpdateType for the list /// @param _initialItems The initial items to add to the list /// @return id_ The id of the newly-created list /// @dev Specify the DISPATCHER as the _owner to make the Enzyme Council the owner function createList( address _owner, UpdateType _updateType, address[] calldata _initialItems ) external returns (uint256 id_) { id_ = getListCount(); lists.push(ListInfo({owner: _owner, updateType: _updateType})); emit ListCreated(msg.sender, _owner, id_, _updateType); __addToList(id_, _initialItems); return id_; } /// @notice Removes items from a given list /// @param _id The id of the list /// @param _items The items to remove from the list function removeFromList(uint256 _id, address[] calldata _items) external onlyListOwner(_id) { UpdateType updateType = getListUpdateType(_id); require( updateType == UpdateType.RemoveOnly || updateType == UpdateType.AddAndRemove, "removeFromList: Cannot remove from list" ); // Silently ignores items that are not in the list for (uint256 i; i < _items.length; i++) { if (isInList(_id, _items[i])) { lists[_id].itemToIsInList[_items[i]] = false; emit ItemRemovedFromList(_id, _items[i]); } } } /// @notice Sets the owner for a given list /// @param _id The id of the list /// @param _nextOwner The owner to set function setListOwner(uint256 _id, address _nextOwner) external onlyListOwner(_id) { lists[_id].owner = _nextOwner; emit ListOwnerSet(_id, _nextOwner); } /// @notice Sets the UpdateType for a given list /// @param _id The id of the list /// @param _nextUpdateType The UpdateType to set /// @dev Can only change to a less mutable option (e.g., both add and remove => add only) function setListUpdateType(uint256 _id, UpdateType _nextUpdateType) external onlyListOwner(_id) { UpdateType prevUpdateType = getListUpdateType(_id); require( _nextUpdateType == UpdateType.None || prevUpdateType == UpdateType.AddAndRemove, "setListUpdateType: _nextUpdateType not allowed" ); lists[_id].updateType = _nextUpdateType; emit ListUpdateTypeSet(_id, prevUpdateType, _nextUpdateType); } // PRIVATE FUNCTIONS /// @dev Helper to add items to a list function __addToList(uint256 _id, address[] memory _items) private { for (uint256 i; i < _items.length; i++) { if (!isInList(_id, _items[i])) { lists[_id].itemToIsInList[_items[i]] = true; emit ItemAddedToList(_id, _items[i]); } } } /// @dev Helper to check if an account is the owner of a given list function __isListOwner(address _who, uint256 _id) private view returns (bool isListOwner_) { address owner = getListOwner(_id); return _who == owner || (owner == getDispatcher() && _who == IDispatcher(getDispatcher()).getOwner()); } ///////////////// // LIST SEARCH // ///////////////// // These functions are concerned with exiting quickly and do not consider empty params. // Developers should sanitize empty params as necessary for their own use cases. // EXTERNAL FUNCTIONS // Multiple items, single list /// @notice Checks if multiple items are all in a given list /// @param _id The list id /// @param _items The items to check /// @return areAllInList_ True if all items are in the list function areAllInList(uint256 _id, address[] memory _items) external view returns (bool areAllInList_) { for (uint256 i; i < _items.length; i++) { if (!isInList(_id, _items[i])) { return false; } } return true; } /// @notice Checks if multiple items are all absent from a given list /// @param _id The list id /// @param _items The items to check /// @return areAllNotInList_ True if no items are in the list function areAllNotInList(uint256 _id, address[] memory _items) external view returns (bool areAllNotInList_) { for (uint256 i; i < _items.length; i++) { if (isInList(_id, _items[i])) { return false; } } return true; } // Multiple items, multiple lists /// @notice Checks if multiple items are all in all of a given set of lists /// @param _ids The list ids /// @param _items The items to check /// @return areAllInAllLists_ True if all items are in all of the lists function areAllInAllLists(uint256[] memory _ids, address[] memory _items) external view returns (bool areAllInAllLists_) { for (uint256 i; i < _items.length; i++) { if (!isInAllLists(_ids, _items[i])) { return false; } } return true; } /// @notice Checks if multiple items are all in one of a given set of lists /// @param _ids The list ids /// @param _items The items to check /// @return areAllInSomeOfLists_ True if all items are in one of the lists function areAllInSomeOfLists(uint256[] memory _ids, address[] memory _items) external view returns (bool areAllInSomeOfLists_) { for (uint256 i; i < _items.length; i++) { if (!isInSomeOfLists(_ids, _items[i])) { return false; } } return true; } /// @notice Checks if multiple items are all absent from all of a given set of lists /// @param _ids The list ids /// @param _items The items to check /// @return areAllNotInAnyOfLists_ True if all items are absent from all lists function areAllNotInAnyOfLists(uint256[] memory _ids, address[] memory _items) external view returns (bool areAllNotInAnyOfLists_) { for (uint256 i; i < _items.length; i++) { if (isInSomeOfLists(_ids, _items[i])) { return false; } } return true; } // PUBLIC FUNCTIONS // Single item, multiple lists /// @notice Checks if an item is in all of a given set of lists /// @param _ids The list ids /// @param _item The item to check /// @return isInAllLists_ True if item is in all of the lists function isInAllLists(uint256[] memory _ids, address _item) public view returns (bool isInAllLists_) { for (uint256 i; i < _ids.length; i++) { if (!isInList(_ids[i], _item)) { return false; } } return true; } /// @notice Checks if an item is in at least one of a given set of lists /// @param _ids The list ids /// @param _item The item to check /// @return isInSomeOfLists_ True if item is in one of the lists function isInSomeOfLists(uint256[] memory _ids, address _item) public view returns (bool isInSomeOfLists_) { for (uint256 i; i < _ids.length; i++) { if (isInList(_ids[i], _item)) { return true; } } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the total count of lists /// @return count_ The total count function getListCount() public view returns (uint256 count_) { return lists.length; } /// @notice Gets the owner of a given list /// @param _id The list id /// @return owner_ The owner function getListOwner(uint256 _id) public view returns (address owner_) { return lists[_id].owner; } /// @notice Gets the UpdateType of a given list /// @param _id The list id /// @return updateType_ The UpdateType function getListUpdateType(uint256 _id) public view returns (UpdateType updateType_) { return lists[_id].updateType; } /// @notice Checks if an item is in a given list /// @param _id The list id /// @param _item The item to check /// @return isInList_ True if the item is in the list function isInList(uint256 _id, address _item) public view returns (bool isInList_) { return lists[_id].itemToIsInList[_item]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../utils/AddressListRegistryPolicyBase.sol"; /// @title AllowedAssetsForRedemptionPolicy Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that limits assets that can be redeemed by specific asset redemption contract AllowedAssetsForRedemptionPolicy is AddressListRegistryPolicyBase { constructor(address _policyManager, address _addressListRegistry) public AddressListRegistryPolicyBase(_policyManager, _addressListRegistry) {} // EXTERNAL FUNCTIONS /// @notice Whether or not the policy can be disabled /// @return canDisable_ True if the policy can be disabled function canDisable() external pure virtual override returns (bool canDisable_) { return true; } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ALLOWED_ASSETS_FOR_REDEMPTION"; } /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external pure override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets; return implementedHooks_; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes /// @dev onlyPolicyManager validation not necessary, as state is not updated and no events are fired function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , , address[] memory assets, , ) = __decodeRedeemSharesForSpecificAssetsValidationData( _encodedArgs ); return passesRule(_comptrollerProxy, assets); } // PUBLIC FUNCTIONS /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { return AddressListRegistry(getAddressListRegistry()).areAllInSomeOfLists( getListIdsForFund(_comptrollerProxy), _assets ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../persistent/address-list-registry/AddressListRegistry.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../utils/PolicyBase.sol"; /// @title AddressListRegistryPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base contract inheritable by any policy that uses the AddressListRegistry abstract contract AddressListRegistryPolicyBase is PolicyBase { event ListsSetForFund(address indexed comptrollerProxy, uint256[] listIds); address private immutable ADDRESS_LIST_REGISTRY; mapping(address => uint256[]) private comptrollerProxyToListIds; constructor(address _policyManager, address _addressListRegistry) public PolicyBase(_policyManager) { ADDRESS_LIST_REGISTRY = _addressListRegistry; } // EXTERNAL FUNCTIONS /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external virtual override onlyPolicyManager { __updateListsForFund(_comptrollerProxy, _encodedSettings); } // INTERNAL FUNCTIONS /// @dev Helper to create new list from encoded data function __createAddressListFromData(address _vaultProxy, bytes memory _newListData) internal returns (uint256 listId_) { ( AddressListRegistry.UpdateType updateType, address[] memory initialItems ) = __decodeNewListData(_newListData); return AddressListRegistry(getAddressListRegistry()).createList( _vaultProxy, updateType, initialItems ); } /// @dev Helper to decode new list data function __decodeNewListData(bytes memory _newListData) internal pure returns (AddressListRegistry.UpdateType updateType_, address[] memory initialItems_) { return abi.decode(_newListData, (AddressListRegistry.UpdateType, address[])); } /// @dev Helper to set the lists to be used by a given fund. /// This is done in a simple manner rather than the most gas-efficient way possible /// (e.g., comparing already-stored items with an updated list would save on storage operations during updates). function __updateListsForFund(address _comptrollerProxy, bytes calldata _encodedSettings) internal { (uint256[] memory existingListIds, bytes[] memory newListsData) = abi.decode( _encodedSettings, (uint256[], bytes[]) ); uint256[] memory nextListIds = new uint256[](existingListIds.length + newListsData.length); require(nextListIds.length != 0, "__updateListsForFund: No lists specified"); // Clear the previously stored list ids as needed if (comptrollerProxyToListIds[_comptrollerProxy].length > 0) { delete comptrollerProxyToListIds[_comptrollerProxy]; } // Add existing list ids. // No need to validate existence, policy will just fail if out-of-bounds index. for (uint256 i; i < existingListIds.length; i++) { nextListIds[i] = existingListIds[i]; comptrollerProxyToListIds[_comptrollerProxy].push(existingListIds[i]); } // Create and add any new lists if (newListsData.length > 0) { address vaultProxy = ComptrollerLib(_comptrollerProxy).getVaultProxy(); for (uint256 i; i < newListsData.length; i++) { uint256 nextListIdsIndex = existingListIds.length + i; nextListIds[nextListIdsIndex] = __createAddressListFromData( vaultProxy, newListsData[i] ); comptrollerProxyToListIds[_comptrollerProxy].push(nextListIds[nextListIdsIndex]); } } emit ListsSetForFund(_comptrollerProxy, nextListIds); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_LIST_REGISTRY` variable value /// @return addressListRegistry_ The `ADDRESS_LIST_REGISTRY` variable value function getAddressListRegistry() public view returns (address addressListRegistry_) { return ADDRESS_LIST_REGISTRY; } /// @notice Gets the list ids used by a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return listIds_ The list ids function getListIdsForFund(address _comptrollerProxy) public view returns (uint256[] memory listIds_) { return comptrollerProxyToListIds[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address) external virtual override { return; } /// @notice Whether or not the policy can be disabled /// @return canDisable_ True if the policy can be disabled /// @dev False by default, can be overridden by the policy function canDisable() external pure virtual override returns (bool canDisable_) { return false; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings(address, bytes calldata) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } ////////////////////////////// // VALIDATION DATA DECODING // ////////////////////////////// /// @dev Helper to parse validation arguments from encoded data for AddTrackedAssets policy hook function __decodeAddTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /// @dev Helper to parse validation arguments from encoded data for CreateExternalPosition policy hook function __decodeCreateExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, uint256 typeId_, bytes memory initializationData_ ) { return abi.decode(_validationData, (address, uint256, bytes)); } /// @dev Helper to parse validation arguments from encoded data for PreTransferShares policy hook function __decodePreTransferSharesValidationData(bytes memory _validationData) internal pure returns ( address sender_, address recipient_, uint256 amount_ ) { return abi.decode(_validationData, (address, address, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostBuyShares policy hook function __decodePostBuySharesValidationData(bytes memory _validationData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesIssued_, uint256 gav_ ) { return abi.decode(_validationData, (address, uint256, uint256, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnExternalPosition policy hook function __decodePostCallOnExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, address externalPosition_, address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_, bytes memory encodedActionData_ ) { return abi.decode( _validationData, (address, address, address[], uint256[], address[], bytes) ); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnIntegration policy hook function __decodePostCallOnIntegrationValidationData(bytes memory _validationData) internal pure returns ( address caller_, address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_ ) { return abi.decode( _validationData, (address, address, bytes4, address[], uint256[], address[], uint256[]) ); } /// @dev Helper to parse validation arguments from encoded data for ReactivateExternalPosition policy hook function __decodeReactivateExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RedeemSharesForSpecificAssets policy hook function __decodeRedeemSharesForSpecificAssetsValidationData(bytes memory _validationData) internal pure returns ( address redeemer_, address recipient_, uint256 sharesToRedeemPostFees_, address[] memory assets_, uint256[] memory assetAmounts_, uint256 gavPreRedeem_ ) { return abi.decode( _validationData, (address, address, uint256, address[], uint256[], uint256) ); } /// @dev Helper to parse validation arguments from encoded data for RemoveExternalPosition policy hook function __decodeRemoveExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RemoveTrackedAssets policy hook function __decodeRemoveTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Helper to check if an account is the owner of a given list
function __isListOwner(address _who, uint256 _id) private view returns (bool isListOwner_) { address owner = getListOwner(_id); return _who == owner || (owner == getDispatcher() && _who == IDispatcher(getDispatcher()).getOwner()); }
6,867,469
./partial_match/42/0x7Dab59e2Ca3a043316C2039453989d8519756d92/sources/DisposableGovernance.sol
Gets ID return by the oraclize query of a given index. index Index. return myid ID return by the oraclize query./
function getApiCallIndex(uint index) external view returns (bytes32 myid) { myid = allAPIcall[index]; }
3,299,901
// 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); } } } } /** * @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); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableData { address public owner; address public pendingOwner; } abstract contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { require(newOwner != address(0) || renounce, "Ownable: zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } else { pendingOwner = newOwner; } } function claimOwnership() public { address _pendingOwner = pendingOwner; require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } contract StorageBuffer { // Reserved storage space to allow for layout changes in the future. uint256[20] private _gap; function getStore(uint a) internal view returns(uint) { require(a < 20, "Not allowed"); return _gap[a]; } function setStore(uint a, uint val) internal { require(a < 20, "Not allowed"); _gap[a] = val; } } // This contract is dedicated to process LP tokens of the users. More precisely, this allows Popsicle to track how much tokens // the user has deposited and indicate how much he is eligible to withdraw abstract contract LPTokenWrapper is StorageBuffer { using SafeERC20 for IERC20; // Address of ICE token IERC20 public immutable ice; // Address of LP token IERC20 public immutable lpToken; // Amount of Lp tokens deposited uint256 private _totalSupply; // A place where user token balance is stored mapping(address => uint256) private _balances; // Function modifier that calls update reward function modifier updateReward(address account) { _updateReward(account); _; } constructor(address _ice, address _lpToken) { require(_ice != address(0) && _lpToken != address(0), "NULL_ADDRESS"); ice = IERC20(_ice); lpToken = IERC20(_lpToken); } // View function that provides tptal supply for the front end function totalSupply() public view returns (uint256) { return _totalSupply; } // View function that provides the LP balance of a user function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // Fuction that is responsible for the recival of LP tokens of the user and the update of the user balance function stake(uint256 amount) virtual public { _totalSupply += amount; _balances[msg.sender] += amount; lpToken.safeTransferFrom(msg.sender, address(this), amount); } // Function that is reponsible for releasing LP tokens to the user and for the update of the user balance function withdraw(uint256 amount) virtual public { _totalSupply -= amount; _balances[msg.sender] -= amount; lpToken.safeTransfer(msg.sender, amount); } //Interface function _updateReward(address account) virtual internal; } /** * This contract is responsible fpr forwarding LP tokens to Masterchef contract. * It calculates ICE rewards and distrubutes both ICE and Sushi */ contract PopsicleJointStaking is LPTokenWrapper, Ownable { using SafeERC20 for IERC20; // Immutable Address of Sushi token IERC20 public immutable sushi; // Immutable masterchef contract address IMasterChef public immutable masterChef; uint256 public immutable pid; // sushi pool id // Reward rate - This is done to set ICE reward rate proportion. uint256 public rewardRate = 2000000; // Custom divisioner that is implemented in order to give the ability to alter rate reward according to the project needs uint256 public constant DIVISIONER = 10 ** 6; // Set of variables that is storing user Sushi rewards uint256 public sushiPerTokenStored; // Info of each user. struct UserInfo { uint256 remainingIceTokenReward; // Remaining Token amount that is owned to the user. uint256 sushiPerTokenPaid; uint256 sushiRewards; } // Info of each user that stakes ICE tokens. mapping(address => UserInfo) public userInfo; //mapping(address => uint256) public sushiPerTokenPaid; //mapping(address => uint256) public sushiRewards; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event SushiPaid(address indexed user, uint256 reward); constructor( address _ice, address _sushi, address _lpToken, address _masterChef, uint256 _pid ) LPTokenWrapper(_ice, _lpToken) { require( _sushi != address(0) && _masterChef != address(0), "NULL_ADDRESSES" ); sushi = IERC20(_sushi); masterChef = IMasterChef(_masterChef); pid = _pid; } // Function which tracks rewards of a user and harvests all sushi rewards from Masterchef function _updateReward(address account) override internal { UserInfo storage user = userInfo[msg.sender]; uint _then = sushi.balanceOf(address(this)); masterChef.withdraw(pid, 0); // harvests sushi sushiPerTokenStored = _sushiPerToken(sushi.balanceOf(address(this)) - _then); if (account != address(0)) { user.sushiRewards = _sushiEarned(account, sushiPerTokenStored); user.sushiPerTokenPaid = sushiPerTokenStored; } } // View function which shows sushi rewards amount of our Pool function sushiPerToken() public view returns (uint256) { return _sushiPerToken(masterChef.pendingSushi(pid, address(this))); } // Calculates how much sushi is provied per LP token function _sushiPerToken(uint earned_) internal view returns (uint256) { uint _totalSupply = totalSupply(); if (_totalSupply > 0) { return (sushiPerTokenStored + earned_) * 1e18 / _totalSupply; } return sushiPerTokenStored; } // View function which shows user ICE reward for displayment on frontend function earned(address account) public view returns (uint256) { UserInfo memory user = userInfo[account]; return _sushiEarned(account, sushiPerToken()) * rewardRate / DIVISIONER + user.remainingIceTokenReward; } // View function which shows user Sushi reward for displayment on frontend function sushiEarned(address account) public view returns (uint256) { return _sushiEarned(account, sushiPerToken()); } // Calculates how much sushi is entitled for a particular user function _sushiEarned(address account, uint256 sushiPerToken_) internal view returns (uint256) { UserInfo memory user = userInfo[account]; return balanceOf(account) * (sushiPerToken_ - user.sushiPerTokenPaid) / 1e18 + user.sushiRewards; } // stake visibility is public as overriding LPTokenWrapper's stake() function //Recieves users LP tokens and deposits them to Masterchef contract function stake(uint256 amount) override public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); lpToken.approve(address(masterChef), amount); masterChef.deposit(pid, amount); emit Staked(msg.sender, amount); } // Recieves Lp tokens from Masterchef and give it out to the user function withdraw(uint256 amount) override public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); masterChef.withdraw(pid, amount); // harvests sushi super.withdraw(amount); emit Withdrawn(msg.sender, amount); } // "Go home" function which withdraws all Funds and distributes all rewards to the user function exit() external { require(msg.sender != address(0)); UserInfo storage user = userInfo[msg.sender]; uint _then = sushi.balanceOf(address(this)); uint256 amount = balanceOf(msg.sender); require(amount > 0, "Cannot withdraw 0"); masterChef.withdraw(pid, amount); // harvests sushi sushiPerTokenStored = _sushiPerToken(sushi.balanceOf(address(this)) - _then); user.sushiRewards = _sushiEarned(msg.sender, sushiPerTokenStored); user.sushiPerTokenPaid = sushiPerTokenStored; super.withdraw(amount); emit Withdrawn(msg.sender, amount); uint256 reward = user.sushiRewards; if (reward > 0) { user.sushiRewards = 0; sushi.safeTransfer(msg.sender, reward); emit SushiPaid(msg.sender, reward); } reward = reward * rewardRate / DIVISIONER + user.remainingIceTokenReward; if (reward > 0) { user.remainingIceTokenReward = safeRewardTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } // Changes rewards rate of ICE token function setRewardRate(uint256 _rewardRate) external onlyOwner { rewardRate = _rewardRate; } // Harvests rewards to the user but leaves the Lp tokens deposited function getReward() public updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; uint256 reward = user.sushiRewards; if (reward > 0) { user.sushiRewards = 0; sushi.safeTransfer(msg.sender, reward); emit SushiPaid(msg.sender, reward); } reward = reward * rewardRate / DIVISIONER + user.remainingIceTokenReward; if (reward > 0) { user.remainingIceTokenReward = safeRewardTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } // Safe token distribution function safeRewardTransfer(address _to, uint256 _amount) internal returns(uint256) { uint256 rewardTokenBalance = ice.balanceOf(address(this)); if (rewardTokenBalance == 0) { //save some gas fee return _amount; } if (_amount > rewardTokenBalance) { //save some gas fee ice.transfer(_to, rewardTokenBalance); return _amount - rewardTokenBalance; } ice.transfer(_to, _amount); return 0; } } // Implemented to call functions of masterChef interface IMasterChef { function deposit(uint256 pid, uint256 amount) external; function withdraw(uint256 pid, uint256 amount) external; function pendingSushi(uint256 pid, address user) external view returns(uint); }
Changes rewards rate of ICE token
function setRewardRate(uint256 _rewardRate) external onlyOwner { rewardRate = _rewardRate; }
1,681,735
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.9; import { IERC20Metadata } from '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol'; import { ProxyAdmin } from '@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol'; import { IUniswapV3Pool } from '@uniswap/v3-core-0.8-support/contracts/interfaces/IUniswapV3Pool.sol'; import { IUniswapV3Factory } from '@uniswap/v3-core-0.8-support/contracts/interfaces/IUniswapV3Factory.sol'; import { ClearingHouseDeployer } from './clearinghouse/ClearingHouseDeployer.sol'; import { InsuranceFundDeployer } from './insurancefund/InsuranceFundDeployer.sol'; import { VQuoteDeployer } from './tokens/VQuoteDeployer.sol'; import { VTokenDeployer } from './tokens/VTokenDeployer.sol'; import { VToken } from './tokens/VToken.sol'; import { VPoolWrapperDeployer } from './wrapper/VPoolWrapperDeployer.sol'; import { IClearingHouse } from '../interfaces/IClearingHouse.sol'; import { IClearingHouseStructures } from '../interfaces/clearinghouse/IClearingHouseStructures.sol'; import { IInsuranceFund } from '../interfaces/IInsuranceFund.sol'; import { IOracle } from '../interfaces/IOracle.sol'; import { IVQuote } from '../interfaces/IVQuote.sol'; import { IVPoolWrapper } from '../interfaces/IVPoolWrapper.sol'; import { IVToken } from '../interfaces/IVToken.sol'; import { AddressHelper } from '../libraries/AddressHelper.sol'; import { PriceMath } from '../libraries/PriceMath.sol'; import { SettlementTokenOracle } from '../oracles/SettlementTokenOracle.sol'; import { Governable } from '../utils/Governable.sol'; import { UNISWAP_V3_FACTORY_ADDRESS, UNISWAP_V3_DEFAULT_FEE_TIER } from '../utils/constants.sol'; contract RageTradeFactory is Governable, ClearingHouseDeployer, InsuranceFundDeployer, VQuoteDeployer, VPoolWrapperDeployer, VTokenDeployer { using AddressHelper for address; using PriceMath for uint256; IVQuote public immutable vQuote; IClearingHouse public immutable clearingHouse; // IInsuranceFund public insuranceFund; // stored in ClearingHouse, replacable from there event PoolInitialized(IUniswapV3Pool vPool, IVToken vToken, IVPoolWrapper vPoolWrapper); /// @notice Sets up the protocol by deploying necessary core contracts /// @dev Need to deploy logic contracts for ClearingHouse, VPoolWrapper, InsuranceFund prior to this constructor( address clearingHouseLogicAddress, address _vPoolWrapperLogicAddress, address insuranceFundLogicAddress, IERC20Metadata settlementToken ) VPoolWrapperDeployer(_vPoolWrapperLogicAddress) { proxyAdmin = _deployProxyAdmin(); proxyAdmin.transferOwnership(msg.sender); // deploys VQuote contract at an address which has most significant nibble as "f" vQuote = _deployVQuote(settlementToken.decimals()); // deploys InsuranceFund proxy IInsuranceFund insuranceFund = _deployProxyForInsuranceFund(insuranceFundLogicAddress); SettlementTokenOracle settlementTokenOracle = new SettlementTokenOracle(); // deploys a proxy for ClearingHouse, and initialize it as well clearingHouse = _deployProxyForClearingHouseAndInitialize( ClearingHouseDeployer.DeployClearingHouseParams( clearingHouseLogicAddress, settlementToken, settlementTokenOracle, insuranceFund, vQuote ) ); clearingHouse.transferGovernance(msg.sender); clearingHouse.transferTeamMultisig(msg.sender); _initializeInsuranceFund(insuranceFund, settlementToken, clearingHouse); } struct InitializePoolParams { VTokenDeployer.DeployVTokenParams deployVTokenParams; IClearingHouseStructures.PoolSettings poolInitialSettings; uint24 liquidityFeePips; uint24 protocolFeePips; uint16 slotsToInitialize; } /// @notice Sets up a new Rage Trade Pool by deploying necessary contracts /// @dev An already deployed oracle contract address (implementing IOracle) is needed prior to using this /// @param initializePoolParams parameters for initializing the pool function initializePool(InitializePoolParams calldata initializePoolParams) external onlyGovernance { // as an argument to vtoken constructer and make wrapper variable as immutable. // this will save sload on all vtoken mints (swaps liqudity adds). // STEP 1: Deploy the virtual token ERC20, such that it will be token0 IVToken vToken = _deployVToken(initializePoolParams.deployVTokenParams); // STEP 2: Deploy vPool (token0=vToken, token1=vQuote) on actual uniswap IUniswapV3Pool vPool = _createUniswapV3Pool(vToken); // STEP 3: Initialize the price on the vPool vPool.initialize( initializePoolParams .poolInitialSettings .oracle .getTwapPriceX128(initializePoolParams.poolInitialSettings.twapDuration) .toSqrtPriceX96() ); vPool.increaseObservationCardinalityNext(initializePoolParams.slotsToInitialize); // STEP 4: Deploys a proxy for the wrapper contract for the vPool, and initialize it as well IVPoolWrapper vPoolWrapper = _deployProxyForVPoolWrapperAndInitialize( IVPoolWrapper.InitializeVPoolWrapperParams( clearingHouse, vToken, vQuote, vPool, initializePoolParams.liquidityFeePips, initializePoolParams.protocolFeePips ) ); // STEP 5: Authorize vPoolWrapper in vToken and vQuote, for minting/burning whenever needed vQuote.authorize(address(vPoolWrapper)); vToken.setVPoolWrapper(address(vPoolWrapper)); clearingHouse.registerPool( IClearingHouseStructures.Pool(vToken, vPool, vPoolWrapper, initializePoolParams.poolInitialSettings) ); emit PoolInitialized(vPool, vToken, vPoolWrapper); } function _createUniswapV3Pool(IVToken vToken) internal returns (IUniswapV3Pool) { return IUniswapV3Pool( IUniswapV3Factory(UNISWAP_V3_FACTORY_ADDRESS).createPool( address(vQuote), address(vToken), UNISWAP_V3_DEFAULT_FEE_TIER ) ); } function _isIVTokenAddressGood(address addr) internal view virtual override returns (bool) { uint32 poolId = addr.truncate(); return // Zero element is considered empty in Uint32L8Array.sol poolId != 0 && // vToken should be token0 and vQuote should be token1 in UniswapV3Pool (uint160(addr) < uint160(address(vQuote))) && // there should not be a collision in poolIds clearingHouse.isPoolIdAvailable(poolId); } }
Sets up a new Rage Trade Pool by deploying necessary contracts An already deployed oracle contract address (implementing IOracle) is needed prior to using this initializePoolParams parameters for initializing the pool as an argument to vtoken constructer and make wrapper variable as immutable. this will save sload on all vtoken mints (swaps liqudity adds). STEP 1: Deploy the virtual token ERC20, such that it will be token0 STEP 2: Deploy vPool (token0=vToken, token1=vQuote) on actual uniswap STEP 3: Initialize the price on the vPool STEP 4: Deploys a proxy for the wrapper contract for the vPool, and initialize it as well STEP 5: Authorize vPoolWrapper in vToken and vQuote, for minting/burning whenever needed
function initializePool(InitializePoolParams calldata initializePoolParams) external onlyGovernance { IVToken vToken = _deployVToken(initializePoolParams.deployVTokenParams); IUniswapV3Pool vPool = _createUniswapV3Pool(vToken); vPool.initialize( initializePoolParams .poolInitialSettings .oracle .getTwapPriceX128(initializePoolParams.poolInitialSettings.twapDuration) .toSqrtPriceX96() ); vPool.increaseObservationCardinalityNext(initializePoolParams.slotsToInitialize); IVPoolWrapper vPoolWrapper = _deployProxyForVPoolWrapperAndInitialize( IVPoolWrapper.InitializeVPoolWrapperParams( clearingHouse, vToken, vQuote, vPool, initializePoolParams.liquidityFeePips, initializePoolParams.protocolFeePips ) ); vQuote.authorize(address(vPoolWrapper)); vToken.setVPoolWrapper(address(vPoolWrapper)); clearingHouse.registerPool( IClearingHouseStructures.Pool(vToken, vPool, vPoolWrapper, initializePoolParams.poolInitialSettings) ); emit PoolInitialized(vPool, vToken, vPoolWrapper); }
2,557,739
pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; /// @title Kudos /// @author Jason Haas /// @notice Kudos ERC721 interface for minting, cloning, and transferring Kudos tokens. contract FFKudos is ERC721Full, Ownable { using SafeMath for uint256; struct Kudo { uint256 priceFinney; uint256 numClonesAllowed; uint256 numClonesInWild; uint256 clonedFromId; } Kudo[] public kudos; uint256 public cloneFeePercentage = 10; bool public isMintable = true; modifier mintable { require( isMintable == true, "New kudos are no longer mintable on this contract. Please see KUDOS_CONTRACT_MAINNET at http://gitcoin.co/l/gcsettings for latest address." ); _; } constructor(string memory _name, string memory _symbol) public ERC721Full(_name, _symbol) { // If the array is new, skip over the first index. if(kudos.length == 0) { Kudo memory _dummyKudo = Kudo({priceFinney: 0,numClonesAllowed: 0, numClonesInWild: 0, clonedFromId: 0 }); kudos.push(_dummyKudo); } } /// @dev mint(): Mint a new Gen0 Kudos. These are the tokens that other Kudos will be "cloned from". /// @param _to Address to mint to. /// @param _priceFinney Price of the Kudos in Finney. /// @param _numClonesAllowed Maximum number of times this Kudos is allowed to be cloned. /// @param _tokenURI A URL to the JSON file containing the metadata for the Kudos. See metadata.json for an example. /// @return the tokenId of the Kudos that has been minted. Note that in a transaction only the tx_hash is returned. function mint(address _to, uint256 _priceFinney, uint256 _numClonesAllowed, string memory _tokenURI) public mintable onlyOwner returns (uint256 tokenId) { Kudo memory _kudo = Kudo({priceFinney: _priceFinney, numClonesAllowed: _numClonesAllowed, numClonesInWild: 0, clonedFromId: 0 }); // The new kudo is pushed onto the array and minted // Note that Solidity uses 0 as a default value when an item is not found in a mapping. tokenId = kudos.push(_kudo) - 1; kudos[tokenId].clonedFromId = tokenId; _mint(_to, tokenId); _setTokenURI(tokenId, _tokenURI); } /// @dev clone(): Clone a new Kudos from a Gen0 Kudos. /// @param _to The address to clone to. /// @param _tokenId The token id of the Kudos to clone and transfer. /// @param _numClonesRequested Number of clones to generate. function clone(address _to, uint256 _tokenId, uint256 _numClonesRequested) public payable mintable { // Grab existing Kudo blueprint Kudo memory _kudo = kudos[_tokenId]; uint256 cloningCost = _kudo.priceFinney * 10**15 * _numClonesRequested; require( _kudo.numClonesInWild + _numClonesRequested <= _kudo.numClonesAllowed, "The number of Kudos clones requested exceeds the number of clones allowed."); require( msg.value >= cloningCost, "Not enough Wei to pay for the Kudos clones."); // Pay the contract owner the cloneFeePercentage amount uint256 contractOwnerFee = (cloningCost.mul(cloneFeePercentage)).div(100); //owner.transfer(contractOwnerFee); // Pay the token owner the cloningCost - contractOwnerFee uint256 tokenOwnerFee = cloningCost.sub(contractOwnerFee); //ownerOf(_tokenId).transfer(tokenOwnerFee); // Update original kudo struct in the array _kudo.numClonesInWild += _numClonesRequested; kudos[_tokenId] = _kudo; // Create new kudo, don't let it be cloned for (uint i = 0; i < _numClonesRequested; i++) { Kudo memory _newKudo; _newKudo.priceFinney = _kudo.priceFinney; _newKudo.numClonesAllowed = 0; _newKudo.numClonesInWild = 0; _newKudo.clonedFromId = _tokenId; // Note that Solidity uses 0 as a default value when an item is not found in a mapping. uint256 newTokenId = kudos.push(_newKudo) - 1; // Mint the new kudos to the _to account _mint(_to, newTokenId); // Use the same tokenURI metadata from the Gen0 Kudos //string memory _tokenURI = tokenURI(_tokenId); string memory _tokenURI = "foo"; _setTokenURI(newTokenId, _tokenURI); } // Return the any leftvoer ETH to the sender msg.sender.transfer(msg.value - contractOwnerFee - tokenOwnerFee); } /// @dev burn(): Burn Kudos token. /// @param _owner The owner address of the token to burn. /// @param _tokenId The Kudos ID to be burned. function burn(address _owner, uint256 _tokenId) public onlyOwner { Kudo memory _kudo = kudos[_tokenId]; uint256 gen0Id = _kudo.clonedFromId; if (_tokenId != gen0Id) { Kudo memory _gen0Kudo = kudos[gen0Id]; _gen0Kudo.numClonesInWild -= 1; kudos[gen0Id] = _gen0Kudo; } delete kudos[_tokenId]; _burn(_owner, _tokenId); } /// @dev setCloneFeePercentage(): Update the Kudos clone fee percentage. Upon cloning a new kudos, /// cloneFeePercentage will go to the contract owner, and /// (100 - cloneFeePercentage) will go to the Gen0 Kudos owner. /// @param _cloneFeePercentage The percentage fee between 0 and 100. function setCloneFeePercentage(uint256 _cloneFeePercentage) public onlyOwner { require( _cloneFeePercentage >= 0 && _cloneFeePercentage <= 100, "Invalid range for cloneFeePercentage. Must be between 0 and 100."); cloneFeePercentage = _cloneFeePercentage; } /// @dev setMintable(): set the isMintable public variable. When set to `false`, no new /// kudos are allowed to be minted or cloned. However, all of already /// existing kudos will remain unchanged. /// @param _isMintable flag for the mintable function modifier. function setMintable(bool _isMintable) public onlyOwner { isMintable = _isMintable; } /// @dev setPrice(): Update the Kudos listing price. /// @param _tokenId The Kudos Id. /// @param _newPriceFinney The new price of the Kudos. function setPrice(uint256 _tokenId, uint256 _newPriceFinney) public onlyOwner { Kudo memory _kudo = kudos[_tokenId]; _kudo.priceFinney = _newPriceFinney; kudos[_tokenId] = _kudo; } /// @dev setTokenURI(): Set an existing token URI. /// @param _tokenId The token id. /// @param _tokenURI The tokenURI string. Typically this will be a link to a json file on IPFS. function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner { _setTokenURI(_tokenId, _tokenURI); } /// @dev getKudosById(): Return a Kudos struct/array given a Kudos Id. /// @param _tokenId The Kudos Id. /// @return the Kudos struct, in array form. function getKudosById(uint256 _tokenId) public view returns (uint256 priceFinney, uint256 numClonesAllowed, uint256 numClonesInWild, uint256 clonedFromId ) { Kudo memory _kudo = kudos[_tokenId]; priceFinney = _kudo.priceFinney; numClonesAllowed = _kudo.numClonesAllowed; numClonesInWild = _kudo.numClonesInWild; clonedFromId = _kudo.clonedFromId; } /// @dev getNumClonesInWild(): Return a Kudos struct/array given a Kudos Id. /// @param _tokenId The Kudos Id. /// @return the number of cloes in the wild function getNumClonesInWild(uint256 _tokenId) public view returns (uint256 numClonesInWild) { Kudo memory _kudo = kudos[_tokenId]; numClonesInWild = _kudo.numClonesInWild; } /// @dev getLatestId(): Returns the newest Kudos Id in the kudos array. /// @return the latest kudos id. function getLatestId() public view returns (uint256 tokenId) { if (kudos.length == 0) { tokenId = 0; } else { tokenId = kudos.length - 1; } } }
getLatestId(): Returns the newest Kudos Id in the kudos array. return the latest kudos id.
function getLatestId() public view returns (uint256 tokenId) { if (kudos.length == 0) { tokenId = 0; tokenId = kudos.length - 1; } }
6,376,170
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { RolesMods } from "../../contexts2/access-control/roles/RolesMods.sol"; import { ADMIN, AUTHORIZED } from "../../shared/roles.sol"; // Interfaces import { ICErc20 } from "../../shared/interfaces/ICErc20.sol"; import { IAToken } from "../../shared/interfaces/IAToken.sol"; import { IVault } from "../../shared/interfaces/IVault.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Libraries import { CacheLib, Cache, CacheType } from "../../shared/libraries/CacheLib.sol"; import { AssetCTokenLib } from "./libraries/AssetCTokenLib.sol"; import { AssetATokenLib } from "./libraries/AssetATokenLib.sol"; import { AssetPPoolLib } from "./libraries/AssetPPoolLib.sol"; import { AssetYVaultLib } from "./libraries/AssetYVaultLib.sol"; import { PoolTogetherLib } from "../../escrow/dapps/libraries/PoolTogetherLib.sol"; import { MaxLoanAmountLib } from "./libraries/MaxLoanAmountLib.sol"; import { MaxTVLLib } from "./libraries/MaxTVLLib.sol"; import { MaxDebtRatioLib } from "./libraries/MaxDebtRatioLib.sol"; // Storage import { AppStorageLib, AppStorage } from "../../storage/app.sol"; import { PrizePoolInterface } from "../../shared/interfaces/pooltogether/PrizePoolInterface.sol"; /** * @notice View function to get asset setting values. * * @author [email protected] */ contract AssetSettingsDataFacet { /** * @notice it gets the asset's max loan amount * @param asset the address of the asset * @return the max loan amount */ function getAssetMaxLoanAmount(address asset) external view returns (uint256) { return MaxLoanAmountLib.get(asset); } /** * @notice it gets the maxTVL of an asset * @param asset the address of the asset * @return it returns the maxTVL */ function getAssetMaxTVL(address asset) external view returns (uint256) { return MaxTVLLib.get(asset); } /** * @notice it gets the maxDebtRatio of an asset * @param asset the address of the asset * @return it returns the maxDebtRatio */ function getAssetMaxDebtRatio(address asset) external view returns (uint256) { return MaxDebtRatioLib.get(asset); } /** * @notice it returns the asset's Compound token * @param asset the address of the asset * @return the Compound token of an asset */ function getAssetCToken(address asset) external view returns (ICErc20) { return AssetCTokenLib.get(asset); } /** * @notice it returns the asset's Aave token * @param asset the address of the asset * @return the Aave token of an asset */ function getAssetAToken(address asset) external view returns (IAToken) { return AssetATokenLib.get(asset); } /** * @notice it returns the asset's PoolTogether PrizePool contract * @param asset the address of the asset * @return the PoolTogether PrizePool contract of an asset */ function getAssetPPool(address asset) external view returns (PrizePoolInterface) { return AssetPPoolLib.get(asset); } /** * @notice it returns the asset's PoolTogether Ticket token * @param asset the address of the asset * @return the PoolTogether Ticket token of an asset */ function getAssetPPoolTicket(address asset) external view returns (IERC20) { return IERC20(PoolTogetherLib.getTicketAddress(asset)); } /** * @notice it gets the Yearn Vault of an asset * @param asset the address of the asset * @return it returns the Yearn Vault */ function getAssetYVault(address asset) external view returns (IVault) { return AssetYVaultLib.get(asset); } }
it returns the asset's PoolTogether PrizePool contract asset the address of the asset return the PoolTogether PrizePool contract of an asset/
function getAssetPPool(address asset) external view returns (PrizePoolInterface) { return AssetPPoolLib.get(asset); }
1,004,200
./partial_match/1/0xd4260e4Bfb354259F5e30279cb0D7F784Ea5f37A/sources/VokenPublicSale2.sol
USD => voken, by `usdAmount`./
function _usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); }
2,613,643
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol contract Convoy is ERC721, ERC721Enumerable { struct Match { uint256 matchId; // not necessary, for debugging address defender; address invader; uint32[5] defense; // null-terminated but 5 max // [0,1,2,3,4,5,6,7,8,9] // [0,1,2,3,4] uint32[5] invasion; // quick reset by setting invasion[0] = 0 bytes32 defenseHash; bytes32 invasionHash; uint256 resultHash; uint8 pointsInvader; uint8 round; bool defenderRevealed; bool invaderRevealed; bool disputeFlag; } uint8 public armySize = 5; // const // (position << 16) + (type << 13) + (hp << 10) + (range << 7) + (attack << 4); uint8 OFF_POSITION = 16; uint8 OFF_TYPE = 13; uint8 OFF_HP = 10; uint8 OFF_RANGE = 7; uint8 OFF_ATTACK = 4; uint8 OFF_SPEED = 1; mapping(uint256 => Match) public matches; uint256[] public joinables; uint256 private counter; event MatchMinted(uint256 indexed matchId); event MatchJoined(uint256 indexed matchId, address opponent); event Committed(uint256 indexed matchId, bool asDefender); event Revealed(uint256 indexed matchId, bool asDefender); event InvadersDestroyed(uint256 indexed matchId, uint8 count); event DefendersDestroyed(uint256 indexed matchId, uint8 count); constructor() ERC721("Match", "MATCH") { // what should we do on deploy? } // to support receiving ETH by default receive() external payable {} fallback() external payable {} function initMatch() public returns (uint256) { _mint(msg.sender, counter); Match storage m = matches[counter]; m.matchId = counter; m.defender = msg.sender; // TODO allow proposing match as invader emit MatchMinted(counter); joinables.push(counter); counter++; return m.matchId; } function getMatch(uint256 matchId) public view returns (Match memory) { require(matchId < counter, "Match too big"); return matches[matchId]; } // return your (defender or invader) newest 10 active (not round=4) matches function yourNewestActiveMatches(address you) public view returns (uint256[] memory) { require(counter > 0, "Not a single match"); uint256 count; uint256[] memory yourMatches = new uint256[](10); for (uint256 i = counter; i > 0 && count < 10; i--) { Match memory m = matches[i - 1]; // i-1 so i must be > 0, do not let 0-- console.log(msg.sender); console.log(m.defender); console.log(m.invader); if (m.defender == you || m.invader == you) { if (m.round < 4) { yourMatches[count++] = i - 1; } } } // filters empty slots from yourMatches, prevents returning invalid 0s uint256[] memory filtered = new uint256[](count); for (uint256 i; i < count; i++) { filtered[i] = yourMatches[i]; } return filtered; } function _test1round(uint256 matchId) public { require(matchId < counter, "Match too big"); matches[matchId].defender = msg.sender; matches[matchId].invader = msg.sender; matches[matchId].defenseHash = "foo"; matches[matchId].invasionHash = "bar"; // matches[matchId]. } function joinlist() public view returns (uint256[] memory) { return joinables; } function joinMatch(uint256 matchId, bool asDefender) public { require(matchId < counter, "Match too big"); require(!asDefender || matches[matchId].defender == address(0), "Defender exists"); require(asDefender || matches[matchId].invader == address(0), "Invader exists"); for (uint256 i = 0; i < joinables.length; i++) { if (matchId == joinables[i]) { // delete element from array joinables[i] = joinables[joinables.length - 1]; joinables.pop(); if (asDefender) { matches[matchId].defender = msg.sender; } else { matches[matchId].invader = msg.sender; } emit MatchJoined(matchId, msg.sender); return; } } revert("matchId not joinable"); } function matchRound(uint256 matchId) public view returns (uint8 round, bool ready) { require(matchId < counter, "Match too big"); round = matches[matchId].round; ready = matches[matchId].defender != address(0) && matches[matchId].invader != address(0); return (round, ready); } function commit(uint256 matchId, bool asDefender, bytes32 hash) public { require(matchId < counter, "Match too big"); require(!matches[matchId].defenderRevealed && !matches[matchId].invaderRevealed, "Reveal initiated already"); require(!asDefender || matches[matchId].defender == msg.sender, "Not the defender"); require(asDefender || matches[matchId].invader == msg.sender, "Not the invader"); // Can only reveal after both sides committed, can commit until both committed and one revealed require(!matches[matchId].defenderRevealed, "Defender already revealed"); require(!matches[matchId].invaderRevealed, "Invader already revealed"); // allows committing before someone has even joined if (asDefender) { matches[matchId].defenseHash = hash; } else { matches[matchId].invasionHash = hash; } emit Committed(matchId, asDefender); // you can commit repeatedly until someone has revealed } function reveal(uint256 matchId, bool asDefender, uint32[5] calldata army) public { require(matchId < counter, "Match too big"); //require(!matches[matchId].defenderRevealed && !matches[matchId].invaderRevealed, "Reveal initiated already"); require(!asDefender || matches[matchId].defender == msg.sender, "Not the defender"); require(asDefender || matches[matchId].invader == msg.sender, "Not the invader"); require(matches[matchId].defenseHash != 0 && matches[matchId].invasionHash != 0, "A side has yet to commit"); require(!asDefender || !matches[matchId].defenderRevealed, "Defender already revealed"); require(asDefender || !matches[matchId].invaderRevealed, "Invader already revealed"); if (asDefender) { matches[matchId].defense = army; matches[matchId].defenderRevealed = true; } else { matches[matchId].invasion = army; matches[matchId].invaderRevealed = true; } emit Revealed(matchId, asDefender); // TODO compute and check hash matches, can't just let opponent take responsibility // XXX not optional because we will clear hash w/o dispute step finishRound(matchId); } function finishRound(uint256 matchId) public { if (matches[matchId].defenderRevealed && matches[matchId].invaderRevealed) { // Both revealed! game on! // rollRound(......); // alternatively, let one side compute results and wait for other side to accept or dispute // but then we need to save state to allow a confirm/dispute step // so we must validate here in the contract // TODO loop a few times, note that armies get modified in place evalRound(matchId); _roundUp(matchId); } } // position should be max 5 bits to fit up to 16 troops in defenseReverse where defense > 16. // There is no uint4 so uint8. function posit(uint32 troop) public view returns (uint8) { return uint8(troop >> OFF_POSITION); } function setPos(uint32 troop, uint8 pos) public returns (uint32) { return troop | ((0x1F & pos) << OFF_POSITION); } function attrib(uint32 troop, uint8 offset) public view returns (uint8) { // 0b111 = 0x07 return 0x07 & uint8(troop >> offset); } function setAttr(uint32 troop, uint8 offset, uint8 val) public returns (uint32) { return troop | ((0x07 & val) << offset); } // looks at defense/invasion and computes state based on that alone, assuming not mid-reveal function evalRound(uint256 matchId) public { require(matchId < counter, "Match too big"); require(matches[matchId].invaderRevealed, "Invader has not revealed"); require(matches[matchId].defenderRevealed, "Defender has not revealed"); uint16 defenseMap; uint16 invasionMap; uint128 defenseReverse; uint128 invasionReverse; uint8 defendersDestroyed; uint8 invadersDestroyed; uint8 invadersSurvived; Match memory m = matches[matchId]; // make map and reverse for (uint8 i = 0; i < armySize && m.defense[i] != 0; i++) { // XXX at this stage they should all be "alive"? if (attrib(m.defense[i], OFF_HP) == 0) { continue; } defenseMap |= uint16(1 << posit(m.defense[i])); defenseReverse |= (i << (4 * posit(m.defense[i]))); // 4 bits for position } for (uint8 i = 0; i < armySize && m.invasion[i] != 0; i++) { if (attrib(m.invasion[i], OFF_HP) == 0) { continue; } invadersSurvived++; // alternatively count bits in post-attacked invasionMap invasionMap |= uint16(1 << posit(m.invasion[i])); invasionReverse |= (i << (4 * posit(m.invasion[i]))); // 4 bits for position } // attack by defense for (uint8 i = 0; i < armySize && m.defense[i] != 0; i++) { uint8 range = attrib(m.defense[i], OFF_RANGE) - 1; // range=1 can attack only directly up/down, so -- uint8 pos = posit(m.defense[i]); if (pos == 0) { continue; } uint8 min = pos - range; for (pos = pos + range; pos >= min; pos--) { // starts big, most advanced troops if ((invasionMap & uint16(1 << pos)) != 0) { // hit uint8 invaderIdx = (0x0F & uint8(invasionReverse >> (4 * pos))); uint8 newHp = attrib(m.invasion[invaderIdx], OFF_HP); newHp -= attrib(m.defense[i], OFF_ATTACK); // prevent underflow by not subtracting if (newHp <= attrib(m.defense[i], OFF_ATTACK)) { newHp = 0; invasionMap -= uint16(1 << pos); invadersDestroyed++; invadersSurvived--; } m.invasion[invaderIdx] = setAttr(m.invasion[invaderIdx], OFF_HP, newHp); // TODO mark as dead, besides hp=0 break; } } } // TODO attack by invader like defense after testing m.pointsInvader += invadersSurvived; emit InvadersDestroyed(matchId, invadersDestroyed); emit DefendersDestroyed(matchId, defendersDestroyed); // move troops - only invaders move invasionMap = 0; // throw away for (uint8 i = 0; i < armySize && m.invasion[i] != 0; i++) { // skip dead troops if (attrib(m.invasion[i], OFF_HP) == 0) { continue; } uint8 speed = attrib(m.invasion[i], OFF_SPEED); uint8 pos = posit(m.invasion[i]); while (speed > 0) { pos++; if ((invasionMap & (1 << pos)) != 0) { pos--; invasionMap |= uint16(1 << pos); m.invasion[i] = setPos(m.invasion[i], pos); break; } speed--; } if (speed == 0) { invasionMap |= uint16(1 << pos); m.invasion[i] = setPos(m.invasion[i], pos); } } } function _roundUp(uint256 matchId) internal { matches[matchId].defenseHash = 0; matches[matchId].invasionHash = 0; // don't reset actual defense/invasion so that other side can view results themselves matches[matchId].defenderRevealed = false; matches[matchId].invaderRevealed = false; matches[matchId].round++; // emit rolled... rounded... } function defense(uint256 matchId) public view returns (uint32[5] memory) { return matches[matchId].defense; } function invasion(uint256 matchId) public view returns (uint32[5] memory) { return matches[matchId].invasion; } /* -------------------------------------------------------------------- */ // Required implementations for ERC721 function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Both revealed! game on! rollRound(......); alternatively, let one side compute results and wait for other side to accept or dispute but then we need to save state to allow a confirm/dispute step so we must validate here in the contract TODO loop a few times, note that armies get modified in place
function finishRound(uint256 matchId) public { if (matches[matchId].defenderRevealed && matches[matchId].invaderRevealed) { evalRound(matchId); _roundUp(matchId); } }
5,445,508
// SPDX-License-Identifier: MIT pragma solidity 0.5.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating 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); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint256) values; mapping(address => uint256) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) internal view returns (uint256) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) internal view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) internal view returns (address) { return map.keys[index]; } function size(Map storage map) internal view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) internal { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) internal { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } interface IXSPStaking { struct Percentage { uint256 timestamp; uint256 percentPerMonth; uint256 percentPerSecond; } struct Staker { uint256 timestamp; uint256 amount; } // public write ----- // gets value and checks current total staked amount. if more than available to stake then returns back function stake(uint256 amount) external returns (uint256 timestamp); // dont forget to unpause if its needed function unstake(bool reinvestReward) external returns (uint256 timestamp); function claimReward() external returns (uint256 claimedAmount, uint256 timestamp); function reinvest() external returns (uint256 reinvestedAmount, uint256 timestamp); // public view ----- function claimableReward() external view returns (uint256 reward); //with internal function for reuse in claimReward() and reinvest() function percentagePerMonth() external view returns (uint256[] memory, uint256[] memory); // for owner // pausing staking. unstake is available. function pauseStacking(uint256 startTime) external returns (bool); // if 0 => block.timestamp function unpauseStacking() external returns (bool); // pausing staking, unstaking and sets 0 percent from current time function pauseGlobally(uint256 startTime) external returns (bool); // if 0 => block.timestamp function unpauseGlobally() external returns (bool); function updateMaxTotalAmountToStake(uint256 amount) external returns (uint256 updatedAmount); function updateMinAmountToStake(uint256 amount) external returns (uint256 updatedAmount); // if 0 => block.timestamp function addPercentagePerMonth(uint256 timestamp, uint256 percent) external returns (uint256 index); // require(timestamp > block.timestamp); function updatePercentagePerMonth(uint256 timestamp, uint256 percent, uint256 index) external returns (bool); function removeLastPercentagePerMonth() external returns (uint256 index); event Stake(address account, uint256 stakedAmount); event Unstake(address account, uint256 unstakedAmount, bool withReward); event ClaimReward(address account, uint256 claimedAmount); event Reinvest(address account, uint256 reinvestedAmount, uint256 totalInvested); event MaxStakeAmountReached(address account, uint256 changeAmount); event StakingPause(uint256 startTime); event StakingUnpause(); // check with empty args event GlobalPause(uint256 startTime); event GlobalUnpause(); event MaxTotalStakeAmountUpdate(uint256 updateAmount); event MinStakeAmountUpdate(uint256 updateAmount); event AddPercentagePerMonth(uint256 percent, uint256 index); event UpdatePercentagePerMonth(uint256 percent, uint256 index); event RemovePercentagePerMonth(uint256 index); } contract AutoInvest is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private investors; IXSPStaking public mainContract = IXSPStaking(0xadc4c058fa4217a3c57f535dc000c2f66a99aba9); uint256 public totalStaked; uint256 public totalPending; uint256 private undestributedReward; uint256 public minAmountToStake = 3 * 10 ** 6 * 10 ** 18; bool public depositsEnabled = true; bool public withdrawalsEnabled = true; bool public emergencyWithdraw = false; IERC20 public token = IERC20(0x36726235dAdbdb4658D33E62a249dCA7c4B2bC68); address public managerAddress; uint256 public withdrawFeePercent = 5; uint256 public harvestFeePercent = 230; uint256 public denominator = 1000; // fee = 50/1000 = 5% event StakeSuccessfull(uint256 amount); event WithdrawalSuccessfull(uint256 amount); event Harvest(uint256 amount); modifier onlyManager { require(msg.sender == owner() || msg.sender == managerAddress); _; } constructor() public { token.safeApprove(address(mainContract), ~uint256(0)); } function length() external view returns (uint) { return investors.size(); } function deposit(uint256 _amount) external { require(depositsEnabled); if (isRunning()) { harvest(); } token.safeTransferFrom(msg.sender, address(this), _amount); totalPending += _amount; if (totalPending >= minAmountToStake || totalStaked >= minAmountToStake) { mainContract.stake(totalPending); totalStaked = totalStaked.add(totalPending); totalPending = 0; emit StakeSuccessfull(totalPending); } if (investors.inserted[msg.sender]) { uint256 oldAmount = investors.get(msg.sender); investors.set(msg.sender, _amount.add(oldAmount)); } else { investors.set(msg.sender, _amount); } // stakers[msg.sender] += _amount; } function changeMinimumAmount(uint256 _newAmount) external onlyOwner { minAmountToStake = _newAmount; } function isRunning() public view returns(bool) { return totalStaked >= minAmountToStake; } function withdraw() external { require(withdrawalsEnabled); require(investors.get(msg.sender) > 0, "Nothing to unstake"); if (!emergencyWithdraw) { require(totalStaked.sub(investors.get(msg.sender)) >= minAmountToStake); } if (isRunning()) { harvest(); } uint256 amount = investors.get(msg.sender); uint256 balanceBefore; uint256 balanceAfter; if (totalStaked > 0) { balanceBefore = token.balanceOf(address(this)); mainContract.unstake(false); balanceAfter = token.balanceOf(address(this)); totalPending = balanceAfter.sub(balanceBefore).sub(amount); totalStaked = 0; } else { totalPending = totalPending.sub(amount); } investors.remove(msg.sender); _stake(); uint256 fee = amount.mul(withdrawFeePercent).div(denominator); amount = amount.sub(fee); // stakers[msg.sender] = 0; token.safeTransfer(msg.sender, amount); token.safeTransfer(managerAddress, fee); emit WithdrawalSuccessfull(amount); } function _stake() internal { if (isRunning()) { mainContract.stake(totalPending); totalStaked = totalStaked.add(totalPending); totalPending = 0; } } function getMyRewardAmount(address _address) public view returns (uint256) { if (!investors.inserted[_address]) { // If not participated in staking return 0; } if (!isRunning()) { // if the contract has not yet staked anything return 0; } else { uint256 totalReward = mainContract.claimableReward(); uint256 stakeShare = investors.get(_address).mul(10**18).div(totalStaked); // uint256 stakeShare = stakers[_address] * 10**18 / totalStaked; return totalReward.mul(stakeShare).div(10**18); } } function _rewardAmount(address _address, uint256 _totalReward) internal view returns (uint256) { uint256 stakeShare = investors.get(_address).mul(10**18).div(totalStaked); // uint256 stakeShare = stakers[_address] * 10**18 / totalStaked; return _totalReward.mul(stakeShare).div(10**18); } function harvest() public { require(isRunning()); (uint256 claimed, ) = mainContract.claimReward(); uint256 fee = claimed.mul(harvestFeePercent).div(denominator); claimed -= fee; address investor; for (uint256 i = 0; i < investors.size(); i++){ investor = investors.getKeyAtIndex(i); uint256 userReward = _rewardAmount(investor, claimed); token.safeTransfer(investor, userReward); } token.safeTransfer(managerAddress, fee); } function setEmergencyWithdraw(bool _value) external onlyManager { emergencyWithdraw = _value; } function changeWithdrawFee(uint256 _newFee) external onlyManager { withdrawFeePercent = _newFee; } function changeHarvestFee(uint256 _newFee) external onlyManager { harvestFeePercent = _newFee; } function changeManagerAddress(address _newAddress) external onlyManager { managerAddress = _newAddress; } function depositStatus(bool _value) external onlyOwner { depositsEnabled = _value; } function withdrawalStatus(bool _value) external onlyOwner { withdrawalsEnabled = _value; } function withdrawStuckTokens(IERC20 _token, uint256 _amount) external onlyManager { _token.safeTransfer(msg.sender, _amount); } }
if 0 => block.timestamp
function pauseGlobally(uint256 startTime) external returns (bool);
929,836
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/dev/automation/2_1/KeeperRegistryLogicB2_1.sol
updates the gas limit for an upkeep/
function setUpkeepGasLimit(uint256 id, uint32 gasLimit) external { if (gasLimit < PERFORM_GAS_MIN || gasLimit > s_storage.maxPerformGas) revert GasLimitOutsideRange(); _requireAdminAndNotCancelled(id); s_upkeep[id].performGas = gasLimit; emit UpkeepGasLimitSet(id, gasLimit); }
3,963,118
/** *Submitted for verification at Etherscan.io on 2021-06-29 */ // File: contracts/Whitelist.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; contract Whitelist { uint256 groupId; address public whiteListManager; struct WhitelistGroup { mapping(address => bool) members; mapping(address => bool) whitelistGroupAdmin; bool created; } mapping(uint256 => WhitelistGroup) private whitelistGroups; event GroupCreated(address, uint256); constructor() public { whiteListManager = msg.sender; } modifier onlyWhitelistManager { require( msg.sender == whiteListManager, "Only Whitelist manager can call this function." ); _; } /// @dev Function to change the whitelist manager of Yieldster. /// @param _manager Address of the new manager. function changeManager(address _manager) public onlyWhitelistManager { whiteListManager = _manager; } /// @dev Function that returns if a whitelist group is exist. /// @param _groupId Group Id of the whitelist group. function _isGroup(uint256 _groupId) private view returns (bool) { return whitelistGroups[_groupId].created; } /// @dev Function that returns if the msg.sender is the whitelist group admin. /// @param _groupId Group Id of the whitelist group. function _isGroupAdmin(uint256 _groupId) public view returns (bool) { return whitelistGroups[_groupId].whitelistGroupAdmin[msg.sender]; } /// @dev Function to create a new whitelist group. /// @param _whitelistGroupAdmin Address of the whitelist group admin. function createGroup(address _whitelistGroupAdmin) public returns (uint256) { groupId += 1; require(!whitelistGroups[groupId].created, "Group already exists"); WhitelistGroup memory newGroup = WhitelistGroup({created: true}); whitelistGroups[groupId] = newGroup; whitelistGroups[groupId].members[_whitelistGroupAdmin] = true; whitelistGroups[groupId].whitelistGroupAdmin[ _whitelistGroupAdmin ] = true; whitelistGroups[groupId].members[msg.sender] = true; emit GroupCreated(msg.sender, groupId); return groupId; } /// @dev Function to delete a whitelist group. /// @param _groupId Group Id of the whitelist group. function deleteGroup(uint256 _groupId) public { require(_isGroup(_groupId), "Group doesn't exist!"); require( _isGroupAdmin(_groupId), "Only Whitelist Group admin is permitted for this operation" ); delete whitelistGroups[_groupId]; } /// @dev Function to add members to a whitelist group. /// @param _groupId Group Id of the whitelist group. /// @param _memberAddress List of address to be added to the whitelist group. function addMembersToGroup( uint256 _groupId, address[] memory _memberAddress ) public { require(_isGroup(_groupId), "Group doesn't exist!"); require( _isGroupAdmin(_groupId), "Only goup admin is permitted for this operation" ); for (uint256 i = 0; i < _memberAddress.length; i++) { whitelistGroups[_groupId].members[_memberAddress[i]] = true; } } /// @dev Function to remove members from a whitelist group. /// @param _groupId Group Id of the whitelist group. /// @param _memberAddress List of address to be removed from the whitelist group. function removeMembersFromGroup( uint256 _groupId, address[] memory _memberAddress ) public { require(_isGroup(_groupId), "Group doesn't exist!"); require( _isGroupAdmin(_groupId), "Only Whitelist Group admin is permitted for this operation" ); for (uint256 i = 0; i < _memberAddress.length; i++) { whitelistGroups[_groupId].members[_memberAddress[i]] = false; } } /// @dev Function to check if an address is a whitelisted address. /// @param _groupId Group Id of the whitelist group. /// @param _memberAddress Address to check. function isMember(uint256 _groupId, address _memberAddress) public view returns (bool) { require(_isGroup(_groupId), "Group doesn't exist!"); return whitelistGroups[_groupId].members[_memberAddress]; } // /// @dev Function that returns the address of the whitelist group admin. // /// @param _groupId Group Id of the whitelist group. // function getWhitelistAdmin(uint256 _groupId) public view returns (address) { // require(_isGroup(_groupId), "Group doesn't exist!"); // return whitelistGroups[_groupId].whitelistGroupAdmin; // } /// @dev Function to add the whitelist admin of a group. /// @param _groupId Group Id of the whitelist group. /// @param _whitelistGroupAdmin Address of the new whitelist admin. function addWhitelistAdmin(uint256 _groupId, address _whitelistGroupAdmin) public { require(_isGroup(_groupId), "Group doesn't exist!"); require( _isGroupAdmin(_groupId), "Only existing whitelist admin can perform this operation" ); whitelistGroups[_groupId].whitelistGroupAdmin[ _whitelistGroupAdmin ] = true; } function removeWhitelistAdmin( uint256 _groupId, address _whitelistGroupAdmin ) public { require(_isGroup(_groupId), "Group doesn't exist!"); require(_whitelistGroupAdmin != msg.sender, "Cannot remove yourself"); require( _isGroupAdmin(_groupId), "Only existing whitelist admin can perform this operation" ); delete whitelistGroups[_groupId].whitelistGroupAdmin[ _whitelistGroupAdmin ]; } }
Function to add members to a whitelist group. _groupId Group Id of the whitelist group. _memberAddress List of address to be added to the whitelist group.
function addMembersToGroup( uint256 _groupId, address[] memory _memberAddress ) public { require(_isGroup(_groupId), "Group doesn't exist!"); require( _isGroupAdmin(_groupId), "Only goup admin is permitted for this operation" ); for (uint256 i = 0; i < _memberAddress.length; i++) { whitelistGroups[_groupId].members[_memberAddress[i]] = true; } }
15,079,424
pragma solidity ^0.6.5; library Assert { event AssertionEvent( bool passed, string message ); function ok(bool a, string memory message) internal pure returns (bool result) { result = a; require(result, message); } function notOk(bool a, string memory message) internal pure returns (bool result) { result = !a; ok(result, message); } function equal(uint a, uint b, string memory message) internal pure returns (bool result) { result = (a == b); ok(result, message); } function equal(int a, int b, string memory message) internal pure returns (bool result) { result = (a == b); ok(result, message); } function equal(bool a, bool b, string memory message) internal pure returns (bool result) { result = (a == b); ok(result, message); } function equal(address a, address b, string memory message) internal pure returns (bool result) { result = (a == b); ok(result, message); } function equal(bytes32 a, bytes32 b, string memory message) internal pure returns (bool result) { result = (a == b); ok(result, message); } function equal(string memory a, string memory b, string memory message) internal pure returns (bool result) { result = (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))); ok(result, message); } function notEqual(uint a, uint b, string memory message) internal pure returns (bool result) { result = (a != b); ok(result, message); } function notEqual(int a, int b, string memory message) internal pure returns (bool result) { result = (a != b); ok(result, message); } function notEqual(bool a, bool b, string memory message) internal pure returns (bool result) { result = (a != b); ok(result, message); } function notEqual(address a, address b, string memory message) internal pure returns (bool result) { result = (a != b); ok(result, message); } function notEqual(bytes32 a, bytes32 b, string memory message) internal pure returns (bool result) { result = (a != b); ok(result, message); } function notEqual(string memory a, string memory b, string memory message) internal pure returns (bool result) { result = (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))); ok(result, message); } /*----------------- Greater than --------------------*/ function greaterThan(uint a, uint b, string memory message) internal pure returns (bool result) { result = (a > b); ok(result, message); } function greaterThan(int a, int b, string memory message) internal pure returns (bool result) { result = (a > b); ok(result, message); } // TODO: safely compare between uint and int function greaterThan(uint a, int b, string memory message) internal pure returns (bool result) { if(b < int(0)) { // int is negative uint "a" always greater result = true; } else { result = (a > uint(b)); } ok(result, message); } function greaterThan(int a, uint b, string memory message) internal pure returns (bool result) { if(a < int(0)) { // int is negative uint "b" always greater result = false; } else { result = (uint(a) > b); } ok(result, message); } /*----------------- Lesser than --------------------*/ function lesserThan(uint a, uint b, string memory message) internal pure returns (bool result) { result = (a < b); ok(result, message); } function lesserThan(int a, int b, string memory message) internal pure returns (bool result) { result = (a < b); ok(result, message); } // TODO: safely compare between uint and int function lesserThan(uint a, int b, string memory message) internal pure returns (bool result) { if(b < int(0)) { // int is negative int "b" always lesser result = false; } else { result = (a < uint(b)); } ok(result, message); } function lesserThan(int a, uint b, string memory message) internal pure returns (bool result) { if(a < int(0)) { // int is negative int "a" always lesser result = true; } else { result = (uint(a) < b); } ok(result, message); } }
TODO: safely compare between uint and int int is negative int "b" always lesser
function lesserThan(uint a, int b, string memory message) internal pure returns (bool result) { if(b < int(0)) { result = false; result = (a < uint(b)); } ok(result, message); }
13,080,243
./partial_match/1/0x8155F0d5714f304aBe85E05293AA7AB386987D3d/sources/MYTH.sol
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; }
2,599,900
pragma solidity ^0.6; import "../../../lib/SafeMath.sol"; import {Ownable} from "../ownership/Ownable.sol"; /** * Stores information for added training data and corresponding meta-data. */ interface DataHandler { function updateClaimableAmount(bytes32 dataKey, uint rewardAmount) external; } /** * Stores information for added training data and corresponding meta-data. */ contract DataHandler64 is Ownable, DataHandler { using SafeMath for uint256; struct StoredData { /** * The data stored. */ // Don't store the data because it's not really needed since we emit events when data is added. // The main reason for storing the data in here is to ensure equality on future interactions like when refunding. // This extra equality check is only necessary if you're worried about hash collisions. // int64[] d; /** * The classification for the data. */ uint64 c; /** * The time it was added. */ uint t; /** * The address that added the data. */ address sender; /** * The amount that was initially given to deposit this data. */ uint initialDeposit; /** * The amount of the deposit that can still be claimed. */ uint claimableAmount; /** * The number of claims that have been made for refunds or reports. * This should be the size of `claimedBy`. */ uint numClaims; /** * The set of addresses that claimed a refund or reward on this data. */ mapping(address => bool) claimedBy; } /** * Meta-data for data that has been added. */ mapping(bytes32 => StoredData) public addedData; function getClaimableAmount(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.claimableAmount; } function getInitialDeposit(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.initialDeposit; } function getNumClaims(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.numClaims; } /** * Check if two arrays of training data are equal. */ function isDataEqual(int64[] memory d1, int64[] memory d2) public pure returns (bool) { if (d1.length != d2.length) { return false; } for (uint i = 0; i < d1.length; ++i) { if (d1[i] != d2[i]) { return false; } } return true; } /** * Log an attempt to add data. * * @param msgSender The address of the one attempting to add data. * @param cost The cost required to add new data. * @param data A single sample of training data for the model. * @param classification The label for `data`. * @return time The time which the data was added, i.e. the current time in seconds. */ function handleAddData(address msgSender, uint cost, int64[] memory data, uint64 classification) public onlyOwner returns (uint time) { time = now; // solium-disable-line security/no-block-members bytes32 key = keccak256(abi.encodePacked(data, classification, time, msgSender)); StoredData storage existingData = addedData[key]; bool okayToOverwrite = existingData.sender == address(0) || existingData.claimableAmount == 0; require(okayToOverwrite, "Conflicting data key. The data may have already been added."); // Maybe we do want to allow duplicate data to be added but just not from the same address. // Of course that is not sybil-proof. // Store data. addedData[key] = StoredData({ // not necessary: d: data, c: classification, t: time, sender: msgSender, initialDeposit: cost, claimableAmount: cost, numClaims: 0 }); } /** * Log a refund attempt. * * @param submitter The address of the one attempting a refund. * @param data The data for which to attempt a refund. * @param classification The label originally submitted for `data`. * @param addedTime The time in seconds for which the data was added. * @return claimableAmount The amount that can be claimed for the refund. * @return claimedBySubmitter `true` if the data has already been claimed by `submitter`, otherwise `false`. * @return numClaims The number of claims that have been made for the contribution before this request. */ function handleRefund(address submitter, int64[] memory data, uint64 classification, uint addedTime) public onlyOwner returns (uint claimableAmount, bool claimedBySubmitter, uint numClaims) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, submitter)); StoredData storage existingData = addedData[key]; // Validate found value. require(existingData.sender != address(0), "Data not found."); // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == submitter, "Data is not from the sender."); claimableAmount = existingData.claimableAmount; claimedBySubmitter = existingData.claimedBy[submitter]; numClaims = existingData.numClaims; // Upon successful completion of the refund the values will be claimed. existingData.claimableAmount = 0; existingData.claimedBy[submitter] = true; existingData.numClaims = numClaims.add(1); } /** * Retrieve information about the data to report. * * @param reporter The address of the one reporting the data. * @param data The data to report. * @param classification The label submitted for `data`. * @param addedTime The time in seconds for which the data was added. * @param originalAuthor The address that originally added the data. * @return initialDeposit The amount that was initially deposited when the data contribution was submitted. * @return claimableAmount The amount remainining that can be claimed. * @return claimedByReporter `true` if the data has already been claimed by `reporter`, otherwise `false`. * @return numClaims The number of claims that have been made for the contribution before this request. * @return dataKey The key to the stored data. */ function handleReport( address reporter, int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public onlyOwner returns (uint initialDeposit, uint claimableAmount, bool claimedByReporter, uint numClaims, bytes32 dataKey) { dataKey = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[dataKey]; // Validate found value. require(existingData.sender != address(0), "Data not found."); // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Sender is not equal."); initialDeposit = existingData.initialDeposit; claimableAmount = existingData.claimableAmount; claimedByReporter = existingData.claimedBy[reporter]; numClaims = existingData.numClaims; existingData.claimedBy[reporter] = true; existingData.numClaims = numClaims.add(1); } /** * @return `true` if the contribution has already been claimed by `claimer`, otherwise `false`. */ function hasClaimed( int64[] memory data, uint64 classification, uint addedTime, address originalAuthor, address claimer) public view returns (bool) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.claimedBy[claimer]; } function updateClaimableAmount(bytes32 dataKey, uint rewardAmount) public override onlyOwner { StoredData storage existingData = addedData[dataKey]; // Already validated key lookup. existingData.claimableAmount = existingData.claimableAmount.sub(rewardAmount); } }
Validate found value. usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
function getNumClaims(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.numClaims; }
12,872,850
./full_match/1/0x997523eF97E0b0a5625Ed2C197e61250acF4e5F1/sources/contracts/extra/ExtraRewardsMultiMerkle.sol
Udpates the Root Manager Udpates the Root Manager newManager Address of the new Root Manager/
function updateRootManager(address newManager) external onlyOwner { if(newManager == address(0)) revert Errors.ZeroAddress(); address oldManager = rootManager; rootManager = newManager; emit UpdateRootManager(oldManager, newManager); }
9,761,002
//SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol"; /** * Request testnet LINK and ETH here: https://faucets.chain.link/ * Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/ */ /** * @notice DO NOT USE THIS CODE IN PRODUCTION. This is an example contract. */ contract GenericLargeResponse is ChainlinkClient { using Chainlink for Chainlink.Request; // variable bytes returned in a signle oracle response bytes public data; string public image_url; /** * @notice Initialize the link token and target oracle * @dev The oracle address must be an Operator contract for multiword response * * * Kovan Testnet details: * Link Token: 0xa36085F69e2889c224210F603D836748e7dC0088 * Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink DevRel) * */ constructor( ) { setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088); setChainlinkOracle(0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8); } /** * @notice Request variable bytes from the oracle */ function requestBytes( ) public { bytes32 specId = "7a97ff8493ec406d90621b2531f9251a"; uint256 payment = 100000000000000000; Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector); req.add("get","https://ipfs.io/ipfs/QmZgsvrA1o1C8BGCrx6mHTqR1Ui1XqbCrtbMVrRLHtuPVD?filename=big-api-response.json"); req.add("path", "image"); sendChainlinkRequest(req, payment); } event RequestFulfilled( bytes32 indexed requestId, bytes indexed data ); /** * @notice Fulfillment function for variable bytes * @dev This is called by the oracle. recordChainlinkFulfillment must be used. */ function fulfillBytes( bytes32 requestId, bytes memory bytesData ) public recordChainlinkFulfillment(requestId) { emit RequestFulfilled(requestId, bytesData); data = bytesData; image_url = string(data); } }
Request variable bytes from the oracle/
function requestBytes( ) public { bytes32 specId = "7a97ff8493ec406d90621b2531f9251a"; uint256 payment = 100000000000000000; Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector); req.add("path", "image"); sendChainlinkRequest(req, payment); } event RequestFulfilled( bytes32 indexed requestId, bytes indexed data );
12,649,312
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IPopsicleV3Optimizer { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @return The address of the Uniswap V3 Pool function pool() external view returns (IUniswapV3Pool); /// @notice The lower tick of the range function tickLower() external view returns (int24); /// @notice The upper tick of the range function tickUpper() external view returns (int24); /** * @notice Deposits tokens in proportion to the Optimizer's current ticks. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param to address that plp should be transfered * @return shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1); /** * @notice Withdraws tokens in proportion to the Optimizer's holdings. * @dev Removes proportional amount of liquidity from Uniswap. * @param shares burned by sender * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1); /** * @notice Updates Optimizer's positions. * @dev Finds base position and limit position for imbalanced token * mints all amounts to this position(including earned fees) */ function rerange() external; /** * @notice Updates Optimizer's positions. Can only be called by the governance. * @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if * we don't have balance during swap because of price impact. * mints all amounts to this position(including earned fees) */ function rebalance() external; } interface IOptimizerStrategy { /// @return Maximul PLP value that could be minted function maxTotalSupply() external view returns (uint256); /// @notice Period of time that we observe for price slippage /// @return time in seconds function twapDuration() external view returns (uint32); /// @notice Maximum deviation of time waited avarage price in ticks function maxTwapDeviation() external view returns (int24); /// @notice Tick multuplier for base range calculation function tickRangeMultiplier() external view returns (int24); /// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6 /// @return The max price impact percentage function priceImpactPercentage() external view returns (uint24); } library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } /// @title Liquidity and ticks functions /// @notice Provides functions for computing liquidity and ticks for token amounts and prices library PoolVariables { using LowGasSafeMath for uint256; using LowGasSafeMath for uint128; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function usersAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } } /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); } /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); } /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions { } /// @title This library is created to conduct a variety of burn liquidity methods library PoolActions { using PoolVariables for IUniswapV3Pool; using LowGasSafeMath for uint256; using SafeCast for uint256; /** * @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply; if (liquidity > 0) { (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128()); if (amount0 > 0 || amount1 > 0) { // collect liquidity share (amount0, amount1) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } } /** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */ function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); } } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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 (r < r1 ? r : r1); } } /** * @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 {LowGasSafeMAth} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using LowGasSafeMath 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 {LowGasSafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } } /// @title Function for getting the current chain ID library ChainId { /// @dev Gets the current chain ID /// @return chainId The current chain ID function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ISS"); require(v == 27 || v == 28, "ISV"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "IS"); return signer; } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = ChainId.get(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (ChainId.get() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, ChainId.get(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 LowGasSafeMath 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_) { _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, "TEA")); 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, "DEB")); 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), "FZA"); require(recipient != address(0), "TZA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TEB"); _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), "MZA"); _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), "BZA"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEB"); _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), "AFZA"); require(spender != address(0), "ATZA"); _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 { } } /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ED"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "IS"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } /// @notice Returns floor(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, floor(x / y) function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := div(x, y) } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); } } /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } } library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param 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'); } } /** * @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, "RC"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } /// @title PopsicleV3 Optimizer is a yield enchancement v3 contract /// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as /// intermediary between the user who wants to provide liquidity to specific pools /// and earn fees from such actions. The contract ensures that user position is in /// range and earns maximum amount of fees available at current liquidity utilization /// rate. contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer { using LowGasSafeMath for uint256; using LowGasSafeMath for uint160; using LowGasSafeMath for uint128; using UnsafeMath for uint256; using SafeCast for uint256; using PoolVariables for IUniswapV3Pool; using PoolActions for IUniswapV3Pool; //Any data passed through by the caller via the IUniswapV3PoolActions#mint call struct MintCallbackData { address payer; } //Any data passed through by the caller via the IUniswapV3PoolActions#swap call struct SwapCallbackData { bool zeroForOne; } /// @notice Emitted when user adds liquidity /// @param sender The address that minted the liquidity /// @param share The amount of share of liquidity added by the user to position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Deposit( address indexed sender, uint256 share, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user withdraws liquidity /// @param sender The address that minted the liquidity /// @param shares of liquidity withdrawn by the user from the position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Withdraw( address indexed sender, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees was collected from the pool /// @param feesFromPool0 Total amount of fees collected in terms of token 0 /// @param feesFromPool1 Total amount of fees collected in terms of token 1 /// @param usersFees0 Total amount of fees collected by users in terms of token 0 /// @param usersFees1 Total amount of fees collected by users in terms of token 1 event CollectFees( uint256 feesFromPool0, uint256 feesFromPool1, uint256 usersFees0, uint256 usersFees1 ); /// @notice Emitted when fees was compuonded to the pool /// @param amount0 Total amount of fees compounded in terms of token 0 /// @param amount1 Total amount of fees compounded in terms of token 1 event CompoundFees( uint256 amount0, uint256 amount1 ); /// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool /// @param tickLower Lower price tick of the positon /// @param tickUpper Upper price tick of the position /// @param amount0 Amount of token 0 deposited to the position /// @param amount1 Amount of token 1 deposited to the position event Rerange( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user collects his fee share /// @param sender User address /// @param fees0 Exact amount of fees claimed by the users in terms of token 0 /// @param fees1 Exact amount of fees claimed by the users in terms of token 1 event RewardPaid( address indexed sender, uint256 fees0, uint256 fees1 ); /// @notice Shows current Optimizer's balances /// @param totalAmount0 Current token0 Optimizer's balance /// @param totalAmount1 Current token1 Optimizer's balance event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance); /// @notice Prevents calls from users modifier onlyGovernance { require(msg.sender == governance, "OG"); _; } /// @inheritdoc IPopsicleV3Optimizer address public immutable override token0; /// @inheritdoc IPopsicleV3Optimizer address public immutable override token1; // WETH address address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @inheritdoc IPopsicleV3Optimizer int24 public immutable override tickSpacing; uint constant MULTIPLIER = 1e6; uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%) //The protocol's fee in hundredths of a bip, i.e. 1e-6 uint24 constant protocolFee = 1e5; mapping (address => bool) private _operatorApproved; // @inheritdoc IPopsicleV3Optimizer IUniswapV3Pool public override pool; // Accrued protocol fees in terms of token0 uint256 public protocolFees0; // Accrued protocol fees in terms of token1 uint256 public protocolFees1; // Total lifetime accrued fees in terms of token0 uint256 public totalFees0; // Total lifetime accrued fees in terms of token1 uint256 public totalFees1; // Address of the Optimizer's owner address public governance; // Pending to claim ownership address address public pendingGovernance; //PopsicleV3 Optimizer settings address address public strategy; // Current tick lower of Optimizer pool position int24 public override tickLower; // Current tick higher of Optimizer pool position int24 public override tickUpper; // Checks if Optimizer is initialized bool public initialized; bool private _paused = false; /** * @dev After deploying, strategy can be set via `setStrategy()` * @param _pool Underlying Uniswap V3 pool with fee = 3000 * @param _strategy Underlying Optimizer Strategy for Optimizer settings */ constructor( address _pool, address _strategy ) ERC20("Popsicle LP V3 USDC/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDC/WETH") { pool = IUniswapV3Pool(_pool); strategy = _strategy; token0 = pool.token0(); token1 = pool.token1(); tickSpacing = pool.tickSpacing(); governance = msg.sender; _operatorApproved[msg.sender] = true; } //initialize strategy function init() external onlyGovernance { require(!initialized, "F"); initialized = true; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); ( , int24 currentTick, , , , , ) = pool.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow } /// @inheritdoc IPopsicleV3Optimizer function deposit( uint256 amount0Desired, uint256 amount1Desired, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 && amount1Desired > 0, "ANV"); _earnFees(); _compoundFees(); // prevent user drains others uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper); // compute the liquidity amount uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper); (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: msg.sender}))); shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER); _mint(to, shares); require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS"); emit Deposit(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function withdraw( uint256 shares, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 amount0, uint256 amount1 ) { require(shares > 0, "S"); require(to != address(0), "WZA"); _earnFees(); _compoundFees(); (amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to); require(amount0 > 0 || amount1 > 0, "EA"); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rerange() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); // Emit snapshot to record balances uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); //Get exact ticks depending on Optimizer's balances (tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rebalance() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); //Calc base ticks (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); PoolVariables.Info memory cache; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); // Calc liquidity for base ticks cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); // Get exact amounts for base ticks (cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); // Get imbalanced token bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); // Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) : int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2 // Calculate Price limit depending on price impact uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); //Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit pool.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, abi.encode(SwapCallbackData({zeroForOne: zeroForOne})) ); (sqrtPriceX96, currentTick, , , , , ) = pool.slot0(); // Emit snapshot to record balances cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); //Get exact ticks depending on Optimizer's new balances (tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); // Add liquidity to the pool (cache.amount0, cache.amount1) = pool.mint( address(this), tickLower, tickUpper, cache.liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); } // Calcs user share depending on deposited amounts function _calcShare(uint256 liquidity, uint256 liquidityLast) internal view returns ( uint256 shares ) { shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast); } /// @dev Amount of token0 held as unused balance. function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); } /// @dev Amount of token1 held as unused balance. function _balance1() internal view returns (uint256) { return IERC20(token1).balanceOf(address(this)).sub(protocolFees1); } /// @dev collects fees from the pool function _earnFees() internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero // Do zero-burns to poke the Uniswap pools so earned fees are updated pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); // Calculate protocol's fees uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1); } function _compoundFees() internal returns (uint256 amount0, uint256 amount1){ uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool if (liquidity > 0) { (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit CompoundFees(amount0, amount1); } } /// @notice Returns current Optimizer's position in pool function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Returns current Optimizer's users amounts in pool function usersAmounts() external view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = pool.usersAmounts(tickLower, tickUpper); } /// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool), "FP"); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0); if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1); } /// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool), "FP"); require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); bool zeroForOne = data.zeroForOne; if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); else pay(token1, address(this), msg.sender, uint256(amount1)); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == weth && address(this).balance >= value) { // pay with WETH9 IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay IWETH9(weth).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } /** * @notice Used to withdraw accumulated protocol fees. */ function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance { _earnFees(); require(protocolFees0 >= amount0, "A0F"); require(protocolFees1 >= amount1, "A1F"); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); require(balance0 >= amount0 && balance1 >= amount1); if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); protocolFees0 = protocolFees0.sub(amount0); protocolFees1 = protocolFees1.sub(amount1); _compoundFees(); emit RewardPaid(msg.sender, amount0, amount1); } // Function modifier that checks if price has not moved a lot recently. // This mitigates price manipulation during rebalance and also prevents placing orders // when it's too volatile. modifier checkDeviation() { pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration()); _; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); emit TransferGovernance(governance, pendingGovernance); pendingGovernance = address(0); governance = msg.sender; } // Sets new strategy contract address for new settings function setStrategy(address _strategy) external onlyGovernance { require(_strategy != address(0), "NA"); strategy = _strategy; } function approveOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = true; } function disableOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = false; } function isOperator(address _operator) external view returns (bool) { return _operatorApproved[_operator]; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "P"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "NP"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() external onlyGovernance whenNotPaused { _paused = true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() external onlyGovernance whenPaused { _paused = false; } }
Check price has not moved a lot recently. This mitigates price manipulation during rebalance and also prevents placing orders when it's too volatile.
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); }
9,338
./partial_match/1/0x3198EAdB777b9b6C789bfc89491774644E95eD7e/sources/contracts/interfaces/pool/ISolidlyV3PoolActions.sol
Permissionless pool actions Contains pool methods that can be called by anyone
interface ISolidlyV3PoolActions { function initialize(uint160 sqrtPriceX96) external; function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, uint256 amount0Min, uint256 amount1Min, uint256 deadline ) external returns (uint256 amount0, uint256 amount1); function burnAndCollect( address recipient, int24 tickLower, int24 tickUpper, uint128 amountToBurn, uint128 amount0ToCollect, uint128 amount1ToCollect ) external returns (uint256 amount0FromBurn, uint256 amount1FromBurn, uint128 amount0Collected, uint128 amount1Collected); function burnAndCollect( address recipient, int24 tickLower, int24 tickUpper, uint128 amountToBurn, uint256 amount0FromBurnMin, uint256 amount1FromBurnMin, uint128 amount0ToCollect, uint128 amount1ToCollect, uint256 deadline ) external returns (uint256 amount0FromBurn, uint256 amount1FromBurn, uint128 amount0Collected, uint128 amount1Collected); function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1); function burn( int24 tickLower, int24 tickUpper, uint128 amount, uint256 amount0Min, uint256 amount1Min, uint256 deadline ) external returns (uint256 amount0, uint256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96 ) external returns (int256 amount0, int256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, uint256 amountLimit, uint256 deadline ) external returns (int256 amount0, int256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, uint256 amountLimit, uint256 deadline, bytes calldata data ) external returns (int256 amount0, int256 amount1); function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external; pragma solidity >=0.5.0; }
15,989,228
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/Factory.sol
@inheritdoc IFactory
function disableWhitelist() external override onlyConfigMaster { whitelistDisabled = true; emit WhitelistDisabled(); }
1,940,562
./full_match/1/0x44C696287E1FC316CAc9C34FbD9e0F64de41A02d/sources/contracts/Farming.sol
deposit If amount is zero, it will claim pending rewards If amount is not zero, it will deposit and reset unlock time _pid {uint256} Pool Id _amount {uint256} Amount of token to deposit/
function deposit( uint256 _pid, uint256 _amount ) external nonReentrant whenNotPaused validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = (user.amount * pool.accTokenPerShare) / SHARE_MULTIPLIER - user.rewardDebt; if (pending > 0) { user.pendingRewards = user.pendingRewards + pending; uint256 claimedAmount = safeTokenTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, _pid, claimedAmount); user.pendingRewards -= claimedAmount; } } if (_amount > 0) { pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); pool.amount += _amount; user.amount += _amount; user.lastClaim = block.timestamp; } user.rewardDebt = (user.amount * pool.accTokenPerShare) / SHARE_MULTIPLIER; emit Deposit(msg.sender, _pid, _amount); }
8,305,556
./full_match/80001/0xe78D2f06d7Ad0cDC884D7DDB65e4BCEdbD212298/sources/_solidstate/contracts/token/ERC20/extended/ERC20ExtendedInternal.sol
decrease spend amount granted to spender spender address whose allowance to decrease amount quantity by which to decrease allowance return success status (always true; otherwise function will revert)/
function _decreaseAllowance( address spender, uint256 amount ) internal virtual returns (bool) { _decreaseAllowance(msg.sender, spender, amount); return true; }
9,525,842
pragma solidity ^0.4.25; contract Control { address owner; struct userData { address userAddress; uint fsmVersion; uint currentState; } struct fsmContractDetail { address contractAddress; string functionName; } userData[] public users; mapping(uint => mapping(uint => mapping(uint=>uint) )) public mapFSM; mapping(uint => mapping(uint => fsmContractDetail)) public mapFSMDetail; uint public versionNumber; // FSM 目前最新的 version (已完成更新的) uint public updatingVersionNumber; // 正在更新的FSM version uint public updateTimeStamp; function () public payable {} constructor() payable{ owner = msg.sender; updatingVersionNumber = 0; versionNumber = 0; } // add general user function addUser(address _userAddress) onlyAdmin{ users.push(userData({ userAddress: _userAddress, fsmVersion: versionNumber, currentState: 0 })); } // admin user update FSM mapping function updateFSM( bool _updateType, // update or delete uint _state, uint _nextState, uint _eventId, string _functionName, address _addressName, bool _finishVersionUpdate // complete version update ) public onlyAdmin{ if(updateTimeStamp != 0 && now - updateTimeStamp > 86400){ // 超過一天後的更新,或是沒有主動完成上一版本,就更新的新版本 updatingVersionNumber = updatingVersionNumber + 1; } if(_updateType){ mapFSMDetail[updatingVersionNumber][_state] = fsmContractDetail({contractAddress: _addressName, functionName: _functionName}); mapFSM[updatingVersionNumber][_state][_eventId] = _nextState; } else { mapFSMDetail[updatingVersionNumber][_state] = fsmContractDetail({contractAddress: 0, functionName: ""}); mapFSM[updatingVersionNumber][_state][_eventId] = 0; } updateTimeStamp = now; if(_finishVersionUpdate){ // 更新完成後,版本號+1 updatingVersionNumber = updatingVersionNumber + 1; versionNumber = updatingVersionNumber - 1; updateTimeStamp = 0; } } function executeNextState(address _userAddress, uint _eventId, uint _functionParameter) public payable{ uint fsmVersion; uint nextState; (nextState,fsmVersion) = userNextState(_userAddress, _eventId); string memory fsmfunction = concatString(mapFSMDetail[fsmVersion][nextState].functionName,'(address)'); bytes4 method = bytes4(keccak256(fsmfunction)); bool callSucceedOrNot = mapFSMDetail[fsmVersion][nextState].contractAddress.call.value(msg.value)(method, _userAddress); if (callSucceedOrNot){ users[getUserIdx(_userAddress)].currentState = nextState; } } function userNextState(address _addr, uint _eventId) returns(uint, uint){ userData user = users[getUserIdx(_addr)]; uint fsmVersion = user.fsmVersion; uint currentState = user.currentState; uint nextState; if(currentState == 0){ nextState = 1; } else { nextState = mapFSM[fsmVersion][currentState][_eventId]; } return (nextState,fsmVersion); } function executeNextStatebytes(address _userAddress, uint _eventId, bytes32 _functionParameter) public payable{ uint fsmVersion; uint nextState; (nextState,fsmVersion) = userNextState(_userAddress, _eventId); string memory fsmfunction = concatString(mapFSMDetail[fsmVersion][nextState].functionName,'(address,bytes32)'); bytes4 method = bytes4(keccak256(fsmfunction)); bool callSucceedOrNot = mapFSMDetail[fsmVersion][nextState].contractAddress.call.value(msg.value)(method, _userAddress, _functionParameter); if (callSucceedOrNot){ users[getUserIdx(_userAddress)].currentState = nextState; } } uint public a; uint public b; string public c; function executeNextStateUint(address _userAddress, uint _eventId, uint _functionParameter) public payable{ uint fsmVersion; uint nextState; (nextState,fsmVersion) = userNextState(_userAddress, _eventId); (a,b) = userNextState(_userAddress, _eventId); c = string(abi.encodePacked(0x00000000000000000000000000000000000000000048656c6c6f20576f726c64)); string memory fsmfunction = concatString(mapFSMDetail[fsmVersion][nextState].functionName,'(address,uint256)'); bytes4 method = bytes4(keccak256(fsmfunction)); bool callSucceedOrNot = mapFSMDetail[fsmVersion][nextState].contractAddress.call.value(msg.value)(method, _userAddress, _functionParameter); if (callSucceedOrNot){ users[getUserIdx(_userAddress)].currentState = nextState; } } function executeNextStatebytesbytesUint(address _userAddress, uint _eventId, bytes32 _p1, bytes32 _p2, uint _p3) public payable{ uint fsmVersion; uint nextState; (nextState,fsmVersion) = userNextState(_userAddress, _eventId); string memory fsmfunction = concatString(mapFSMDetail[fsmVersion][nextState].functionName,'(address,bytes32,,bytes32,uint256)'); bytes4 method = bytes4(keccak256(fsmfunction)); bool callSucceedOrNot = mapFSMDetail[fsmVersion][nextState].contractAddress.call.value(msg.value)(method, _userAddress, _p1, _p2, _p3); if (callSucceedOrNot){ users[getUserIdx(_userAddress)].currentState = nextState; } } // update to the latest version function userUpdateFSMtoNewVersion() public onlyGeneralUser{ uint i = getUserIdx(msg.sender); users[i].fsmVersion = versionNumber; } function getUserIdx(address _userAddress) public view returns(uint){ uint index = 100000; for(uint i = 0; i < users.length; i++){ if (_userAddress == users[i].userAddress){ index = i; } } return index; } function setUserFsmVersionAndState(address _addr, uint _state) public onlyAdmin{ } function compensateMoney(address _addr, uint _money) payable{ _addr.send(_money); } function concatString(string _s1, string _s2) view returns(string) { bytes memory byte_s1 = bytes(_s1); bytes memory byte_s2 = bytes(_s2); string memory concatedString = new string(byte_s1.length + byte_s2.length); bytes memory bret = bytes(concatedString); uint k = 0; for (uint i = 0; i < byte_s1.length; i++)bret[k++] = byte_s1[i]; for (i = 0; i < byte_s2.length; i++) bret[k++] = byte_s2[i]; return concatedString; } modifier onlyAdmin() { require(msg.sender == owner); _; } modifier onlyGeneralUser() { uint i = getUserIdx(msg.sender); require(i < 100000); _; } }
update to the latest version
function userUpdateFSMtoNewVersion() public onlyGeneralUser{ uint i = getUserIdx(msg.sender); users[i].fsmVersion = versionNumber; }
5,440,457
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) { bytecode = _bytecode; } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); // Early return in case that bytes length is 0 if (_length != 0) { bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); } return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (bytes1) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32((int256(1 << uint256(int256(exponent))) * 10000 * int256(uint256(int256(significand)) | 0x400)) >> 10); } else { result = int32(((int256(uint256(int256(significand)) | 0x400) * 10000) / int256(1 << uint256(int256(- exponent)))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { require(_len > 0, "Cannot copy 0 bytes"); // 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)) } } } // File: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint32 constant internal UINT32_MAX = type(uint32).max; uint64 constant internal UINT64_MAX = type(uint64).max; struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bool` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bool` value. */ function decodeBool(Value memory _cborValue) public pure returns(bool) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(_cborValue.majorType == 7, "Tried to read a `bool` value from a `CBOR.Value` with majorType != 7"); if (_cborValue.len == 20) { return false; } else if (_cborValue.len == 21) { return true; } else { revert("Tried to read `bool` from a `CBOR.Value` with len different than 20 or 21"); } } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT32_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) external pure returns(int32[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int32[] memory array = new int32[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(uint128(length)); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(uint128(decodeUint64(_cborValue))); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) external pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) external pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) external pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, 0, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* * STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* * ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } /* * Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) external pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) external pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) external pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) external pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return ErrorCodes.Unknown; } return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns (ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return (ErrorCodes.Unknown, "Unknown error (no error code)"); } ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR && error.length >= 2) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources && error.length >= 2) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls && error.length >= 4) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator && error.length >= 5) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP && error.length >= 3) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout && error.length >= 2) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow && error.length >= 5) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow && error.length >= 5) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero && error.length >= 5) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.BridgeMalformedRequest) { errorMessage = "The structure of the request is invalid and it cannot be parsed"; } else if (errorCode == ErrorCodes.BridgePoorIncentives) { errorMessage = "The request has been rejected by the bridge node due to poor incentives"; } else if (errorCode == ErrorCodes.BridgeOversizedResult) { errorMessage = "The request result length exceeds a bridge contract defined limit"; } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a boolean value from a Result as an `bool` value. * @param _result An instance of Result. * @return The `bool` decoded from the Result. */ function asBool(Result memory _result) external pure returns(bool) { require(_result.success, "Tried to read `bool` value from errored Result"); return _result.cborValue.decodeBool(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) external pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) external pure returns(int32[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) external pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) external pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) external pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) external pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) external pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) external pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { return ErrorCodes(_discriminant); } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = bytes1(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = bytes1(uint8(_u / 10) + 48); b2[1] = bytes1(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = bytes1(uint8(_u / 100) + 48); b3[1] = bytes1(uint8(_u % 100 / 10) + 48); b3[2] = bytes1(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = bytes1(d0); b2[1] = bytes1(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/WitnetRequestBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestBoardInterface { // Event emitted when a new DR is posted event PostedRequest(uint256 _id); // Event emitted when a result is reported event PostedResult(uint256 _id); /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _requestAddress The request contract address which includes the request bytecode. /// @return The unique identifier of the data request. function postDataRequest(address _requestAddress) external payable returns(uint256); /// @dev Increments the reward of a data request by adding the transaction value to it. /// @param _id The unique identifier of the data request. function upgradeDataRequest(uint256 _id) external payable; /// @dev Retrieves the DR transaction hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR transaction function readDrTxHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the Witnet Request Board can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); /// @dev Estimate the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. /// @return The reward to be included for the given gas price. function estimateGasCost(uint256 _gasPrice) external view returns(uint256); } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create Witnet data requests. */ abstract contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestBoardInterface internal immutable wrb; /** * @notice Include an address to specify the WitnetRequestBoard. * @param _wrb WitnetRequestBoard address. */ constructor(address _wrb) { wrb = WitnetRequestBoardInterface(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully resolved by Witnet modifier witnetRequestResolved(uint256 _id) { require(witnetCheckRequestResolved(_id), "Witnet request is not yet resolved by the Witnet network"); _; } /** * @notice Send a new request to the Witnet network with transaction value as result report reward. * @dev Call to `post_dr` function in the WitnetRequestBoard contract. * @param _request An instance of the `Request` contract. * @return Sequencial identifier for the request included in the WitnetRequestBoard. */ function witnetPostRequest(Request _request) internal returns (uint256) { return wrb.postDataRequest{value: msg.value}(address(_request)); } /** * @notice Check if a request has been resolved by Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. * @return A boolean telling if the request has been already resolved or not. */ function witnetCheckRequestResolved(uint256 _id) internal view returns (bool) { // If the result of the data request in Witnet is not the default, then it means that it has been reported as resolved. return wrb.readDrTxHash(_id) != 0; } /** * @notice Upgrade the reward for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestBoard contract. * @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. */ function witnetUpgradeRequest(uint256 _id) internal { wrb.upgradeDataRequest{value: msg.value}(_id); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestBoard contract. * @param _id The unique identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } /** * @notice Estimate the reward amount. * @dev Call to `estimate_gas_cost` function in the WitnetRequestBoard contract. * @param _gasPrice The gas price for which we want to retrieve the estimation. * @return The reward to be included for the given gas price. */ function witnetEstimateGasCost(uint256 _gasPrice) internal view returns (uint256) { return wrb.estimateGasCost(_gasPrice); } } // File: adomedianizer/contracts/interfaces/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abf0108e38eb18706123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc000001003220d0a0908051205fa3fc000001003100a186420012846308094ebdc03") { } } // File: contracts/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { using Witnet for Witnet.Result; // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event PriceUpdated(uint64); // Emits when found an error decoding request result event ResultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "Complete pending request before requesting a new one"); // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestResolved(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); // solhint-disable-next-line not-rely-on-time timestamp = block.timestamp; emit PriceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit ResultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(uint256(lastPrice)); return(value, timestamp, 200); } }
Upgrade the reward for a Data Request previously included. Call to `upgrade_dr` function in the WitnetRequestBoard contract. _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard./
function witnetUpgradeRequest(uint256 _id) internal { }
997,863
./full_match/1/0x0F345F57ee2b395e23390f8e1F1869D7E6C0F70e/sources/contracts/p1/Deployer.sol
effects: Deploy a proxy for Main and every component of Main Call init() on Main and every component of Main, using `params` for needed parameters While doing this, init assetRegistry with this.rsrAsset and a new rTokenAsset Set up Auth so that `owner` holds all roles and no one else has any Main - Proxy Components - Proxies Init StRSR
function deploy( string memory name, string memory symbol, string calldata mandate, address owner, DeploymentParams memory params ) external returns (address) { require(owner != address(0) && owner != address(this), "invalid owner"); MainP1 main = MainP1( address(new ERC1967Proxy(address(implementations.main), new bytes(0))) ); IRToken rToken = IRToken( address(new ERC1967Proxy(address(implementations.components.rToken), new bytes(0))) ); Components memory components = Components({ stRSR: IStRSR( address(new ERC1967Proxy(address(implementations.components.stRSR), new bytes(0))) ), rToken: rToken, assetRegistry: IAssetRegistry( address( new ERC1967Proxy( address(implementations.components.assetRegistry), new bytes(0) ) ) ), basketHandler: IBasketHandler( address( new ERC1967Proxy( address(implementations.components.basketHandler), new bytes(0) ) ) ), backingManager: IBackingManager( address( new ERC1967Proxy( address(implementations.components.backingManager), new bytes(0) ) ) ), distributor: IDistributor( address( new ERC1967Proxy(address(implementations.components.distributor), new bytes(0)) ) ), rsrTrader: IRevenueTrader( address( new ERC1967Proxy(address(implementations.components.rsrTrader), new bytes(0)) ) ), rTokenTrader: IRevenueTrader( address( new ERC1967Proxy(address(implementations.components.rTokenTrader), new bytes(0)) ) ), furnace: IFurnace( address(new ERC1967Proxy(address(implementations.components.furnace), new bytes(0))) ), broker: IBroker( address(new ERC1967Proxy(address(implementations.components.broker), new bytes(0))) ) }); main, params.tradingDelay, params.backingBuffer, params.maxTradeSlippage, params.minTradeVolume ); components.rTokenTrader.init( main, IERC20(address(rToken)), params.maxTradeSlippage, params.minTradeVolume ); components.broker.init(main, gnosis, implementations.trade, params.auctionLength); { string memory stRSRSymbol = string(abi.encodePacked(StringLib.toLower(symbol), "RSR")); string memory stRSRName = string(abi.encodePacked(stRSRSymbol, " Token")); main.stRSR().init( main, stRSRName, stRSRSymbol, params.unstakingDelay, params.rewardPeriod, params.rewardRatio ); } main, semver, name, symbol, mandate, params.issuanceRate, params.scalingRedemptionRate, params.redemptionRateFloor ); assets[0] = new RTokenAsset(components.rToken, params.rTokenMaxTradeVolume); assets[1] = rsrAsset; main.grantRole(SHORT_FREEZER, owner); main.grantRole(LONG_FREEZER, owner); main.grantRole(PAUSER, owner); main.renounceRole(OWNER, address(this)); main.renounceRole(SHORT_FREEZER, address(this)); main.renounceRole(LONG_FREEZER, address(this)); main.renounceRole(PAUSER, address(this)); emit RTokenCreated(main, components.rToken, components.stRSR, owner, semver); return (address(components.rToken)); }
8,486,096
/** *Submitted for verification at Etherscan.io on 2022-03-15 */ // SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // File @openzeppelin/contracts/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File contracts/utils/CvxMintAmount.sol pragma solidity 0.8.9; abstract contract CvxMintAmount { uint256 private constant _CLIFF_SIZE = 100000 * 1e18; //new cliff every 100,000 tokens uint256 private constant _CLIFF_COUNT = 1000; // 1,000 cliffs uint256 private constant _MAX_SUPPLY = 100000000 * 1e18; //100 mil max supply IERC20 private constant _CVX_TOKEN = IERC20(address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)); // CVX Token function getCvxMintAmount(uint256 crvEarned) public view returns (uint256) { //first get total supply uint256 cvxTotalSupply = _CVX_TOKEN.totalSupply(); //get current cliff uint256 currentCliff = cvxTotalSupply / _CLIFF_SIZE; //if current cliff is under the max if (currentCliff >= _CLIFF_COUNT) return 0; //get remaining cliffs uint256 remaining = _CLIFF_COUNT - currentCliff; //multiply ratio of remaining cliffs to total cliffs against amount CRV received uint256 cvxEarned = (crvEarned * remaining) / _CLIFF_COUNT; //double check we have not gone over the max supply uint256 amountTillMax = _MAX_SUPPLY - cvxTotalSupply; if (cvxEarned > amountTillMax) cvxEarned = amountTillMax; return cvxEarned; } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/utils/SlippageTolerance.sol pragma solidity 0.8.9; contract SlippageTolerance is Authorization { using ScaledMath for uint256; uint256 public slippageTolerance; event SetSlippageTolerance(uint256 value); // Emitted after a succuessful setting of slippage tolerance constructor(IRoleManager roleManager) Authorization(roleManager) { slippageTolerance = 0.97e18; } /** * @notice Set slippage tolerance for reward token swaps. * @dev Stored as a multiplier, e.g. 2% would be set as 0.98. * @param _slippageTolerance New imbalance tolarance out. * @return True if successfully set. */ function setSlippageTolerance(uint256 _slippageTolerance) external onlyGovernance returns (bool) { require(_slippageTolerance <= ScaledMath.ONE, Error.INVALID_SLIPPAGE_TOLERANCE); require(_slippageTolerance > 0.8e18, Error.INVALID_SLIPPAGE_TOLERANCE); slippageTolerance = _slippageTolerance; emit SetSlippageTolerance(_slippageTolerance); return true; } } // File interfaces/IERC20Full.sol pragma solidity 0.8.9; /// @notice This is the ERC20 interface including optional getter functions /// The interface is used in the frontend through the generated typechain wrapper interface IERC20Full is IERC20 { function symbol() external view returns (string memory); function name() external view returns (string memory); function decimals() external view returns (uint8); } // File interfaces/vendor/IBooster.sol pragma solidity 0.8.9; interface IBooster { function poolInfo(uint256 pid) external returns ( address lpToken, address token, address gauge, address crvRewards, address stash, bool shutdown ); /** * @dev `_pid` is the ID of the Convex for a specific Curve LP token. */ function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); function depositAll(uint256 _pid, bool _stake) external returns (bool); } // File interfaces/vendor/ICurveSwap.sol pragma solidity 0.8.9; interface ICurveSwap { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata min_amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function coins(uint256 i) external view returns (address); function get_dy( int128 i, int128 j, uint256 _dx ) external view returns (uint256); function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; } // File interfaces/vendor/ICurveSwapEth.sol pragma solidity 0.8.9; interface ICurveSwapEth { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external payable; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata min_amounts) external; function exchange( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external payable; function coins(uint256 i) external view returns (address); function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; } // File interfaces/vendor/IRewardStaking.sol pragma solidity 0.8.9; interface IRewardStaking { function stakeFor(address, uint256) external; function stake(uint256) external; function stakeAll() external returns (bool); function withdraw(uint256 amount, bool claim) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address account) external view returns (uint256); } // File interfaces/vendor/UniswapRouter02.sol pragma solidity 0.8.9; interface UniswapRouter02 { function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( 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 swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external returns (uint256 amountIn); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountOut); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); function getReserves( address factory, address tokenA, address tokenB ) external view returns (uint256 reserveA, uint256 reserveB); function WETH() external pure returns (address); } interface UniswapV2Pair { function getReserves() external view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ); } interface UniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } // File interfaces/vendor/ICurveRegistry.sol pragma solidity 0.8.9; interface ICurveRegistry { function get_pool_from_lp_token(address lpToken) external returns (address); } // File contracts/strategies/BkdTriHopCvx.sol pragma solidity 0.8.9; /** * This is the BkdTriHopCvx strategy, which is designed to be used by a Backd ERC20 Vault. * The strategy holds a given ERC20 underlying and allocates liquidity to Convex via a given Curve Pool. * The Curve Pools used are Meta Pools which first require getting an LP Token from another Curve Pool. * The strategy does a 'Hop' when depositing and withdrawing, by first getting the required LP Token, and then the final LP Token for Convex. * Rewards received on Convex (CVX, CRV), are sold in part for the underlying. * A share of earned CVX & CRV are retained on behalf of the Backd community to participate in governance. */ contract BkdTriHopCvx is IStrategy, CvxMintAmount, SlippageTolerance { using ScaledMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using AddressProviderHelpers for IAddressProvider; uint256 private constant _CURVE_CVX_INDEX = 1; uint256 private constant _CURVE_ETH_INDEX = 0; IBooster internal constant _BOOSTER = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); // Convex Booster Contract ICurveRegistry internal constant _CURVE_REGISTRY = ICurveRegistry(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5); // Curve Registry Contract IERC20 internal constant _CVX = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // CVX IERC20 internal constant _WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH IERC20 internal constant _CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV UniswapRouter02 internal constant _SUSHISWAP = UniswapRouter02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap Router for swaps UniswapRouter02 internal constant _UNISWAP = UniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap Router for swaps ICurveSwapEth internal constant _CVX_ETH_CURVE_POOL = ICurveSwapEth(0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4); // CVX/ETH Curve Pool IAddressProvider internal immutable _addressProvider; // Address provider used for getting oracle provider address public immutable vault; // Backd Vault IERC20 public immutable underlying; // Strategy Underlying ICurveSwap public immutable curveHopPool; // Curve Pool to use for Hops IERC20 public immutable hopLp; // Curve Hop Pool LP Token uint256 public immutable curveHopIndex; // Underlying index in Curve Pool uint256 public immutable decimalMultiplier; // Used for converting between underlying and LP ICurveSwap public curvePool; // Curve Pool uint256 public convexPid; // Index of Convex Pool in Booster Contract uint256 public curveIndex; // Underlying index in Curve Pool IERC20 public lp; // Curve Pool LP Token IRewardStaking public rewards; // Rewards Contract for claiming Convex Rewards uint256 public imbalanceToleranceIn; // Maximum allowed slippage from Curve Pool Imbalance for depositing uint256 public imbalanceToleranceOut; // Maximum allowed slippage from Curve Pool Imbalance for withdrawing uint256 public hopImbalanceToleranceIn; // Maximum allowed slippage from Curve Hop Pool Imbalance for depositing uint256 public hopImbalanceToleranceOut; // Maximum allowed slippage from Curve Hop Pool Imbalance for withdrawing address public communityReserve; // Address for sending CVX & CRV Community Reserve share uint256 public cvxCommunityReserveShare; // Share of CVX sent to Community Reserve uint256 public crvCommunityReserveShare; // Share of CRV sent to Community Reserve address public override strategist; // The strategist for the strategy bool public isShutdown; // If the strategy is shutdown, stops all deposits mapping(address => UniswapRouter02) public tokenDex; // Dex to use for swapping for a given token EnumerableSet.AddressSet private _rewardTokens; // List of additional reward tokens when claiming rewards on Convex event Deposit(uint256 amount); // Emitted after a successfull deposit event Withdraw(uint256 amount); // Emitted after a successful withdrawal event WithdrawAll(uint256 amount); // Emitted after successfully withdrwaing all event Harvest(uint256 amount); // Emitted after a successful harvest event Shutdown(); // Emitted after a successful shutdown event SetCommunityReserve(address reserve); // Emitted after a succuessful setting of reserve event SetCrvCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CRV Community Reserve Share event SetCvxCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CVX Community Reserve Share event SetImbalanceToleranceIn(uint256 value); // Emitted after a succuessful setting of imbalance tolerance in event SetImbalanceToleranceOut(uint256 value); // Emitted after a succuessful setting of imbalance tolerance out event SetHopImbalanceToleranceIn(uint256 value); // Emitted after a succuessful setting of hop imbalance tolerance in event SetHopImbalanceToleranceOut(uint256 value); // Emitted after a succuessful setting of hop imbalance tolerance out event SetStrategist(address strategist); // Emitted after a succuessful setting of strategist event AddRewardToken(address token); // Emitted after successfully adding a new reward token event RemoveRewardToken(address token); // Emitted after successfully removing a reward token event SwapDex(address token, address newDex); // Emitted after successfully swapping a tokens dex modifier onlyVault() { require(msg.sender == vault, Error.UNAUTHORIZED_ACCESS); _; } constructor( address vault_, address strategist_, uint256 convexPid_, uint256 curveIndex_, uint256 curveHopIndex_, IAddressProvider addressProvider_ ) SlippageTolerance(addressProvider_.getRoleManager()) { // Getting data from supporting contracts (address lp_, , , address rewards_, , ) = _BOOSTER.poolInfo(convexPid_); lp = IERC20(lp_); rewards = IRewardStaking(rewards_); address curvePool_ = _CURVE_REGISTRY.get_pool_from_lp_token(lp_); curvePool = ICurveSwap(curvePool_); address hopLp_ = ICurveSwap(curvePool_).coins(curveIndex_); hopLp = IERC20(hopLp_); address curveHopPool_ = _CURVE_REGISTRY.get_pool_from_lp_token(hopLp_); curveHopPool = ICurveSwap(curveHopPool_); address underlying_ = ICurveSwap(curveHopPool_).coins(curveHopIndex_); underlying = IERC20(underlying_); decimalMultiplier = 10**(18 - IERC20Full(underlying_).decimals()); // Setting inputs vault = vault_; strategist = strategist_; convexPid = convexPid_; curveIndex = curveIndex_; curveHopIndex = curveHopIndex_; _addressProvider = IAddressProvider(addressProvider_); // Setting default values imbalanceToleranceIn = 0.001e18; imbalanceToleranceOut = 0.048e18; hopImbalanceToleranceIn = 0.001e18; hopImbalanceToleranceOut = 0.0015e18; // Setting dexes _setDex(address(_CRV), _SUSHISWAP); _setDex(address(_CVX), _SUSHISWAP); _setDex(address(underlying_), _SUSHISWAP); // Approvals IERC20(underlying_).safeApprove(curveHopPool_, type(uint256).max); IERC20(hopLp_).safeApprove(curvePool_, type(uint256).max); IERC20(lp_).safeApprove(address(_BOOSTER), type(uint256).max); IERC20(underlying_).safeApprove(address(_SUSHISWAP), type(uint256).max); _CVX.safeApprove(address(_CVX_ETH_CURVE_POOL), type(uint256).max); _CRV.safeApprove(address(_SUSHISWAP), type(uint256).max); _WETH.safeApprove(address(_SUSHISWAP), type(uint256).max); } /** * @notice Withdraw an amount of underlying to the vault. * @dev This can only be called by the vault. * If the amount is not available, it will be made liquid. * @param amount Amount of underlying to withdraw. * @return True if successful withdrawal. */ function withdraw(uint256 amount) external override onlyVault returns (bool) { if (amount == 0) return false; // Transferring from idle balance if enough uint256 underlyingBalance = _underlyingBalance(); if (underlyingBalance >= amount) { underlying.safeTransfer(vault, amount); emit Withdraw(amount); return true; } // Calculating needed amount of LP to withdraw uint256 requiredUnderlyingAmount = amount - underlyingBalance; uint256 maxHopLpBurned = _maxHopLpBurned(requiredUnderlyingAmount); uint256 requiredHopLpAmount = maxHopLpBurned - _hopLpBalance(); uint256 maxLpBurned = _maxLpBurned(requiredHopLpAmount); uint256 requiredLpAmount = maxLpBurned - _lpBalance(); // Unstaking needed LP Tokens from Convex if (!rewards.withdrawAndUnwrap(requiredLpAmount, false)) return false; // Removing needed liquidity from Curve Pool uint256[2] memory amounts; amounts[curveIndex] = requiredHopLpAmount; curvePool.remove_liquidity_imbalance(amounts, maxLpBurned); // Removing needed liquidity from Curve Hop Pool uint256[3] memory hopAmounts; hopAmounts[curveHopIndex] = requiredUnderlyingAmount; curveHopPool.remove_liquidity_imbalance(hopAmounts, maxHopLpBurned); // Sending underlying to vault underlying.safeTransfer(vault, amount); emit Withdraw(amount); return true; } /** * @notice Shuts down the strategy, disabling deposits. * @return True if reserve was successfully set. */ function shutdown() external override onlyVault returns (bool) { if (isShutdown) return false; isShutdown = true; emit Shutdown(); return true; } /** * @notice Set the address of the communit reserve. * @dev CRV & CVX will be taxed and allocated to the reserve, * such that Backd can participate in governance. * @param _communityReserve Address of the community reserve. * @return True if successfully set. */ function setCommunityReserve(address _communityReserve) external onlyGovernance returns (bool) { communityReserve = _communityReserve; emit SetCommunityReserve(_communityReserve); return true; } /** * @notice Set the share of CRV to send to the Community Reserve. * @param crvCommunityReserveShare_ New fee charged on CRV rewards for governance. * @return True if successfully set. */ function setCrvCommunityReserveShare(uint256 crvCommunityReserveShare_) external onlyGovernance returns (bool) { require(crvCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(communityReserve != address(0), "Community reserve must be set"); crvCommunityReserveShare = crvCommunityReserveShare_; emit SetCrvCommunityReserveShare(crvCommunityReserveShare_); return true; } /** * @notice Set the share of CVX to send to the Community Reserve. * @param cvxCommunityReserveShare_ New fee charged on CVX rewards for governance. * @return True if successfully set. */ function setCvxCommunityReserveShare(uint256 cvxCommunityReserveShare_) external onlyGovernance returns (bool) { require(cvxCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(communityReserve != address(0), "Community reserve must be set"); cvxCommunityReserveShare = cvxCommunityReserveShare_; emit SetCvxCommunityReserveShare(cvxCommunityReserveShare_); return true; } /** * @notice Set imbalance tolerance for Curve Pool deposits. * @dev Stored as a percent, e.g. 1% would be set as 0.01 * @param _imbalanceToleranceIn New imbalance tolarance in. * @return True if successfully set. */ function setImbalanceToleranceIn(uint256 _imbalanceToleranceIn) external onlyGovernance returns (bool) { imbalanceToleranceIn = _imbalanceToleranceIn; emit SetImbalanceToleranceIn(_imbalanceToleranceIn); return true; } /** * @notice Set imbalance tolerance for Curve Pool withdrawals. * @dev Stored as a percent, e.g. 1% would be set as 0.01 * @param _imbalanceToleranceOut New imbalance tolarance out. * @return True if successfully set. */ function setImbalanceToleranceOut(uint256 _imbalanceToleranceOut) external onlyGovernance returns (bool) { imbalanceToleranceOut = _imbalanceToleranceOut; emit SetImbalanceToleranceOut(_imbalanceToleranceOut); return true; } /** * @notice Set hop imbalance tolerance for Curve Hop Pool deposits. * @dev Stored as a percent, e.g. 1% would be set as 0.01 * @param _hopImbalanceToleranceIn New hop imbalance tolarance in. * @return True if successfully set. */ function setHopImbalanceToleranceIn(uint256 _hopImbalanceToleranceIn) external onlyGovernance returns (bool) { hopImbalanceToleranceIn = _hopImbalanceToleranceIn; emit SetHopImbalanceToleranceIn(_hopImbalanceToleranceIn); return true; } /** * @notice Set hop imbalance tolerance for Curve Hop Pool withdrawals. * @dev Stored as a percent, e.g. 1% would be set as 0.01 * @param _hopImbalanceToleranceOut New hop imbalance tolarance out. * @return True if successfully set. */ function setHopImbalanceToleranceOut(uint256 _hopImbalanceToleranceOut) external onlyGovernance returns (bool) { hopImbalanceToleranceOut = _hopImbalanceToleranceOut; emit SetHopImbalanceToleranceOut(_hopImbalanceToleranceOut); return true; } /** * @notice Set strategist. * @dev Can only be set by current strategist. * @param _strategist Address of new strategist. * @return True if successfully set. */ function setStrategist(address _strategist) external returns (bool) { require(msg.sender == strategist, Error.UNAUTHORIZED_ACCESS); strategist = _strategist; emit SetStrategist(_strategist); return true; } /** * @notice Add a reward token to list of extra reward tokens. * @dev These are tokens that are not the main assets of the strategy. For instance, temporary incentives. * @param token Address of token to add to reward token list. * @return True if successfully added. */ function addRewardToken(address token) external onlyGovernance returns (bool) { require( token != address(_CVX) && token != address(underlying) && token != address(_CRV) && token != address(_WETH), Error.INVALID_TOKEN_TO_ADD ); if (_rewardTokens.contains(token)) return false; _rewardTokens.add(token); _setDex(token, _SUSHISWAP); IERC20(token).safeApprove(address(_SUSHISWAP), 0); IERC20(token).safeApprove(address(_SUSHISWAP), type(uint256).max); emit AddRewardToken(token); return true; } /** * @notice Remove a reward token. * @param token Address of token to remove from reward token list. * @return True if successfully removed. */ function removeRewardToken(address token) external onlyGovernance returns (bool) { if (!_rewardTokens.remove(token)) return false; emit RemoveRewardToken(token); return true; } /** * @notice Set the DEX that should be used for swapping for a specific coin. * If Uniswap is active, it will switch to SushiSwap and vice versa. * @dev Only SushiSwap and Uniswap are supported. * @param token Address of token for which the DEX should be updated. */ function swapDex(address token) external onlyGovernance returns (bool) { UniswapRouter02 currentDex = tokenDex[token]; require(address(currentDex) != address(0), Error.NO_DEX_SET); UniswapRouter02 newDex = currentDex == _SUSHISWAP ? _UNISWAP : _SUSHISWAP; _setDex(token, newDex); IERC20(token).safeApprove(address(newDex), 0); IERC20(token).safeApprove(address(newDex), type(uint256).max); emit SwapDex(token, address(newDex)); return true; } /** * @notice Changes the Convex Pool used for farming yield, e.g. from FRAX to MIM. * @dev First withdraws all funds, then harvests any rewards, then changes pool, then deposits again. * @param convexPid_ The PID for the new Convex Pool. * @param curveIndex_ The index of the new Convex Pool Token in the new Curve Pool. */ function changeConvexPool(uint256 convexPid_, uint256 curveIndex_) external onlyGovernance { _harvest(); _withdrawAllToHopLp(); convexPid = convexPid_; curveIndex = curveIndex_; (address lp_, , , address rewards_, , ) = _BOOSTER.poolInfo(convexPid_); lp = IERC20(lp_); rewards = IRewardStaking(rewards_); address curvePool_ = _CURVE_REGISTRY.get_pool_from_lp_token(lp_); curvePool = ICurveSwap(curvePool_); IERC20(hopLp).safeApprove(curvePool_, 0); IERC20(hopLp).safeApprove(curvePool_, type(uint256).max); IERC20(lp_).safeApprove(address(_BOOSTER), 0); IERC20(lp_).safeApprove(address(_BOOSTER), type(uint256).max); require(_deposit(), Error.DEPOSIT_FAILED); } /** * @notice Returns the name of the strategy. * @return The name of the strategy. */ function name() external view override returns (string memory) { return "BkdTriHopCvx"; } /** * @notice Amount of rewards that can be harvested in the underlying. * @dev Includes rewards for CRV & CVX. * @return Estimated amount of underlying available to harvest. */ function harvestable() external view override returns (uint256) { uint256 crvAmount_ = rewards.earned(address(this)); if (crvAmount_ == 0) return 0; return _underlyingAmountOut( _CRV, crvAmount_.scaledMul(ScaledMath.ONE - crvCommunityReserveShare) ) + _underlyingAmountOut( _CVX, getCvxMintAmount(crvAmount_).scaledMul(ScaledMath.ONE - cvxCommunityReserveShare) ); } /** * @dev Contract does not stash tokens. */ function hasPendingFunds() external pure override returns (bool) { return false; } /** * @notice Deposit all available underlying into Convex pool. * @dev Liquidity is added to Curve Pool then Curve LP tokens are deposited * into Convex and Convex LP tokens are staked for rewards by default. * @return True if successful deposit. */ function deposit() public payable override onlyVault returns (bool) { return _deposit(); } /** * @notice Withdraw all underlying. * @dev This does not liquidate reward tokens and only considers * idle underlying, idle lp tokens and staked lp tokens. * @return Amount of underlying withdrawn */ function withdrawAll() public override returns (uint256) { require( msg.sender == vault || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS ); // Withdrawing all from Convex and converting to Hop LP Token _withdrawAllToHopLp(); // Removing liquidity from Curve Hop Pool uint256 hopLpBalance = _hopLpBalance(); if (hopLpBalance > 0) { curveHopPool.remove_liquidity_one_coin( hopLpBalance, int128(uint128(curveHopIndex)), _minUnderlyingAccepted(hopLpBalance) ); } // Transferring underlying to vault uint256 underlyingBalance = _underlyingBalance(); if (underlyingBalance == 0) return 0; underlying.safeTransfer(vault, underlyingBalance); emit WithdrawAll(underlyingBalance); return underlyingBalance; } /** * @notice Harvests reward tokens and sells these for the underlying. * @dev Any underlying harvested is not redeposited by this method. * @return Amount of underlying harvested. */ function harvest() public override onlyVault returns (uint256) { return _harvest(); } /** * @notice Get the total underlying balance of the strategy. * @dev This includes idle underlying, idle LP and LP deposited on Convex. * @return Underlying balance of strategy. */ function balance() public view override returns (uint256) { return _underlyingBalance() + _hopLpToUnderlying(_lpToHopLp(_stakedBalance() + _lpBalance()) + _hopLpBalance()); } /** * @dev Set the dex to use for a token. * @param token Address of token to set the dex for. * @param dex Dex to use for swaps with that token. */ function _setDex(address token, UniswapRouter02 dex) internal { tokenDex[token] = dex; } /** * @notice Swaps all balance of a token for WETH. * @param token Address of the token to swap for WETH. */ function _swapAllForWeth(IERC20 token) internal { uint256 amount = token.balanceOf(address(this)); return _swapForWeth(token, amount); } /** * @notice Swaps a token for WETH. * @param token Address of the token to swap for WETH. * @param amount Amount of the token to swap for WETH. */ function _swapForWeth(IERC20 token, uint256 amount) internal { if (amount == 0) return; // Handling CVX Swaps if (address(token) == address(_CVX)) { _CVX_ETH_CURVE_POOL.exchange( _CURVE_CVX_INDEX, _CURVE_ETH_INDEX, amount, amount .scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(_CVX))) .scaledMul(slippageTolerance) ); return; } // Handling other swaps address[] memory path = new address[](2); path[0] = address(token); path[1] = address(_WETH); tokenDex[address(token)].swapExactTokensForTokens( amount, amount .scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(token))) .scaledMul(slippageTolerance), path, address(this), block.timestamp ); } /** * @notice Swaps all available WETH for underlying. */ function _swapWethForUnderlying() internal { uint256 wethBalance = _WETH.balanceOf(address(this)); if (wethBalance == 0) return; address[] memory path = new address[](2); path[0] = address(_WETH); path[1] = address(underlying); tokenDex[address(underlying)].swapExactTokensForTokens( wethBalance, wethBalance .scaledDiv(_addressProvider.getOracleProvider().getPriceETH(address(underlying))) .scaledMul(slippageTolerance) / decimalMultiplier, path, address(this), block.timestamp ); } /** * @notice Sends a share of the current balance of CRV and CVX to the Community Reserve. */ function _sendCommunityReserveShare() internal { address communityReserve_ = communityReserve; if (communityReserve_ == address(0)) return; uint256 cvxCommunityReserveShare_ = cvxCommunityReserveShare; if (cvxCommunityReserveShare_ > 0) { uint256 cvxBalance_ = _CVX.balanceOf(address(this)); if (cvxBalance_ > 0) { _CVX.safeTransfer( communityReserve_, cvxBalance_.scaledMul(cvxCommunityReserveShare_) ); } } uint256 crvCommunityReserveShare_ = crvCommunityReserveShare; if (crvCommunityReserveShare_ > 0) { uint256 crvBalance_ = _CRV.balanceOf(address(this)); if (crvBalance_ > 0) { _CRV.safeTransfer( communityReserve_, crvBalance_.scaledMul(crvCommunityReserveShare_) ); } } } /** * @dev Get the balance of the underlying. */ function _underlyingBalance() internal view returns (uint256) { return underlying.balanceOf(address(this)); } /** * @dev Get the balance of the hop lp. */ function _hopLpBalance() internal view returns (uint256) { return hopLp.balanceOf(address(this)); } /** * @dev Get the balance of the lp. */ function _lpBalance() internal view returns (uint256) { return lp.balanceOf(address(this)); } /** * @dev Get the balance of the underlying staked in the Curve pool. */ function _stakedBalance() internal view returns (uint256) { return rewards.balanceOf(address(this)); } /** * @notice Gets the amount of underlying that would be received by selling the token. * @dev Uses WETH as intermediate in swap path. * @return Underlying amount that would be received. */ function _underlyingAmountOut(IERC20 token, uint256 amountIn) internal view returns (uint256) { if (amountIn == 0) return 0; address[] memory path; if (token == _CVX) { IERC20 underlying_ = underlying; path = new address[](2); path[0] = address(_WETH); path[1] = address(underlying_); return tokenDex[address(underlying_)].getAmountsOut( _CVX_ETH_CURVE_POOL.get_dy(_CURVE_CVX_INDEX, _CURVE_ETH_INDEX, amountIn), path )[1]; } path = new address[](3); path[0] = address(token); path[1] = address(_WETH); path[2] = address(underlying); return tokenDex[address(token)].getAmountsOut(amountIn, path)[2]; } /** * @notice Calculates the minimum LP to accept when depositing underlying into Curve Pool. * @param _hopLpAmount Amount of Hop LP that is being deposited into Curve Pool. * @return The minimum LP balance to accept. */ function _minLpAccepted(uint256 _hopLpAmount) internal view returns (uint256) { return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceIn); } /** * @notice Calculates the maximum LP to accept burning when withdrawing amount from Curve Pool. * @param _hopLpAmount Amount of Hop LP that is being widthdrawn from Curve Pool. * @return The maximum LP balance to accept burning. */ function _maxLpBurned(uint256 _hopLpAmount) internal view returns (uint256) { return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE + imbalanceToleranceOut); } /** * @notice Calculates the minimum Hop LP to accept when burning LP tokens to withdraw from Curve Pool. * @param _lpAmount Amount of LP tokens being burned to withdraw from Curve Pool. * @return The mininum Hop LP balance to accept. */ function _minHopLpAcceptedFromWithdraw(uint256 _lpAmount) internal view returns (uint256) { return _lpToHopLp(_lpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceOut); } /** * @notice Calculates the minimum Hop LP to accept when depositing underlying into Curve Hop Pool. * @param _underlyingAmount Amount of underlying that is being deposited into Curve Hop Pool. * @return The minimum Hop LP balance to accept. */ function _minHopLpAcceptedFromDeposit(uint256 _underlyingAmount) internal view returns (uint256) { return _underlyingToHopLp(_underlyingAmount).scaledMul( ScaledMath.ONE - hopImbalanceToleranceIn ); } /** * @notice Calculates the maximum Hop LP to accept burning when withdrawing amount from Curve Hop Pool. * @param _underlyingAmount Amount of underlying that is being widthdrawn from Curve Hop Pool. * @return The maximum Hop LP balance to accept burning. */ function _maxHopLpBurned(uint256 _underlyingAmount) internal view returns (uint256) { return _underlyingToHopLp(_underlyingAmount).scaledMul( ScaledMath.ONE + hopImbalanceToleranceOut ); } /** * @notice Calculates the minimum underlying to accept when burning Hop LP tokens to withdraw from Curve Hop Pool. * @param _hopLpAmount Amount of Hop LP tokens being burned to withdraw from Curve Hop Pool. * @return The mininum underlying balance to accept. */ function _minUnderlyingAccepted(uint256 _hopLpAmount) internal view returns (uint256) { return _hopLpToUnderlying(_hopLpAmount).scaledMul(ScaledMath.ONE - hopImbalanceToleranceOut); } /** * @notice Converts an amount of underlying into their estimated Hop LP value. * @dev Uses get_virtual_price which is less suceptible to manipulation. * But is also less accurate to how much could be withdrawn. * @param _underlyingAmount Amount of underlying to convert. * @return The estimated value in the Hop LP. */ function _underlyingToHopLp(uint256 _underlyingAmount) internal view returns (uint256) { return (_underlyingAmount * decimalMultiplier).scaledDiv(curveHopPool.get_virtual_price()); } /** * @notice Converts an amount of Hop LP into their estimated underlying value. * @dev Uses get_virtual_price which is less suceptible to manipulation. * But is also less accurate to how much could be withdrawn. * @param _hopLpAmount Amount of Hop LP to convert. * @return The estimated value in the underlying. */ function _hopLpToUnderlying(uint256 _hopLpAmount) internal view returns (uint256) { return (_hopLpAmount / decimalMultiplier).scaledMul(curveHopPool.get_virtual_price()); } /** * @notice Converts an amount of LP into their estimated Hop LP value. * @dev Uses get_virtual_price which is less suceptible to manipulation. * But is also less accurate to how much could be withdrawn. * @param _lpAmount Amount of underlying to convert. * @return The estimated value in the Hop LP. */ function _lpToHopLp(uint256 _lpAmount) internal view returns (uint256) { return _lpAmount.scaledMul(curvePool.get_virtual_price()).scaledDiv( curveHopPool.get_virtual_price() ); } /** * @notice Converts an amount of Hop LP into their estimated LP value. * @dev Uses get_virtual_price which is less suceptible to manipulation. * But is also less accurate to how much could be withdrawn. * @param _hopLpAmount Amount of Hop LP to convert. * @return The estimated value in the LP. */ function _hopLpToLp(uint256 _hopLpAmount) internal view returns (uint256) { return _hopLpAmount.scaledMul(curveHopPool.get_virtual_price()).scaledDiv( curvePool.get_virtual_price() ); } /** * @dev Deposit all available underlying into Convex pool. * @return True if successful deposit. */ function _deposit() private returns (bool) { require(msg.value == 0, Error.INVALID_VALUE); require(!isShutdown, Error.STRATEGY_SHUT_DOWN); // Depositing into Curve Hop Pool uint256 underlyingBalance = _underlyingBalance(); if (underlyingBalance > 0) { uint256[3] memory hopAmounts; hopAmounts[curveHopIndex] = underlyingBalance; curveHopPool.add_liquidity(hopAmounts, _minHopLpAcceptedFromDeposit(underlyingBalance)); } // Depositing into Curve Pool uint256 hopLpBalance = _hopLpBalance(); if (hopLpBalance > 0) { uint256[2] memory amounts; amounts[curveIndex] = hopLpBalance; curvePool.add_liquidity(amounts, _minLpAccepted(hopLpBalance)); } // Depositing into Convex and Staking if (_lpBalance() == 0) return false; if (!_BOOSTER.depositAll(convexPid, true)) return false; emit Deposit(underlyingBalance); return true; } /** * @dev Withdraw all underlying and convert to the Hop LP Token. */ function _withdrawAllToHopLp() private { // Unstaking and withdrawing from Convex pool uint256 stakedBalance = _stakedBalance(); if (stakedBalance > 0) { rewards.withdrawAndUnwrap(stakedBalance, false); } // Removing liquidity from Curve Pool uint256 lpBalance = _lpBalance(); if (lpBalance > 0) { curvePool.remove_liquidity_one_coin( lpBalance, int128(uint128(curveIndex)), _minHopLpAcceptedFromWithdraw(lpBalance) ); } } function _harvest() private returns (uint256) { uint256 initialBalance = _underlyingBalance(); // Claim Convex rewards rewards.getReward(); // Sending share to Community Reserve _sendCommunityReserveShare(); // Swap CVX for WETH _swapAllForWeth(_CVX); // Swap CRV for WETH _swapAllForWeth(_CRV); // Swap Extra Rewards for WETH for (uint256 i = 0; i < _rewardTokens.length(); i++) { _swapAllForWeth(IERC20(_rewardTokens.at(i))); } // Swap WETH for underlying _swapWethForUnderlying(); uint256 harvested = _underlyingBalance() - initialBalance; emit Harvest(harvested); return harvested; } }
Calculates the minimum Hop LP to accept when depositing underlying into Curve Hop Pool. _underlyingAmount Amount of underlying that is being deposited into Curve Hop Pool. return The minimum Hop LP balance to accept./
function _minHopLpAcceptedFromDeposit(uint256 _underlyingAmount) internal view returns (uint256) { return _underlyingToHopLp(_underlyingAmount).scaledMul( ScaledMath.ONE - hopImbalanceToleranceIn ); }
2,187,046
pragma solidity ^0.4.24; /** * Version: 0.1.0 * The ERC-1384 is an Equity Agreement Standard used for smart contracts on Ethereum * blockchain for project equity allocation. * The current ERC-1384 agreement standard version is 0.1.0, which includes the basic * information of the project query, equity creation, confirmation of equity validity, * equity transfer, record of equity transfer and other functions. */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } contract ERC20 { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ERC1384Interface { function name() external view returns (string _name); function FasNum() external view returns (uint256 _FasNum); function owner() external view returns (address _owner); function createTime() external view returns (uint256 _createTime); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _FasId) public view returns (address _owner); function exists(uint256 _FasId) public view returns (bool); function allOwnedFas(address _owner) public view returns (uint256[] _allOwnedFasList); function getTransferRecords(uint256 _FasId) public view returns (address[] _preOwners); function transfer(address _to, uint256[] _FasId) public; function createVote() public payable returns (uint256 _voteId); function vote(uint256 _voteId, uint256 _vote_status_value) public; function getVoteResult(uint256 _voteId) public payable returns (bool result); function dividend(address _token_owner) public; event Transfer( address indexed _from, address indexed _to, uint256 indexed _FasId ); event Vote( uint256 _voteId ); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address internal project_owner; address internal new_project_owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { project_owner = msg.sender; } modifier onlyOwner { require(msg.sender == project_owner); _; } function transferOwnership(address _new_project_owner) public onlyOwner { new_project_owner = _new_project_owner; } } contract ERC1384BasicContract is ERC1384Interface, Owned { using SafeMath for uint256; // Project Name string internal proejct_name; // Project Fas Number uint256 internal project_fas_number; // Project Create Time uint256 internal project_create_time; // Owner Number uint256 internal owners_num; // Vote Number uint256 internal votes_num; address internal token_0x_address; /** * @dev Constructor function */ constructor(string _project_name, address _token_0x_address) public { proejct_name = _project_name; project_fas_number = 100; project_create_time = block.timestamp; token_0x_address = _token_0x_address; for(uint i = 0; i < project_fas_number; i++) { FasOwner[i] = project_owner; ownedFasCount[project_owner] = ownedFasCount[project_owner].add(1); address[1] memory preOwnerList = [project_owner]; transferRecords[i] = preOwnerList; } owners_num = 0; votes_num = 0; ownerExists[project_owner] = true; addOwnerNum(project_owner); } /** * @dev Gets the project name * @return string representing the project name */ function name() external view returns (string) { return proejct_name; } /** * @dev Gets the project Fas number * @return uint256 representing the project Fas number */ function FasNum() external view returns (uint256) { return project_fas_number; } /** * @dev Gets the project owner * @return address representing the project owner */ function owner() external view returns (address) { return project_owner; } /** * @dev Gets the project create time * @return uint256 representing the project create time */ function createTime() external view returns (uint256) { return project_create_time; } // Mapping from number of owner to owner mapping (uint256 => address) internal ownerNum; mapping (address => bool) internal ownerExists; // Mapping from Fas ID to owner mapping (uint256 => address) internal FasOwner; // Mapping from owner to number of owned Fas mapping (address => uint256) internal ownedFasCount; // Mapping from Fas ID to approved address mapping (uint256 => address) internal FasApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; // Mapping from Fas ID to previous owners mapping (uint256 => address[]) internal transferRecords; // Mapping from vote ID to vote result mapping (uint256 => mapping (uint256 => uint256)) internal voteResult; function acceptOwnership() public { require(msg.sender == new_project_owner); emit OwnershipTransferred(project_owner, new_project_owner); transferForOwnerShip(project_owner, new_project_owner, allOwnedFas(project_owner)); project_owner = new_project_owner; new_project_owner = address(0); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedFasCount[_owner]; } /** * @dev Gets the owner of the specified Fas ID * @param _FasId uint256 ID of the Fas to query the owner of * @return owner address currently marked as the owner of the given Fas ID */ function ownerOf(uint256 _FasId) public view returns (address) { address _owner = FasOwner[_FasId]; require(_owner != address(0)); return _owner; } /** * @dev Returns whether the specified Fas exists * @param _FasId uint256 ID of the Fas to query the existence of * @return whether the Fas exists */ function exists(uint256 _FasId) public view returns (bool) { address _owner = FasOwner[_FasId]; return _owner != address(0); } /** * @dev Gets the owner of all owned Fas * @param _owner address to query the balance of * @return the FasId list of owners */ function allOwnedFas(address _owner) public view returns (uint256[]) { uint256 _ownedFasCount = ownedFasCount[_owner]; uint256 j = 0; uint256[] memory _allOwnedFasList = new uint256[](_ownedFasCount); for(uint256 i = 0; i < project_fas_number; i++) { if(FasOwner[i] == _owner) { _allOwnedFasList[j] = i; j = j.add(1); } } return _allOwnedFasList; } /** * @dev Internal function to add Owner Count to the list of a given address * @param _owner address representing the new owner */ function addOwnerNum(address _owner) internal { require(ownedFasCount[_owner] != 0); if(ownerExists[_owner] == false) { ownerNum[owners_num] = _owner; owners_num = owners_num.add(1); ownerExists[_owner] = true; } } /** * @dev Internal function to add a Fas ID to the list of a given address * @param _to address representing the new owner of the given Fas ID * @param _FasId uint256 ID of the Fas to be added to the Fas list of the given address */ function addFasTo(address _to, uint256 _FasId) internal { require(FasOwner[_FasId] == address(0)); FasOwner[_FasId] = _to; ownedFasCount[_to] = ownedFasCount[_to].add(1); } /** * @dev Internal function to remove a Fas ID from the list of a given address * @param _from address representing the previous owner of the given Fas ID * @param _FasId uint256 ID of the Fas to be removed from the Fas list of the given address */ function removeFasFrom(address _from, uint256 _FasId) internal { require(ownerOf(_FasId) == _from); ownedFasCount[_from] = ownedFasCount[_from].sub(1); FasOwner[_FasId] = address(0); } /** * @dev Returns whether the given spender can transfer a given Fas ID * @param _spender address of the spender to query * @param _FasId uint256 ID of the Fas to be transferred * @return bool whether the msg.sender is approved for the given Fas ID, * is an operator of the owner, or is the owner of the Fas */ function isOwner(address _spender, uint256 _FasId) internal view returns (bool){ address _owner = ownerOf(_FasId); return (_spender == _owner); } /** * @dev Record the transfer records for a Fas ID * @param _FasId uint256 ID of the Fas * @return bool record */ function transferRecord(address _nowOwner, uint256 _FasId) internal{ address[] memory preOwnerList = transferRecords[_FasId]; address[] memory _preOwnerList = new address[](preOwnerList.length + 1); for(uint i = 0; i < _preOwnerList.length; ++i) { if(i != preOwnerList.length) { _preOwnerList[i] = preOwnerList[i]; } else { _preOwnerList[i] = _nowOwner; } } transferRecords[_FasId] = _preOwnerList; } /** * @dev Gets the transfer records for a Fas ID * @param _FasId uint256 ID of the Fas * @return address of previous owners */ function getTransferRecords(uint256 _FasId) public view returns (address[]) { return transferRecords[_FasId]; } /** * @dev Transfers the ownership of a given Fas ID to a specified address * @param _project_owner the address of _project_owner * @param _to address to receive the ownership of the given Fas ID * @param _FasId uint256 ID of the Fas to be transferred */ function transferForOwnerShip(address _project_owner,address _to, uint256[] _FasId) internal{ for(uint i = 0; i < _FasId.length; i++) { require(isOwner(_project_owner, _FasId[i])); require(_to != address(0)); transferRecord(_to, _FasId[i]); removeFasFrom(_project_owner, _FasId[i]); addFasTo(_to, _FasId[i]); } addOwnerNum(_to); } /** * @dev Transfers the ownership of a given Fas ID to a specified address * @param _to address to receive the ownership of the given Fas ID * @param _FasId uint256 ID of the Fas to be transferred */ function transfer(address _to, uint256[] _FasId) public{ for(uint i = 0; i < _FasId.length; i++) { require(isOwner(msg.sender, _FasId[i])); require(_to != address(0)); transferRecord(_to, _FasId[i]); removeFasFrom(msg.sender, _FasId[i]); addFasTo(_to, _FasId[i]); emit Transfer(msg.sender, _to, _FasId[i]); } addOwnerNum(_to); } /** * @dev Create a new vote * @return the new vote of ID */ function createVote() public payable returns (uint256){ votes_num = votes_num.add(1); // Vote Agree Number voteResult[votes_num][0] = 0; // Vote Disagree Number voteResult[votes_num][1] = 0; // Vote Abstain Number voteResult[votes_num][2] = 0; // Start Voting Time voteResult[votes_num][3] = block.timestamp; emit Vote(votes_num); return votes_num; } /** * @dev Voting for a given vote ID * @param _voteId the given vote ID * @param _vote_status_value uint256 the vote of status, 0 Agree, 1 Disagree, 2 Abstain */ function vote(uint256 _voteId, uint256 _vote_status_value) public{ require(_vote_status_value >= 0); require(_vote_status_value <= 2); require(block.timestamp <= (voteResult[_voteId][3] + 1 days)); uint256 temp_Fas_count = balanceOf(msg.sender); if(_vote_status_value == 0) { voteResult[_voteId][0] = voteResult[_voteId][0].add(temp_Fas_count); } else if(_vote_status_value == 1) { voteResult[_voteId][1] = voteResult[_voteId][1].add(temp_Fas_count); } else { voteResult[_voteId][2] = voteResult[_voteId][2].add(temp_Fas_count); } } /** * @dev Gets the voting restult for a vote ID * @param _voteId the given vote ID * @return the voting restult, true success, false failure */ function getVoteResult(uint256 _voteId) public payable returns (bool){ require(block.timestamp > (voteResult[_voteId][3] + 1 days)); uint agree_num = voteResult[_voteId][0]; uint disagree_num = voteResult[_voteId][1]; uint abstain_num = voteResult[_voteId][2]; uint temp_abstain_num = 100 - agree_num - disagree_num; if(temp_abstain_num != abstain_num) { voteResult[_voteId][2] = temp_abstain_num; } if(agree_num > disagree_num) { return true; } else { return false; } } /** * @dev Distribution of benefits * @param _token_owner Divider's Token address */ function dividend(address _token_owner) public{ uint256 temp_allowance = ERC20(token_0x_address).allowance(_token_owner, address(this)); for(uint i = 0; i < owners_num; i++) { uint256 temp_Fas_count = balanceOf(ownerNum[i]); uint256 _dividend = temp_allowance * temp_Fas_count / 100; ERC20(token_0x_address).transferFrom(_token_owner, ownerNum[i], _dividend); } } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
Create a new vote return the new vote of ID/ Vote Agree Number Vote Disagree Number Vote Abstain Number Start Voting Time
function createVote() public payable returns (uint256){ votes_num = votes_num.add(1); voteResult[votes_num][0] = 0; voteResult[votes_num][1] = 0; voteResult[votes_num][2] = 0; voteResult[votes_num][3] = block.timestamp; emit Vote(votes_num); return votes_num; }
12,981,265
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // 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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; interface IAuthorizerAdaptor is IAuthentication { /** * @notice Returns the Balancer Vault */ function getVault() external view returns (IVault); /** * @notice Returns the Authorizer */ function getAuthorizer() external view returns (IAuthorizer); /** * @notice Performs an arbitrary function call on a target contract, provided the caller is authorized to do so. * @param target - Address of the contract to be called * @param data - Calldata to be sent to the target contract * @return The bytes encoded return value from the performed function call */ function performAction(address target, bytes calldata data) external payable returns (bytes memory); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IAuthorizerAdaptor.sol"; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IVotingEscrow { struct Point { int128 bias; int128 slope; // - dweight / dt uint256 ts; uint256 blk; // block } function epoch() external view returns (uint256); function totalSupply(uint256 timestamp) external view returns (uint256); function user_point_epoch(address user) external view returns (uint256); function point_history(uint256 timestamp) external view returns (Point memory); function user_point_history(address user, uint256 timestamp) external view returns (Point memory); function checkpoint() external; function admin() external view returns (IAuthorizerAdaptor); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./IBalancerTokenAdmin.sol"; import "./IGaugeController.sol"; interface IBalancerMinter { event Minted(address indexed recipient, address gauge, uint256 minted); /** * @notice Returns the address of the Balancer Governance Token */ function getBalancerToken() external view returns (IERC20); /** * @notice Returns the address of the Balancer Token Admin contract */ function getBalancerTokenAdmin() external view returns (IBalancerTokenAdmin); /** * @notice Returns the address of the Gauge Controller */ function getGaugeController() external view returns (IGaugeController); /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge `LiquidityGauge` address to get mintable amount from */ function mint(address gauge) external returns (uint256); /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauges List of `LiquidityGauge` addresses */ function mintMany(address[] calldata gauges) external returns (uint256); /** * @notice Mint tokens for `user` * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauge `LiquidityGauge` address to get mintable amount from * @param user Address to mint to */ function mintFor(address gauge, address user) external returns (uint256); /** * @notice Mint tokens for `user` across multiple gauges * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauges List of `LiquidityGauge` addresses * @param user Address to mint to */ function mintManyFor(address[] calldata gauges, address user) external returns (uint256); /** * @notice The total number of tokens minted for `user` from `gauge` */ function minted(address user, address gauge) external view returns (uint256); /** * @notice Whether `minter` is approved to mint tokens for `user` */ function getMinterApproval(address minter, address user) external view returns (bool); /** * @notice Set whether `minter` is approved to mint tokens on your behalf */ function setMinterApproval(address minter, bool approval) external; /** * @notice Set whether `minter` is approved to mint tokens on behalf of `user`, who has signed a message authorizing * them. */ function setMinterApprovalWithSignature( address minter, bool approval, address user, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // The below functions are near-duplicates of functions available above. // They are included for ABI compatibility with snake_casing as used in vyper contracts. // solhint-disable func-name-mixedcase /** * @notice Whether `minter` is approved to mint tokens for `user` */ function allowed_to_mint_for(address minter, address user) external view returns (bool); /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @dev This function is not recommended as `mintMany()` is more flexible and gas efficient * @param gauges List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauges) external; /** * @notice Mint tokens for `user` * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauge `LiquidityGauge` address to get mintable amount from * @param user Address to mint to */ function mint_for(address gauge, address user) external; /** * @notice Toggle whether `minter` is approved to mint tokens for `user` */ function toggle_approve_mint(address minter) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "./IBalancerToken.sol"; interface IBalancerTokenAdmin is IAuthentication { // solhint-disable func-name-mixedcase function INITIAL_RATE() external view returns (uint256); function RATE_REDUCTION_TIME() external view returns (uint256); function RATE_REDUCTION_COEFFICIENT() external view returns (uint256); function RATE_DENOMINATOR() external view returns (uint256); // solhint-enable func-name-mixedcase /** * @notice Returns the address of the Balancer Governance Token */ function getBalancerToken() external view returns (IBalancerToken); /** * @notice Returns the Balancer Vault. */ function getVault() external view returns (IVault); function activate() external; function rate() external view returns (uint256); function startEpochTimeWrite() external returns (uint256); function mint(address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IAuthorizerAdaptor.sol"; import "./IVotingEscrow.sol"; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IGaugeController { function checkpoint_gauge(address gauge) external; function gauge_relative_weight(address gauge, uint256 time) external returns (uint256); function voting_escrow() external view returns (IVotingEscrow); function token() external view returns (IERC20); function add_type(string calldata name, uint256 weight) external; function change_type_weight(int128 typeId, uint256 weight) external; // Gauges are to be added with zero initial weight so the full signature is not required function add_gauge(address gauge, int128 gaugeType) external; function n_gauge_types() external view returns (int128); function gauge_types(address gauge) external view returns (int128); function admin() external view returns (IAuthorizerAdaptor); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface ILiquidityGauge { function integrate_fraction(address user) external view returns (uint256); function user_checkpoint(address user) external returns (bool); function is_killed() external view returns (bool); function killGauge() external; function unkillGauge() external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IBalancerToken is IERC20 { function mint(address to, uint256 amount) external; function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; // solhint-disable-next-line func-name-mixedcase function DEFAULT_ADMIN_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function MINTER_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function SNAPSHOT_ROLE() external view returns (bytes32); function snapshot() external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ILiquidityGauge.sol"; interface ILiquidityGaugeFactory { /** * @notice Returns true if `gauge` was created by this factory. */ function isGaugeFromFactory(address gauge) external view returns (bool); function create(address pool) external returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "../interfaces/IBalancerMinter.sol"; import "../interfaces/IBalancerTokenAdmin.sol"; import "../interfaces/IGaugeController.sol"; import "../interfaces/ILiquidityGauge.sol"; abstract contract StakelessGauge is ILiquidityGauge, ReentrancyGuard { IERC20 internal immutable _balToken; IBalancerTokenAdmin private immutable _tokenAdmin; IBalancerMinter private immutable _minter; IGaugeController private immutable _gaugeController; IAuthorizerAdaptor private immutable _authorizerAdaptor; event Checkpoint(uint256 indexed periodTime, uint256 periodEmissions); // solhint-disable var-name-mixedcase uint256 private immutable _RATE_REDUCTION_TIME; uint256 private immutable _RATE_REDUCTION_COEFFICIENT; uint256 private immutable _RATE_DENOMINATOR; // solhint-enable var-name-mixedcase uint256 private _rate; uint256 private _period; uint256 private _startEpochTime; uint256 private _emissions; bool private _isKilled; constructor(IBalancerMinter minter) { IBalancerTokenAdmin tokenAdmin = IBalancerTokenAdmin(minter.getBalancerTokenAdmin()); IERC20 balToken = tokenAdmin.getBalancerToken(); IGaugeController gaugeController = minter.getGaugeController(); _balToken = balToken; _tokenAdmin = tokenAdmin; _minter = minter; _gaugeController = gaugeController; _authorizerAdaptor = gaugeController.admin(); _RATE_REDUCTION_TIME = tokenAdmin.RATE_REDUCTION_TIME(); _RATE_REDUCTION_COEFFICIENT = tokenAdmin.RATE_REDUCTION_COEFFICIENT(); _RATE_DENOMINATOR = tokenAdmin.RATE_DENOMINATOR(); // Prevent initialisation of implementation contract // Choice of `type(uint256).max` prevents implementation from being checkpointed _period = type(uint256).max; } // solhint-disable-next-line func-name-mixedcase function __StakelessGauge_init() internal { require(_period == 0, "Already initialized"); // Because we calculate the rate locally, this gauge cannot // be used prior to the start of the first emission period uint256 rate = _tokenAdmin.rate(); require(rate != 0, "BalancerTokenAdmin not yet activated"); _rate = rate; _period = _currentPeriod(); _startEpochTime = _tokenAdmin.startEpochTimeWrite(); } function checkpoint() external payable nonReentrant returns (bool) { require(msg.sender == address(_authorizerAdaptor), "SENDER_NOT_ALLOWED"); uint256 lastPeriod = _period; uint256 currentPeriod = _currentPeriod(); if (lastPeriod < currentPeriod) { _gaugeController.checkpoint_gauge(address(this)); uint256 rate = _rate; uint256 newEmissions = 0; lastPeriod += 1; uint256 nextEpochTime = _startEpochTime + _RATE_REDUCTION_TIME; for (uint256 i = lastPeriod; i < lastPeriod + 255; ++i) { if (i > currentPeriod) break; uint256 periodTime = i * 1 weeks; uint256 periodEmission = 0; uint256 gaugeWeight = _gaugeController.gauge_relative_weight(address(this), periodTime); if (nextEpochTime >= periodTime && nextEpochTime < periodTime + 1 weeks) { // If the period crosses an epoch, we calculate a reduction in the rate // using the same formula as used in `BalancerTokenAdmin`. We perform the calculation // locally instead of calling to `BalancerTokenAdmin.rate()` because we are generating // the emissions for the upcoming week, so there is a possibility the new // rate has not yet been applied. // Calculate emission up until the epoch change uint256 durationInCurrentEpoch = nextEpochTime - periodTime; periodEmission = (gaugeWeight * rate * durationInCurrentEpoch) / 10**18; // Action the decrease in rate rate = (rate * _RATE_DENOMINATOR) / _RATE_REDUCTION_COEFFICIENT; // Calculate emission from epoch change to end of period uint256 durationInNewEpoch = 1 weeks - durationInCurrentEpoch; periodEmission += (gaugeWeight * rate * durationInNewEpoch) / 10**18; _rate = rate; _startEpochTime = nextEpochTime; nextEpochTime += _RATE_REDUCTION_TIME; } else { periodEmission = (gaugeWeight * rate * 1 weeks) / 10**18; } emit Checkpoint(periodTime, periodEmission); newEmissions += periodEmission; } _period = currentPeriod; _emissions += newEmissions; if (newEmissions > 0 && !_isKilled) { _minter.mint(address(this)); _postMintAction(newEmissions); } } return true; } function _currentPeriod() internal view returns (uint256) { // solhint-disable-next-line not-rely-on-time return (block.timestamp / 1 weeks) - 1; } function _postMintAction(uint256 mintAmount) internal virtual; // solhint-disable func-name-mixedcase function user_checkpoint(address) external pure override returns (bool) { return true; } function integrate_fraction(address user) external view override returns (uint256) { require(user == address(this), "Gauge can only mint for itself"); return _emissions; } function is_killed() external view override returns (bool) { return _isKilled; } /** * @notice Kills the gauge so it cannot mint BAL */ function killGauge() external override { require(msg.sender == address(_authorizerAdaptor), "SENDER_NOT_ALLOWED"); _isKilled = true; } /** * @notice Unkills the gauge so it can mint BAL again */ function unkillGauge() external override { require(msg.sender == address(_authorizerAdaptor), "SENDER_NOT_ALLOWED"); _isKilled = false; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./ILiquidityGauge.sol"; interface ISingleRecipientGauge is ILiquidityGauge { function initialize(address recipient) external; function getRecipient() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../interfaces/ISingleRecipientGauge.sol"; import "../StakelessGauge.sol"; import "./IGatewayRouter.sol"; import "./IArbitrumFeeProvider.sol"; contract ArbitrumRootGauge is ISingleRecipientGauge, StakelessGauge { address private immutable _gateway; IGatewayRouter private immutable _gatewayRouter; IArbitrumFeeProvider private immutable _factory; address private _recipient; constructor(IBalancerMinter minter, IGatewayRouter gatewayRouter) StakelessGauge(minter) { _gateway = gatewayRouter.getGateway(address(minter.getBalancerToken())); _gatewayRouter = gatewayRouter; _factory = IArbitrumFeeProvider(msg.sender); } function initialize(address recipient) external override { // This will revert in all calls except the first one __StakelessGauge_init(); _recipient = recipient; } function getRecipient() external view override returns (address) { return _recipient; } function _postMintAction(uint256 mintAmount) internal override { // Token needs to be approved on the gateway NOT the gateway router _balToken.approve(_gateway, mintAmount); (uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost) = _factory.getArbitrumFees(); uint256 totalBridgeCost = _getTotalBridgeCost(gasLimit, gasPrice, maxSubmissionCost); require(msg.value == totalBridgeCost, "Incorrect msg.value passed"); // After bridging, the BAL should arrive on Arbitrum within 10 minutes. If it // does not, the L2 transaction may have failed due to an insufficient amount // within `max_submission_cost + (gas_limit * gas_price)` // In this case, the transaction can be manually broadcasted on Arbitrum by calling // `ArbRetryableTicket(0x000000000000000000000000000000000000006e).redeem(redemption-TxID)` // The calldata for this manual transaction is easily obtained by finding the reverted // transaction in the tx history for 0x000000000000000000000000000000000000006e on Arbiscan. // https://developer.offchainlabs.com/docs/l1_l2_messages#retryable-transaction-lifecycle _gatewayRouter.outboundTransfer{ value: totalBridgeCost }( _balToken, _recipient, mintAmount, gasLimit, gasPrice, abi.encode(maxSubmissionCost, "") ); } function getTotalBridgeCost() external view returns (uint256) { (uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost) = _factory.getArbitrumFees(); return _getTotalBridgeCost(gasLimit, gasPrice, maxSubmissionCost); } function _getTotalBridgeCost( uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost ) internal pure returns (uint256) { return gasLimit * gasPrice + maxSubmissionCost; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IGatewayRouter { function outboundTransfer( IERC20 token, address recipient, uint256 amount, uint256 gasLimit, uint256 gasPrice, bytes calldata data ) external payable; function getGateway(address token) external view returns (address gateway); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IArbitrumFeeProvider { function getArbitrumFees() external view returns ( uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Clones.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "../../interfaces/ILiquidityGaugeFactory.sol"; import "./ArbitrumRootGauge.sol"; import "./IArbitrumFeeProvider.sol"; contract ArbitrumRootGaugeFactory is ILiquidityGaugeFactory, IArbitrumFeeProvider, Authentication { IVault private immutable _vault; ArbitrumRootGauge private _gaugeImplementation; mapping(address => bool) private _isGaugeFromFactory; mapping(address => address) private _recipientGauge; uint64 private _gasLimit; uint64 private _gasPrice; uint64 private _maxSubmissionCost; event ArbitrumRootGaugeCreated(address indexed gauge, address indexed recipient); event ArbitrumFeesModified(uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost); constructor( IVault vault, IBalancerMinter minter, IGatewayRouter gatewayRouter, uint64 gasLimit, uint64 gasPrice, uint64 maxSubmissionCost ) Authentication(bytes32(uint256(address(this)))) { _vault = vault; _gaugeImplementation = new ArbitrumRootGauge(minter, gatewayRouter); _gasLimit = gasLimit; _gasPrice = gasPrice; _maxSubmissionCost = maxSubmissionCost; } /** * @dev Returns the address of the Vault. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns the address of the Vault's Authorizer. */ function getAuthorizer() public view returns (IAuthorizer) { return getVault().getAuthorizer(); } /** * @notice Returns the address of the implementation used for gauge deployments. */ function getGaugeImplementation() public view returns (address) { return address(_gaugeImplementation); } /** * @notice Returns true if `gauge` was created by this factory. */ function isGaugeFromFactory(address gauge) external view override returns (bool) { return _isGaugeFromFactory[gauge]; } /** * @notice Returns the gauge which sends funds to `recipient`. */ function getRecipientGauge(address recipient) external view returns (ILiquidityGauge) { return ILiquidityGauge(_recipientGauge[recipient]); } /** * @notice Returns the recipient of `gauge`. */ function getGaugeRecipient(address gauge) external view returns (address) { return ISingleRecipientGauge(gauge).getRecipient(); } /** * @notice Set the fees for the Arbitrum side of the bridging transaction */ function getArbitrumFees() external view override returns ( uint256 gasLimit, uint256 gasPrice, uint256 maxSubmissionCost ) { gasLimit = _gasLimit; gasPrice = _gasPrice; maxSubmissionCost = _maxSubmissionCost; } /** * @notice Deploys a new gauge which bridges all of its BAL allowance to a single recipient on Polygon. * @dev Care must be taken to ensure that gauges deployed from this factory are * suitable before they are added to the GaugeController. * @param recipient The address to receive BAL minted from the gauge * @return The address of the deployed gauge */ function create(address recipient) external override returns (address) { require(_recipientGauge[recipient] == address(0), "Gauge already exists"); address gauge = Clones.clone(address(_gaugeImplementation)); ArbitrumRootGauge(gauge).initialize(recipient); _isGaugeFromFactory[gauge] = true; _recipientGauge[recipient] = gauge; emit ArbitrumRootGaugeCreated(gauge, recipient); return gauge; } /** * @notice Set the fees for the Arbitrum side of the bridging transaction */ function setArbitrumFees( uint64 gasLimit, uint64 gasPrice, uint64 maxSubmissionCost ) external authenticate { _gasLimit = gasLimit; _gasPrice = gasPrice; _maxSubmissionCost = maxSubmissionCost; emit ArbitrumFeesModified(gasLimit, gasPrice, maxSubmissionCost); } // Authorization function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return getAuthorizer().canPerform(actionId, account, address(this)); } }
Returns the address of the Balancer Governance Token/ Returns the Balancer Vault./ SPDX-License-Identifier: GPL-3.0-or-later This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http:www.gnu.org/licenses/>. For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case naming convention. solhint-disable func-name-mixedcase Gauges are to be added with zero initial weight so the full signature is not required
interface IGaugeController { function checkpoint_gauge(address gauge) external; function gauge_relative_weight(address gauge, uint256 time) external returns (uint256); function voting_escrow() external view returns (IVotingEscrow); function token() external view returns (IERC20); function add_type(string calldata name, uint256 weight) external; function change_type_weight(int128 typeId, uint256 weight) external; function add_gauge(address gauge, int128 gaugeType) external; function n_gauge_types() external view returns (int128); function gauge_types(address gauge) external view returns (int128); function admin() external view returns (IAuthorizerAdaptor); }
170,363
./partial_match/1/0x9490CCf93Cd750dc47f72402A163022cfB94CFC9/sources/contracts/vaults/TreasuryVault/RibbonTreasuryVaultLite.sol
Returns the asset balance held on the vault for the account account is the address to lookup balance for return the amount of `asset` custodied by the vault for the user/
function accountVaultBalance(address account) public view returns (uint256) { uint256 _decimals = vaultParams.decimals; uint256 assetPerShare = ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, _decimals ); return ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals); }
3,540,712
pragma solidity ^0.4.24; import "../Roles.sol"; import "./OwnerRole.sol"; /** * @title ListerAdminRole * * @dev Role for providing access control to functions that administer individual lister roles. * This contract inherits from OwnerRole so that owners can administer this role. * The ListerRole contract should inherit from this contract. */ contract ListerAdminRole is OwnerRole { using Roles for Roles.Role; /** Event emitted whenever an account is given access to the listerAdmin role. */ event ListerAdminAdded(address indexed account); /** Event emitted whenever an account has access removed from the listerAdmin role. */ event ListerAdminRemoved(address indexed account); /** Mapping of account addresses with access to the listerAdmin role. */ Roles.Role private _listerAdmins; /** * @dev Modifier to make a function callable only when the caller has access to the listerAdmin role. */ modifier onlyListerAdmin() { require(_isListerAdmin(msg.sender)); _; } /** * @dev Assert if the given `account` has been provided access to the listerAdmin role. * * @param account The account address being queried * @return True if the given `account` has access to the listerAdmin role, otherwise false */ function isListerAdmin(address account) external view returns (bool) { return _isListerAdmin(account); } /** * @return The number of account addresses with access to the listerAdmin role. */ function numberOfListerAdmins() external view returns (uint256) { return _listerAdmins.size(); } /** * @return An array containing all account addresses with access to the listerAdmin role. */ function listerAdmins() external view returns (address[]) { return _listerAdmins.toArray(); } /** * @dev Provide the given `account` with access to the listerAdmin role. * Callable by an account with the owner role. * * @param account The account address being given access to the listerAdmin role */ function addListerAdmin(address account) external onlyOwner { _addListerAdmin(account); } /** * @dev Remove access to the listerAdmin role for the given `account`. * Callable by an account with the owner role. * * @param account The account address having access removed from the listerAdmin role */ function removeListerAdmin(address account) external onlyOwner { _removeListerAdmin(account); } /** * @dev Remove access to the listerAdmin role for the `previousAccount` and give access to the `newAccount`. * Callable by an account with the owner role. * * @param previousAccount The account address having access removed from the listerAdmin role * @param newAccount The account address being given access to the listerAdmin role */ function replaceListerAdmin(address previousAccount, address newAccount) external onlyOwner { _replaceListerAdmin(previousAccount, newAccount); } /** * @dev Replace all accounts that have access to the listerAdmin role with the given array of `accounts`. * Callable by an account with the owner role. * * @param accounts An array of account addresses to replace all existing listerAdmins with */ function replaceAllListerAdmins(address[] accounts) external onlyOwner { _replaceAllListerAdmins(accounts); } /** * @dev Internal function that asserts the given `account` is in `_listerAdmins`. * * @param account The account address being queried * @return True if the given `account` is in `_listerAdmins`, otherwise false */ function _isListerAdmin(address account) internal view returns (bool) { return _listerAdmins.has(account); } /** * @dev Internal function that adds the given `account` to `_listerAdmins`. * Emits a ListerAdminAdded event. * * @param account The account address being given access to the listerAdmin role */ function _addListerAdmin(address account) internal { _listerAdmins.add(account); emit ListerAdminAdded(account); } /** * @dev Internal function that removes the given `account` from `_listerAdmins`. * Emits a ListAdminRemoved event. * * @param account The account address having access removed from the listerAdmin role */ function _removeListerAdmin(address account) internal { _listerAdmins.remove(account); emit ListerAdminRemoved(account); } /** * @dev Internal function that replaces the `previousAccount` in `_listerAdmins` with the `newAccount`. * Emits a ListerAdminRemoved event. * Emits a ListerAdminAdded event. * * @param previousAccount The account address having access removed from the listerAdmin role * @param newAccount The account address being given access to the listerAdmin role */ function _replaceListerAdmin(address previousAccount, address newAccount) internal { _listerAdmins.replace(previousAccount, newAccount); emit ListerAdminRemoved(previousAccount); emit ListerAdminAdded(newAccount); } /** * @dev Internal function that replaces all accounts in `_listerAdmins` with the given array of `accounts`. * Emits a ListerAdminAdded event for each account in the `accounts` array that doesn't already have access. * Emits a ListerAdminRemoved event for each account that has access removed from the tester role. * * @param accounts An array of account addresses to replace all existing listerAdmins with */ function _replaceAllListerAdmins(address[] accounts) internal { // Emit a ListerAdminAdded event for each account that doesn't already have access to the role for (uint256 i = 0; i < accounts.length; i++) { if (!_listerAdmins.has(accounts[i])) { emit ListerAdminAdded(accounts[i]); } } // Replace all existing accounts with the given array of addresses address[] memory previousAccounts = _listerAdmins.replaceAll(accounts); // Emit a ListerAdminRemoved event for each previous account that no longer has access to the role for (uint256 j = 0; j < previousAccounts.length; j++) { if (!_listerAdmins.has(previousAccounts[j])) { emit ListerAdminRemoved(previousAccounts[j]); } } } }
Internal function that asserts the given `account` is in `_listerAdmins`. account The account address being queried return True if the given `account` is in `_listerAdmins`, otherwise false/
function _isListerAdmin(address account) internal view returns (bool) { return _listerAdmins.has(account); }
12,634,055
/** *Submitted for verification at Etherscan.io on 2021-03-17 */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface IGoaldDAO { /** Returns the number of goalds deployed from this DAO. */ function getGoaldCount() external view returns (uint256); /** Returns the current address that fees will be sent to. */ function getProxyAddress() external view returns (address); /** Called if the DAO manager is no longer a holder after burning the initialization tokens. */ function initializeDecreasesHolders() external; /** Called if the DAO manager is now a holder after claiming the initialization tokens. */ function issuanceIncreasesHolders() external; /** Makes this DAO ready for deployments (regardless of whether or not there are authorized ones). */ function makeReady(uint256 governanceStage, uint256 idOffset) external; /** Update the reward balances prior to the transfer completing. */ function preTransfer(address sender, address recipient) external; /** Updates holder counts after doing a transfer. */ function postTransfer(address sender, uint256 senderBefore, uint256 senderAfter, uint256 recipientBefore, uint256 recipientAfter) external; /** Called when the DAO has been initialized. */ function updateGovernanceStage() external; } contract GoaldToken is ERC20 { address public _manager = msg.sender; /** @dev The DAO versions. DAOs only become invalid if they have a security vulnerability that compromises this contract. */ address[] private _daoAddresses; mapping(address => uint256) private _isValidDAO; uint256 private constant UNTRACKED_DAO = 0; uint256 private constant VALID_DAO = 1; uint256 private constant INVALID_DAO = 2; /** @dev The number of decimals is small to allow for rewards of tokens with substantially different exchange rates. */ uint8 private constant DECIMALS = 2; /** * @dev The minimum amount of tokens necessary to be eligible for a reward. This is "one token", considering decimal places. We * are choosing two decimal places because we are initially targeting WBTC, which has 8. This way we can do a minimum reward ratio * of 1 / 1,000,000 of a WBTC, relative to our token. So at $25,000 (2020 value), the minimum reward would be $250 (assuming we * have issued all 10,000 tokens). */ uint256 private constant REWARD_THRESHOLD = 10**uint256(DECIMALS); /** * @dev The maximum supply is 210,000 tokens. 110,000 tokens are burned on initiating the DAO; 10,000 are given to Bittrees for * initial management. The remainder are minted on a decreasing schedule based on the total number of deployed Goalds. */ uint256 private constant MAX_SUPPLY = 210000 * REWARD_THRESHOLD; /** @dev The base token URI for the Goald metadata. */ string private _baseTokenURI; /** @dev The total number of deployed Goalds across all DAOs. */ uint256 private _goaldCount; /** * @dev The stage of the governance token. Tokens can be issued based on deployments regardless of what stage we are in. * 0: Created, with no governance protocol initiated. The initial governance issuance can be claimed. * 1: Initial governance issuance has been claimed. * 2: The governance protocal has been initiated. * 3: All governance tokens have been issued. */ uint256 private constant STAGE_INITIAL = 0; uint256 private constant STAGE_ISSUANCE_CLAIMED = 1; uint256 private constant STAGE_DAO_INITIATED = 2; uint256 private constant STAGE_ALL_GOVERNANCE_ISSUED = 3; uint256 private _governanceStage; // Reentrancy reversions are the only calls to revert (in this contract) that do not have reasons. We add a third state, 'frozen' // to allow for locking non-admin functions. The contract may be permanently frozen if it has been upgraded. uint256 private constant RE_NOT_ENTERED = 1; uint256 private constant RE_ENTERED = 2; uint256 private constant RE_FROZEN = 3; uint256 private _status; // Separate reentrancy status to further guard against arbitrary calls against a DAO contract via `unsafeCallDAO()`. uint256 private _daoStatus; // Override decimal places to 2. See `GoaldProxy.REWARD_THRESHOLD`. constructor() ERC20("Goald", "GOALD") public { _setupDecimals(DECIMALS); _status = RE_FROZEN; _daoStatus = RE_NOT_ENTERED; } /// Events /// event DAOStatusChanged(address daoAddress, uint256 status); event DAOUpgraded(address daoAddress); event GoaldDeployed(address goaldAddress); event ManagerChanged(address newManager); /// Admin /// /** Freezes the contract. Only admin functions can be called. */ function freeze() external { // Reentrancy guard. require(_status == RE_NOT_ENTERED); require(msg.sender == _manager, "Not manager"); _status = RE_FROZEN; } /** Sets the status of a given DAO. */ function setDAOStatus(address daoAddress, uint256 index, uint256 status) external { // Reentrancy guard. require(_status == RE_NOT_ENTERED || _status == RE_FROZEN); require(msg.sender == _manager, "Not manager"); // Validate the index as well. require(_daoAddresses[index] == daoAddress, "Non-matching DAO index"); // Validate the status. require(status == VALID_DAO || status == INVALID_DAO, "Invalid status"); uint256 currentStatus = _isValidDAO[daoAddress]; require(currentStatus != status && (currentStatus == VALID_DAO || currentStatus == INVALID_DAO), "Invalid current status"); // Update the status. _isValidDAO[daoAddress] = status; // Hello world! emit DAOStatusChanged(daoAddress, status); } function setManager(address newManager) external { // Reentrancy guard. require(_status == RE_NOT_ENTERED || _status == RE_FROZEN); require(msg.sender == _manager, "Not manager"); require(newManager != address(0), "Can't be zero address"); require(newManager != address(this), "Can't be this address"); // If the issuance has been claimed but the DAO has not been initialized, then the new manager must be able to initialize it. require((_governanceStage != STAGE_ISSUANCE_CLAIMED) || (balanceOf(newManager) > 110000 * REWARD_THRESHOLD), "New manager can't init DAO"); _manager = newManager; // Hello world! emit ManagerChanged(newManager); } /** Unfreezes the contract. Non-admin functions can again be called. */ function unfreeze() external { // Reentrancy guard. require(_status == RE_FROZEN); require(msg.sender == _manager, "Not manager"); _status = RE_NOT_ENTERED; } /** Upgrades to the new DAO version. Can only be done when frozen. */ function upgradeDAO(address daoAddress) external { // Reentrancy guard. require(_status == RE_FROZEN); _status = RE_ENTERED; // It must be a contract. uint256 codeSize; assembly { codeSize := extcodesize(daoAddress) } require(codeSize > 0, "Not a contract"); // Make sure it hasn't been tracked yet. require(_isValidDAO[daoAddress] == UNTRACKED_DAO, "DAO already tracked"); // Upgrade the DAO. _daoAddresses.push(daoAddress); _isValidDAO[daoAddress] = VALID_DAO; // Enable the DAO. IGoaldDAO(daoAddress).makeReady(_governanceStage, _goaldCount); // Hello world! emit DAOUpgraded(daoAddress); // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _status = RE_FROZEN; } /// Goalds /// /** Gets the base url for Goald metadata. */ function getBaseTokenURI() external view returns (string memory) { return _baseTokenURI; } /** Gets the total number of deployed Goalds. */ function getGoaldCount() external view returns (uint256) { return _goaldCount; } /** Returns the address of the DAO which deployed the Goald. */ function getGoaldDAO(uint256 id) external view returns (address) { require(id < _goaldCount, "ID too large"); uint256 addressesCount = _daoAddresses.length; uint256 index; uint256 goaldCount; address goaldAddress; for (; index < addressesCount; index ++) { goaldAddress = _daoAddresses[index]; goaldCount += IGoaldDAO(goaldAddress).getGoaldCount(); if (id <= goaldCount) { return goaldAddress; } } revert("Unknown DAO"); } /** * Called when a deployer deploys a new Goald (via the DAO contract). Currently we use this to distribute the governance token * according to the following schedule. An additional 120,000 tokens will be claimable by the deployer of this proxy. This will * create a total supply of 210,000 tokens. Once the governance protocal is set up, 110,000 tokens will be burned to initiate that * mechanism. That will leave 10% ownership for the deployer of the contract, with the remaining 90% disbused on Goald creations. * No rewards can be paid out before the governance protocal has been initiated. * * # Goalds # Tokens * 0 - 9 1000 * 10 - 19 900 * 20 - 29 800 * 30 - 39 700 * 40 - 49 600 * 50 - 59 500 * 60 - 69 400 * 70 - 79 300 * 80 - 89 200 * 90 - 99 100 * < 3600 10 */ function goaldDeployed(address recipient, address goaldAddress) external returns (uint256) { // Reentrancy guard. require(_daoStatus == RE_NOT_ENTERED); // Validate the caller. require(msg.sender == _daoAddresses[_daoAddresses.length - 1], "Caller not latest DAO"); require(_isValidDAO[msg.sender] == VALID_DAO, "Caller not valid DAO"); // Hello world! emit GoaldDeployed(goaldAddress); uint256 goaldCount = _goaldCount++; if (_governanceStage == STAGE_ALL_GOVERNANCE_ISSUED) { return 0; } // Calculate the amount of tokens issued based on the schedule. uint256 amount; if (goaldCount < 10) { amount = 1000; } else if (goaldCount < 20) { amount = 900; } else if (goaldCount < 30) { amount = 800; } else if (goaldCount < 40) { amount = 700; } else if (goaldCount < 50) { amount = 600; } else if (goaldCount < 60) { amount = 500; } else if (goaldCount < 70) { amount = 400; } else if (goaldCount < 80) { amount = 300; } else if (goaldCount < 90) { amount = 200; } else if (goaldCount < 100) { amount = 100; } else if (goaldCount < 3600) { amount = 10; } // We have issued all tokens, so move to the last stage of governance. This will short circuit this function on future calls. // This will result in unnecessary gas if the DAO is never initiated and all 3600 token-earning goalds are created. But the // DAO should be initiated long before that. else if (_governanceStage == STAGE_DAO_INITIATED) { _governanceStage = STAGE_ALL_GOVERNANCE_ISSUED; } if (amount == 0) { return 0; } // Validate the recipient. require(_isValidDAO[recipient] == UNTRACKED_DAO, "Can't be DAO"); require(recipient != address(0), "Can't be zero address"); require(recipient != address(this), "Can't be Goald token"); // Validate the amount. uint256 totalSupply = totalSupply(); require(amount + totalSupply > totalSupply, "Overflow error"); require(amount + totalSupply < MAX_SUPPLY, "Exceeds supply"); // Mint the tokens. _mint(recipient, amount * REWARD_THRESHOLD); return amount; } /** Sets the base url for Goald metadata. */ function setBaseTokenURI(string calldata baseTokenURI) external { // Reentrancy guard. require(_status == RE_NOT_ENTERED || _status == RE_FROZEN); require(msg.sender == _manager, "Not manager"); _baseTokenURI = baseTokenURI; } /// Governance /// /** Claims the initial issuance of the governance token to enable bootstrapping the DAO. */ function claimIssuance() external { // Reentrancy guard. require(_status == RE_NOT_ENTERED); require(msg.sender == _manager, "Not manager"); require(_governanceStage == STAGE_INITIAL, "Already claimed"); // We are creating a new holder. if (balanceOf(_manager) < REWARD_THRESHOLD) { uint256 index; uint256 count = _daoAddresses.length; for (; index < count; index ++) { IGoaldDAO(_daoAddresses[index]).issuanceIncreasesHolders(); } } // Mint the tokens. _mint(_manager, 120000 * REWARD_THRESHOLD); // Update the governance stage. _governanceStage = STAGE_ISSUANCE_CLAIMED; } /** Returns the address of the DAO at the given index. */ function getDAOAddressAt(uint256 index) external view returns (address) { return _daoAddresses[index]; } /** Returns the number of historical DAO addresses. */ function getDAOCount() external view returns (uint256) { return _daoAddresses.length; } /** Returns the status of the DAO with the given address. */ function getDAOStatus(address daoAddress) external view returns (uint256) { return _isValidDAO[daoAddress]; } /** Gets the latest dao address, so long as it's valid. */ function getLatestDAO() external view returns (address) { address daoAddress = _daoAddresses[_daoAddresses.length - 1]; require(_isValidDAO[daoAddress] == VALID_DAO, "Latest DAO invalid"); return daoAddress; } /** Returns the current stage of the DAO's governance. */ function getGovernanceStage() external view returns (uint256) { return _governanceStage; } /** Releases management to the DAO. */ function initializeDAO() external { // Reentrancy guard. require(_status == RE_NOT_ENTERED); _status = RE_ENTERED; require(msg.sender == _manager, "Not manager"); require(_governanceStage == STAGE_ISSUANCE_CLAIMED, "Issuance unclaimed"); // Burn the tokens. uint256 startingBalance = balanceOf(_manager); require(startingBalance >= 110000 * REWARD_THRESHOLD, "Not enough tokens"); _burn(_manager, 110000 * REWARD_THRESHOLD); // Update the stage. _governanceStage = STAGE_DAO_INITIATED; uint256 count = _daoAddresses.length; // If the manager no longer is a holder we need to tell the latest DAO. if (count > 0 && startingBalance - (110000 * REWARD_THRESHOLD) < REWARD_THRESHOLD) { IGoaldDAO(_daoAddresses[count - 1]).initializeDecreasesHolders(); } // Tell the DAOs so they can create rewards. uint256 index; for (; index < count; index++) { IGoaldDAO(_daoAddresses[index]).updateGovernanceStage(); } // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _status = RE_NOT_ENTERED; } /** * Executes a function on the DAO. Only the manager can call this function. This guards against reentrancy so any called function * cannot execute a call against this contract. This code is duplicated with `unsafeCallDAO()` in place of having an internal * `_callDAO()` since reentrancy guarding is not guaranteed. * * @param daoAddress Which DAO is being called. * @param encodedData The non-packed, abi encoded calldata that will be included with the function call. */ function safeCallDAO(address daoAddress, bytes calldata encodedData) external returns (bytes memory) { // Reentrancy guard. We check against both normal reentrancy and DAO call reentrancy. require(_status == RE_NOT_ENTERED); require(_daoStatus == RE_NOT_ENTERED); _status = RE_ENTERED; _daoStatus = RE_ENTERED; require(msg.sender == _manager, "Not manager"); // `_isValidDAO` since DAOs can be disabled. Use `unsafeCallDAO()` if a call must be made to an invalid DAO. require(_isValidDAO[daoAddress] == VALID_DAO, "Not a valid DAO"); // Call the function, bubbling on errors. (bool success, bytes memory returnData) = daoAddress.call(encodedData); // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _status = RE_NOT_ENTERED; _daoStatus = RE_NOT_ENTERED; // See @OpenZeppelin.Address._functionCallWithValue() 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(); } } } /** * Executes a function on the DAO. Only the manager can call this function. This DOES NOT guard against reentrancy. Do not use * this unless reentrancy is needed or the call is made to an invlaid contract. Otherwise use `safeCallDAO()`. This code is * duplicated in place of having an internal `_callDAO()` since reentrancy guarding is not guaranteed. * * @param daoAddress Which DAO is being called. * @param encodedData The non-packed, abi encoded calldata that will be included with the function call. */ function unsafeCallDAO(address daoAddress, bytes calldata encodedData) external returns (bytes memory) { // Reentrancy guard. We check against both normal reentrancy and DAO call reentrancy. require(_daoStatus == RE_NOT_ENTERED); _daoStatus = RE_ENTERED; require(msg.sender == _manager, "Not manager"); // `_isValidDAO` since DAOs can be disabled. require(_isValidDAO[daoAddress] != UNTRACKED_DAO, "DAO not tracked"); // Call the function, bubbling on errors. (bool success, bytes memory returnData) = daoAddress.call(encodedData); // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _daoStatus = RE_NOT_ENTERED; // See @OpenZeppelin.Address._functionCallWithValue() 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(); } } } /// ERC20 Overrides /// /** This is overridden so we can update the reward balancees prior to the transfer completing. */ function transfer(address recipient, uint256 amount) public override returns (bool) { // Reentrancy guard. require(_status == RE_NOT_ENTERED); _status = RE_ENTERED; // Preserve the original balances so we know if we need to change `_rewardHolders`. We need to call `pre()` and `post()` on // every DAO version to make sure that the reward balances are updated correctly. uint256 senderBefore = balanceOf(msg.sender); uint256 recipientBefore = balanceOf(recipient); // Update reward balances. uint256 count = _daoAddresses.length; uint256 index; for (; index < count; index ++) { IGoaldDAO(_daoAddresses[index]).preTransfer(msg.sender, recipient); } // Transfer the tokens. super.transfer(recipient, amount); // Update holder counts. index = 0; for (; index < count; index ++) { IGoaldDAO(_daoAddresses[index]).postTransfer(msg.sender, senderBefore, balanceOf(msg.sender), recipientBefore, balanceOf(recipient)); } // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _status = RE_NOT_ENTERED; return true; } /** This is overridden so we can update the reward balancees prior to the transfer completing. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { // Reentrancy guard. require(_status == RE_NOT_ENTERED); _status = RE_ENTERED; // Preserve the original balances so we know if we need to change `_rewardHolders`. We need to call `pre()` and `post()` on // every DAO version to make sure that the reward balances are updated correctly. uint256 senderBefore = balanceOf(sender); uint256 recipientBefore = balanceOf(recipient); // Update reward balances. uint256 count = _daoAddresses.length; uint256 index; for (; index < count; index ++) { IGoaldDAO(_daoAddresses[index]).preTransfer(sender, recipient); } // Transfer the tokens. super.transferFrom(sender, recipient, amount); // Update holder counts. index = 0; for (; index < count; index ++) { IGoaldDAO(_daoAddresses[index]).postTransfer(sender, senderBefore, balanceOf(sender), recipientBefore, balanceOf(recipient)); } // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200). _status = RE_NOT_ENTERED; return true; } }
Releases management to the DAO. / Reentrancy guard. Burn the tokens. Update the stage. If the manager no longer is a holder we need to tell the latest DAO.
function initializeDAO() external { require(_status == RE_NOT_ENTERED); _status = RE_ENTERED; require(msg.sender == _manager, "Not manager"); require(_governanceStage == STAGE_ISSUANCE_CLAIMED, "Issuance unclaimed"); uint256 startingBalance = balanceOf(_manager); require(startingBalance >= 110000 * REWARD_THRESHOLD, "Not enough tokens"); _burn(_manager, 110000 * REWARD_THRESHOLD); _governanceStage = STAGE_DAO_INITIATED; uint256 count = _daoAddresses.length; if (count > 0 && startingBalance - (110000 * REWARD_THRESHOLD) < REWARD_THRESHOLD) { IGoaldDAO(_daoAddresses[count - 1]).initializeDecreasesHolders(); } for (; index < count; index++) { IGoaldDAO(_daoAddresses[index]).updateGovernanceStage(); } }
2,229,996
./full_match/44787/0x8D38DA4eb0315582013D42a909db8076a79de277/sources/contracts/StarFarm.sol
Deposit LP tokens to MasterChef for STAR allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid,1); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender()); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100)); uint256 accStarPerShare = pool.accStarPerShare; uint256 lpSupply = pool.lpSupply.add(pool.extraAmount); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = starReward.mul(1e12).div(lpSupply); } if(_amountGain >0){ uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12); user.reward = user.reward.add(_amountpendingStar); } uint256 pending = user.reward; if(pending > 0) { starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100)); starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100)); pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100)); starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100)); pending = pending.sub(pending.mul(rewardRatio).div(100)); pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100)); starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100)); user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100)); starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100)); user.reward = 0; pool.accStarPerShare = accStarPerShare; } if (_amount > 0) { pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount); user.amount = user.amount.add(_amount); user.lastDeposit = block.timestamp; uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100); pool.extraAmount = pool.extraAmount.add(_extraAmount); pool.lpSupply = pool.lpSupply.add(_amount); if(isPoolUser[_pid][_msgSender()] == false){ userIndex[_pid][pool.size] = _msgSender(); pool.size += 1; isPoolUser[_pid][_msgSender()] = true; } } emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]); } event WithdrawTL(uint256 reward,uint256 pendingStar);
13,246,233
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interface/icustom.sol"; import "./Third.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; // MasterChef is the master of OFI. He can make OFI and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once OFI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract LockPool is Third { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Router02 router; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 lockTime; uint256 lastTime; // // We do some fancy math here. Basically, any point in time, the amount of OFIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accOFIPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accOFIPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. OFIs to distribute per block. uint256 lastRewardBlock; // Last block number that OFIs distribution occurs. uint256 accOFIPerShare; // Accumulated OFIs per share, times 1e12. See below. uint256 minAMount; uint256 maxAMount; uint256 deposit_fee; // 1/10000 uint256 withdraw_fee; // 1/10000 ICustom lend; // 1/10000 IERC20 rewardToken; // 1/10000 uint256 lpSupply; uint256 allWithdrawReward; } // The OFI TOKEN! Common public OFI; // Fee address. address public feeaddr; // Dev address. address public devaddr; // Operation address. address public operationaddr; // Fund address. address public fundaddr; // OFI tokens created per block. uint256 public OFIPerBlock; // Bonus muliplier for early OFI makers. uint256 public LockMulti = 1; uint256 public LockTime = 3 days; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDev(address indexed devAddress); event SetOFIPerBlock(uint256 _OFIPerBlock); event SetMigrator(address _migrator); event SetOperation(address _operation); event SetFund(address _fund); event SetInstitution(address _institution); event SetFee(address _feeaddr); event SetPool(uint256 pid ,address lpaddr,uint256 point,uint256 min,uint256 max); constructor( Common _OFI, address _feeaddr, address _devaddr, address _operationaddr, address _fundaddr, uint256 _OFIPerBlock, uint256 _LockMulti, IUniswapV2Router02 _router ) public { OFI = _OFI; devaddr = _devaddr; feeaddr = _feeaddr; OFIPerBlock = _OFIPerBlock; operationaddr = _operationaddr; fundaddr = _fundaddr; router = _router; LockMulti = _LockMulti; } function poolLength() external view returns (uint256) { return poolInfo.length; } function setCbay(Common _cbay) public { OFI = _cbay; } function setOFIPerBlock(uint256 _OFIPerBlock) public onlyOwner { OFIPerBlock = _OFIPerBlock; emit SetOFIPerBlock(_OFIPerBlock); } function setLockTime(uint256 _lockTime) public onlyOwner { LockTime = _lockTime; } function setLockMulti(uint256 _lockMulti) public onlyOwner { LockMulti = _lockMulti; } function GetPoolInfo(uint256 id) external view returns (PoolInfo memory) { return poolInfo[id]; } function GetUserInfo(uint256 id,address addr) external view returns (UserInfo memory) { return userInfo[id][addr]; } function balanceOfUnderlying(PoolInfo memory pool) public view returns (uint256){ return pool.lend.updatedSupplyOf(address(this)); } // View function to see pending RITs on frontend. function rewardLp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage uRIT = userInfo[_pid][_user]; uint256 thirdAllBalance = balanceOfUnderlying(pool); if(thirdAllBalance <= 0){ return 0; } uint256 ba = uRIT.amount.mul(thirdAllBalance).div(pool.lpSupply); if(ba > uRIT.amount){ return ba.sub(uRIT.amount); } return 0; } // View function to see pending RITs on frontend. function allRewardLp(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 thirdAllBalance = balanceOfUnderlying(pool); if(thirdAllBalance <= pool.lpSupply){ return 0; } return pool.allWithdrawReward.add(thirdAllBalance.sub(pool.lpSupply)); } // 设置锁仓时间 30天一周期 function SetUserLock(uint256 id) public { UserInfo storage user = userInfo[id][msg.sender]; require(user.amount>0,"need deposit first"); require(user.lockTime<=0,"has lock already"); user.lockTime = user.lockTime.add(now).add(LockTime); } // 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, IERC20 _lpToken, bool _withUpdate,uint256 _min,uint256 _max,uint256 _deposit_fee,uint256 _withdraw_fee,ICustom _lend,IERC20 _rewardToken) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accOFIPerShare: 0, minAMount:_min, maxAMount:_max, deposit_fee : _deposit_fee, withdraw_fee : _withdraw_fee, lend: _lend, rewardToken: _rewardToken, lpSupply: 0, allWithdrawReward: 0 })); approve(poolInfo[poolInfo.length-1]); emit SetPool(poolInfo.length-1 , address(_lpToken), _allocPoint, _min, _max); } function approve(PoolInfo memory pool) private { if(address(pool.lend) != address(0) ){ if(address(pool.rewardToken) != address(0)){ pool.rewardToken.approve(address(router),uint256(-1)); pool.rewardToken.approve(address(pool.lend),uint256(-1)); } pool.lpToken.approve(address(pool.lend), uint256(-1)); } } // Update the given pool's OFI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate,uint256 _min,uint256 _max,uint256 _deposit_fee,uint256 _withdraw_fee,ICustom _lend,IERC20 _rewardToken) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].minAMount = _min; poolInfo[_pid].maxAMount = _max; poolInfo[_pid].deposit_fee = _deposit_fee; poolInfo[_pid].withdraw_fee = _withdraw_fee; poolInfo[_pid].lend = _lend; poolInfo[_pid].rewardToken = _rewardToken; approve(poolInfo[_pid]); emit SetPool(_pid , address(poolInfo[_pid].lpToken), _allocPoint, _min, _max); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } function getApy(uint256 _pid) public view returns (uint256) { uint256 yearCount = OFIPerBlock.mul(86400).div(3).mul(365); return yearCount.div(getTvl(_pid)); } function getTvl(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; (uint256 t1,uint256 t2,) = IUniswapV2Pair(address(pool.lpToken)).getReserves(); address token0 = IUniswapV2Pair(address(pool.lpToken)).token0(); uint256 allCount = 0; if(token0==address(OFI)){ // 总成本 allCount = t1.mul(2); } else{ allCount = t2.mul(2); } uint256 lpSupply = pool.lpSupply; uint256 totalSupply = pool.lpToken.totalSupply(); return allCount.mul(lpSupply).div(totalSupply); } // View function to see pending OFIs on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOFIPerShare = pool.accOFIPerShare; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 OFIReward = multiplier.mul(OFIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOFIPerShare = accOFIPerShare.add(OFIReward.mul(1e12).div(lpSupply)); } uint256 pending = user.amount.mul(accOFIPerShare).div(1e12).sub(user.rewardDebt); if(user.lockTime > now){ return pending; } return pending.div(LockMulti); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid,0,true); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid,uint256 _amount,bool isAdd) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } pool.lpSupply = isAdd ? pool.lpSupply.add(_amount) : pool.lpSupply.sub(_amount) ; if (pool.lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 OFIReward = multiplier.mul(OFIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); OFI.mint(address(this), OFIReward); // Liquidity reward pool.accOFIPerShare = pool.accOFIPerShare.add(OFIReward.mul(1e12).div(pool.lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for OFI allocation. function deposit(uint256 _pid, uint256 _amount) public { require(pause==0,'can not execute'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid,0,true); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accOFIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(user.lockTime <= 0){ pending = pending.div(LockMulti); } safeOFITransfer(msg.sender, pending); } } if(_amount > 0) { if(pool.deposit_fee > 0){ uint256 feeR = _amount.mul(pool.deposit_fee).div(10000); pool.lpToken.safeTransferFrom(address(msg.sender), devaddr, feeR); _amount = _amount.sub(feeR); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.lastTime = block.timestamp; if (pool.minAMount > 0 && user.amount < pool.minAMount){ revert("amount is too low"); } if (pool.maxAMount > 0 && user.amount > pool.maxAMount){ revert("amount is too high"); } if(address(pool.lend) != address(0)){ depositLend( pool, _amount); } pool.lpSupply = pool.lpSupply.add(_amount); } user.rewardDebt = user.amount.mul(pool.accOFIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function depositLend(PoolInfo memory pool,uint256 _amount) private { if(_amount<=0){ return; } pool.lend.mint(_amount); } function withdrawLend(uint256 _pid,uint256 _amount) private returns(uint256){ PoolInfo storage pool = poolInfo[_pid]; require(pool.lpSupply>0,"none pool.lpSupply"); uint256 allAmount = pool.lend.updatedSupplyOf(address(this)); uint256 shouldAmount = _amount.mul(allAmount).div(pool.lpSupply); if(shouldAmount>_amount){ pool.allWithdrawReward = pool.allWithdrawReward.add(shouldAmount.sub(_amount)); } // pool.lend.redeem(shouldAmount); return shouldAmount; } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid,0,false); uint256 pending = user.amount.mul(pool.accOFIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(user.lockTime <= 0){ pending = pending.div(LockMulti); } safeOFITransfer(msg.sender, pending); } if(_amount > 0) { require(user.lockTime<=now,"mining in lock,can not withdraw"); uint256 shouldAmount = _amount; if(address(pool.lend) != address(0)){ shouldAmount = withdrawLend(_pid,_amount); } user.amount = user.amount.sub(_amount); uint256 originAmount = _amount; if(pool.withdraw_fee>0 && ((block.timestamp-user.lastTime) < LockTime)){ uint256 fee = _amount.mul(pool.withdraw_fee).div(10000); _amount = _amount.sub(fee); pool.lpToken.safeTransfer(devaddr, fee); shouldAmount = _amount; } safeLpTransfer(pool,msg.sender,shouldAmount); pool.lpSupply = pool.lpSupply.sub(originAmount); } user.rewardDebt = user.amount.mul(pool.accOFIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function safeLpTransfer(PoolInfo memory pool,address _to, uint256 _amount) internal { uint256 ba = pool.lpToken.balanceOf(address(this)); if (_amount > ba) { pool.lpToken.transfer(_to, ba); } else { pool.lpToken.transfer(_to, _amount); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe OFI transfer function, just in case if rounding error causes pool to not have enough OFIs. function safeOFITransfer(address _to, uint256 _amount) internal { uint256 ba = OFI.balanceOf(address(this)); if (_amount > ba) { OFI.transfer(_to, ba); } else { OFI.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); require(_devaddr != address(0), "_devaddr is address(0)"); devaddr = _devaddr; emit SetDev(_devaddr); } // Update operation address by the previous operation. function operation(address _opaddr) public { require(msg.sender == operationaddr, "operation: wut?"); require(_opaddr != address(0), "_opaddr is address(0)"); operationaddr = _opaddr; emit SetOperation(_opaddr); } // Update fund address by the previous fund. function fund(address _fundaddr) public { require(msg.sender == fundaddr, "fund: wut?"); require(_fundaddr != address(0), "_fundaddr is address(0)"); fundaddr = _fundaddr; emit SetFund(_fundaddr); } // Update fee address by the previous institution. function setFee(address _feeaddr) public { require(msg.sender == feeaddr, "feeaddr: wut?"); require(_feeaddr != address(0), "_feeaddr is address(0)"); feeaddr = _feeaddr; emit SetFee(_feeaddr); } }
Update fee address by the previous institution.
function setFee(address _feeaddr) public { require(msg.sender == feeaddr, "feeaddr: wut?"); require(_feeaddr != address(0), "_feeaddr is address(0)"); feeaddr = _feeaddr; emit SetFee(_feeaddr); }
15,865,820
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import 'hardhat/console.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '../base/ERC721FullUpgradeable.sol'; import '../base/SignatureVerifier.sol'; import '../erc721/Worlds.sol'; import '../erc721/Degens.sol'; import '../utility/DegenData.sol'; import '../utility/DystopianData.sol'; import '../utility/DystopianDataFactory.sol'; import '../utility/WorldTreasury.sol'; import '../lib/Strings.sol'; // Upgradeable contract containing the Dystopian ERC721 tokens. // Each token gets its own DystopianData contract. contract Dystopians is ERC721FullUpgradeable, SignatureVerifier { using CountersUpgradeable for CountersUpgradeable.Counter; using Strings for string; // the cost to rename a dystopian uint256 renameCost; // the costs and skill requiremets to craft of each class of dystopian. mapping(uint16 => CraftRules) craftRules; // metadata for each Dystopian token including the address of the token's data contract. mapping(uint256 => DystopianToken) tokenMeta; // we need to know the worlds contract address to pass to the data contract. // we also use it to fetch token addresses from the world's treasury. Worlds worlds; // we veify the player's stats to mint a new dystopian. Degens degens; // the dystopian data factory is responsible for deploying new DystopianData contracts. DystopianDataFactory dystopianDataFactory; // payments (mint fees) are sent to this address address payable payments; string private constant tokenNotRegisteredError = 'Token not registered: '; string private constant insufficientBalanceError = 'Not enough tokens to craft: '; // emitted when a dystopian is minted event DystopianCreated(uint256 indexed id, uint256 indexed degen, address indexed owner, uint16 class, address dataContract); // emitted when a dystopian class is registered event DystopianRegistered(uint16 class); function initialize( uint256 _renameCost, address _dystopianDataFactory, address _worlds, address _degens, address _payments ) public initializer { _initialize('Dystopians', 'DYSTOPIANS'); renameCost = _renameCost; worlds = Worlds(_worlds); degens = Degens(_degens); payments = payable(_payments); dystopianDataFactory = DystopianDataFactory(_dystopianDataFactory); } // set the address of the worlds contract. // because they have a circular dependency, we choose to initialize Dystopians first. function setCraftRules(CraftRules[] calldata _rules) external onlyOwner { for (uint256 i = 0; i < _rules.length; i++) { craftRules[_rules[i].class] = _rules[i]; emit DystopianRegistered(_rules[i].class); } } // craft (mint) new dystopian token and create a new DystopianData contract for it // the world ensures that function craftDystopian( uint256 _degen, uint256 _degenWorld, uint16 _class, Dystopian calldata _dystopianData, bytes calldata _worldSignature ) external payable returns (uint256) { verifySignature(_degenWorld, _degen, _class, _dystopianData, _worldSignature); console.log('signature verified'); address _degenOwner = degens.ownerOf(_degen); require(_degenOwner == msg.sender, 'Only the degen owner can craft a dystopian.'); console.log('degen owner verified'); CraftRules memory _classRules = craftRules[_class]; require(_classRules.recipe.tokens.length > 0, 'Invalid class.'); console.log('class verified'); // check if allowances are enough to mint for (uint256 i = 0; i < _classRules.recipe.tokens.length; i++) { Token memory _token = _classRules.recipe.tokens[i]; console.log('checking allowance for token', _token.name, 'must be greater than', _token.amount); // fetch the token address from the world's treasury WorldTreasury _worldTreasury = worlds.getWorldTreasury(_degenWorld); if (bytes(_token.name).length == 0) { // recipe requires eth require(msg.value >= _token.amount, 'Not enough ETH to craft.'); // transfer ETH to the payments contract payments.transfer(address(this).balance); // transfer entire balance to the payments address } else { // recipe requires token IERC20 _tokenContract = _worldTreasury.getRegisteredToken(_token.name); require(address(_tokenContract) != address(0), tokenNotRegisteredError.concatenate(_token.name)); uint256 _allowance = _tokenContract.allowance(msg.sender, address(this)); console.log('allowance for token', _token.name, ':', _allowance); require( _allowance >= _token.amount, insufficientBalanceError.concatenate(_token.name).concatenate(uint2str(_token.amount)) ); // transfer tokens to the payments contract bool _transferSuccessful = _tokenContract.transferFrom(msg.sender, payments, _token.amount); require(_transferSuccessful, 'Failed to transfer tokens.'); console.log('transferred token', _token.name, _token.amount); } console.log('finished token transfer'); } // mint the token uint256 _id = super.safeMint(msg.sender); // create the data contract DystopianData _data = dystopianDataFactory.deployDystopianData( _id, _classRules.name, renameCost, address(worlds), address(this), payments ); // save the dystopian data for the first time // no signature required _data.updateDystopianData(_degenWorld, _dystopianData, abi.encode(0)); // store the data contract tokenMeta[_id] = DystopianToken(_class, _data); // emit the event emit DystopianCreated(_id, _degen, msg.sender, _class, address(_data)); return _id; } function verifySignature( uint256 _degenWorld, uint256 _degen, uint16 _class, Dystopian calldata _dystopianData, bytes calldata _worldSignature ) private view { address _worldOwner = worlds.ownerOf(_degenWorld); require(_worldOwner != address(0), 'no one owns this world'); bytes32 _nextHash = getNextHash(_degen, _dystopianData, _class); (address _signer, , ) = getSigner(_nextHash, _worldSignature); console.log('signer:', _signer, 'world owner:' , _worldOwner); require(_signer == _worldOwner, 'the owner of the world must sign Dystopian mints'); } // get the DystopianToken metadata for a given dystopian function getDystopianToken(uint256 _id) external view returns (DystopianToken memory) { return tokenMeta[_id]; } // get the rules for crafting a class of dystopians function getCraftRules(uint16 _class) external view returns (CraftRules memory) { return craftRules[_class]; } // get the next hash for the world to sign. // only valid for one mint. function getNextHash( uint256 _degen, Dystopian calldata _dystopianData, uint16 _class ) public view returns (bytes32) { // hash the token count + the address so that every hash for every mint gets a unique hash. uint256 _tokenCount = tokenIdCounter.current(); return keccak256(abi.encode(_tokenCount, _degen, _class, _dystopianData, address(this))); } } // metadata about each dystopian including rarity, generation & seed struct DystopianToken { uint16 class; // the data contract deployed for each dystopian DystopianData dataContract; } struct CraftRules { // the class of the dystopian to be crafted uint16 class; // the recipe (token cost) for crafting this dystopian. Inventory recipe; // the name of the class string name; } // dreadful function uint2str(uint256 _i) pure returns (string memory _uintAsString) { if (_i == 0) { return '0'; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 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); }
set the address of the worlds contract. because they have a circular dependency, we choose to initialize Dystopians first.
function setCraftRules(CraftRules[] calldata _rules) external onlyOwner { for (uint256 i = 0; i < _rules.length; i++) { craftRules[_rules[i].class] = _rules[i]; emit DystopianRegistered(_rules[i].class); } }
5,346,026
./full_match/1/0xBf3B3b9368262Ed9BD06B621149CA947984D1B31/sources/contracts/main/TruStakeMATICv2.sol
more gas efficient to use assembly for zero address check
function _checkNotZeroAddress(address toCheck) private pure { assembly { if iszero(toCheck) { let ptr := mload(0x40) revert(ptr, 0x4) } } }
4,869,172
// optimizer: 4289999999 // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_BALANCE_OF = 0x70a08231; // balanceOf(address) bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a gas-optimized balance check to avoid a redundant extcodesize check in addition to the returndatasize check. /// @param token The address of the ERC-20 token. /// @param to The address of the user to check. /// @return amount The token amount. function safeBalanceOf(IERC20 token, address to) internal view returns (uint256 amount) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_BALANCE_OF, to)); require(success && data.length >= 32, "BoringERC20: BalanceOf failed"); amount = abi.decode(data, (uint256)); } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } interface IFlashBorrower { /// @notice The flashloan callback. `amount` + `fee` needs to repayed to msg.sender before this call returns. /// @param sender The address of the invoker of this flashloan. /// @param token The address of the token that is loaned. /// @param amount of the `token` that is loaned. /// @param fee The fee that needs to be paid on top for this loan. Needs to be the same as `token`. /// @param data Additional data that was passed to the flashloan function. function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } interface IBatchFlashBorrower { /// @notice The callback for batched flashloans. Every amount + fee needs to repayed to msg.sender before this call returns. /// @param sender The address of the invoker of this flashloan. /// @param tokens Array of addresses for ERC-20 tokens that is loaned. /// @param amounts A one-to-one map to `tokens` that is loaned. /// @param fees A one-to-one map to `tokens` that needs to be paid on top for each loan. Needs to be the same token. /// @param data Additional data that was passed to the flashloan function. function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } /// @notice Interface for SushiSwap. interface ISushiSwap { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } /// @notice Interface for depositing into SushiBar. interface ISushiBarEnter { function enter(uint256 amount) external; } contract FlashXsushiFromBentoBoxToSushiSwapAndStakeAgain is IFlashBorrower { using BoringMath for uint256; using BoringERC20 for IERC20; IERC20 constant wETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // ETH wrapper contract v9 (mainnet) IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract (mainnet) address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI (mainnet) ISushiSwap constant sushiSwapSushiETHpair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap (mainnet) ISushiSwap constant sushiSwapXsushiETHpair = ISushiSwap(0x36e2FCCCc59e5747Ff63a03ea2e5C0c2C14911e7); // xSUSHI/ETH pair on SushiSwap (mainnet) constructor() public { sushiToken.approve(sushiBar, type(uint256).max); // max approve xSUSHI staking from this contract } function onFlashLoan( address sender, // account that activates flash loan from BENTO IERC20, // default to flash borrow xSUSHI uint256 amount, // xSUSHI amount flash borrowed uint256 fee, // BENTO flash loan fee bytes calldata // default to not use data in flash loan ) external override { /// @dev The following internal functions run xSUSHI flash loan strategy (swap/swap/stake). swapFlashxSushiForWeth(amount); // swap borrowed xSUSHI for wETH swapWethForSushi(); // swap output wETH for SUSHI ISushiBarEnter(sushiBar).enter(sushiToken.safeBalanceOf(address(this))); // stake output SUSHI into xSUSHI /// @dev The following functions pay back xSUSHI to BENTO with fee and send any winnings to `sender`. uint256 payback = amount.add(fee); // calculate `payback` to BENTO as borrowed xSUSHI `amount` + `fee` IERC20(sushiBar).safeTransfer(msg.sender, payback); // send `payback` to BENTO IERC20(sushiBar).safeTransfer(sender, IERC20(sushiBar).safeBalanceOf(address(this)).sub(payback)); // skim remainder xSUSHI winnings to `sender` } function swapFlashxSushiForWeth(uint256 amount) private { (uint256 reserve0, uint256 reserve1, ) = sushiSwapXsushiETHpair.getReserves(); uint256 amountInWithFee = amount.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); sushiSwapXsushiETHpair.swap(0, out, address(this), ""); } function swapWethForSushi() private { uint256 wETHamount = wETH.safeBalanceOf(address(this)); (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHpair.getReserves(); uint256 amountInWithFee = wETHamount.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); wETH.safeTransfer(address(sushiSwapSushiETHpair), wETHamount); sushiSwapSushiETHpair.swap(out, 0, address(this), ""); } }
Interface for SushiSwap.
interface ISushiSwap { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } }
12,657,065
pragma solidity ^0.4.18; interface trinityData{ function getChannelBalance(bytes32 channelId) external view returns (uint256); function getChannelStatus(bytes32 channelId) external view returns(uint8); function getChannelExist(bytes32 channelId) external view returns(bool); function getChannelClosingSettler(bytes32 channelId) external view returns (address); function getSettlingTimeoutBlock(bytes32 channelId) external view returns(uint256); function getChannelPartners(bytes32 channelId) external view returns (address,address); function getClosingSettle(bytes32 channelId)external view returns (uint256,uint256,address,address,uint256,uint256); function getTimeLock(bytes32 channelId, bytes32 lockHash) external view returns(address,address,uint256,uint256, uint256, bool); } contract TrinityEvent{ event Deposit(bytes32 channleId, address partnerA, uint256 amountA,address partnerB, uint256 amountB); event UpdateDeposit(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event QuickCloseChannel(bytes32 channleId, address closer, uint256 amount1, address partner, uint256 amount2); event CloseChannel(bytes32 channleId, address invoker, uint256 nonce, uint256 blockNumber); event UpdateTransaction(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event Settle(bytes32 channleId, address partnerA, uint256 amountA, address partnerB, uint256 amountB); event Withdraw(bytes32 channleId, address invoker, uint256 nonce, bytes32 hashLock, bytes32 secret); event WithdrawUpdate(bytes32 channleId, bytes32 hashLock, uint256 nonce, uint256 balance); event WithdrawSettle(bytes32 channleId, bytes32 hashLock, uint256 balance); } contract Owner{ address public owner; bool paused; constructor() public{ owner = msg.sender; paused = false; } modifier onlyOwner(){ require(owner == msg.sender); _; } modifier whenNotPaused(){ require(!paused); _; } modifier whenPaused(){ require(paused); _; } //disable contract setting funciton function pause() external onlyOwner whenNotPaused { paused = true; } //enable contract setting funciton function unpause() public onlyOwner whenPaused { paused = false; } } contract VerifySignature{ function verifyTimelock(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockPeriod , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature) internal pure returns(bool) { address recoverA = verifyLockSignature(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash, partnerAsignature); address recoverB = verifyLockSignature(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash, partnerBsignature); if ((recoverA == sender && recoverB == receiver) || (recoverA == receiver && recoverB == sender)){ return true; } return false; } function verifyLockSignature(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockPeriod , uint256 lockAmount, bytes32 lockHash, bytes signature) internal pure returns(address) { bytes32 data_hash; address recover_addr; data_hash=keccak256(channelId, nonce, sender, receiver, lockPeriod, lockAmount,lockHash); recover_addr=_recoverAddressFromSignature(signature,data_hash); return recover_addr; } /* * Funcion: parse both signature for check whether the transaction is valid * Parameters: * addressA: node address that deployed on same channel; * addressB: node address that deployed on same channel; * balanceA : nodaA assets amount; * balanceB : nodaB assets assets amount; * nonce: transaction nonce; * signatureA: A signature for this transaction; * signatureB: B signature for this transaction; * Return: * result: if both signature is valid, return TRUE, or return False. */ function verifyTransaction( bytes32 channelId, uint256 nonce, address addressA, uint256 balanceA, address addressB, uint256 balanceB, bytes signatureA, bytes signatureB) internal pure returns(bool result){ address recoverA; address recoverB; recoverA = recoverAddressFromSignature(channelId, nonce, addressA, balanceA, addressB, balanceB, signatureA); recoverB = recoverAddressFromSignature(channelId, nonce, addressA, balanceA, addressB, balanceB, signatureB); if ((recoverA == addressA && recoverB == addressB) || (recoverA == addressB && recoverB == addressA)){ return true; } return false; } function recoverAddressFromSignature( bytes32 channelId, uint256 nonce, address addressA, uint256 balanceA, address addressB, uint256 balanceB, bytes signature ) internal pure returns(address) { bytes32 data_hash; address recover_addr; data_hash=keccak256(channelId, nonce, addressA, balanceA, addressB, balanceB); recover_addr=_recoverAddressFromSignature(signature,data_hash); return recover_addr; } function _recoverAddressFromSignature(bytes signature,bytes32 dataHash) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; (r,s,v)=signatureSplit(signature); return ecrecoverDecode(dataHash,v, r, s); } function signatureSplit(bytes signature) pure internal returns (bytes32 r, bytes32 s, uint8 v) { assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := and(mload(add(signature, 65)), 0xff) } v=v+27; require((v == 27 || v == 28), "check v value"); } function ecrecoverDecode(bytes32 datahash,uint8 v,bytes32 r,bytes32 s) internal pure returns(address addr){ addr=ecrecover(datahash,v,r,s); return addr; } } library SafeMath{ function add256(uint256 addend, uint256 augend) internal pure returns(uint256 result){ uint256 sum = addend + augend; assert(sum >= addend); return sum; } function sub256(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } contract TrinityContractCore is Owner, VerifySignature, TrinityEvent{ using SafeMath for uint256; uint8 constant OPENING = 1; uint8 constant CLOSING = 2; uint8 constant LOCKING = 3; trinityData public trinityDataContract; constructor(address _dataAddress) public{ trinityDataContract = trinityData(_dataAddress); } function getChannelBalance(bytes32 channelId) public view returns (uint256){ return trinityDataContract.getChannelBalance(channelId); } function getChannelStatus(bytes32 channelId) public view returns (uint8){ return trinityDataContract.getChannelStatus(channelId); } function getTimeoutBlock(bytes32 channelId) public view returns (uint256){ return trinityDataContract.getSettlingTimeoutBlock(channelId); } function setDataContract(address _dataContract) external onlyOwner { trinityDataContract = trinityData(_dataContract); } /* * Function: 1. Lock both participants assets to the contract * 2. setup channel. * Before lock assets,both participants must approve contract can spend special amout assets. * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * amountA : partnerA will lock assets amount; * amountB : partnerB will lock assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * Return: * Null; */ function deposit(bytes32 channelId, uint256 nonce, address funderAddress, uint256 funderAmount, address partnerAddress, uint256 partnerAmount, bytes funderSignature, bytes partnerSignature) external whenNotPaused{ //verify both signature to check the behavious is valid. require(verifyTransaction(channelId, nonce, funderAddress, funderAmount, partnerAddress, partnerAmount, funderSignature, partnerSignature) == true); bool channelExist = trinityDataContract.getChannelExist(channelId); //if channel have existed, can not create it again require(channelExist == false, "check whether channel exist"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("depositData(bytes32,address,uint256,address,uint256)")), channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); require(callResult == true); emit Deposit(channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); } function updateDeposit(bytes32 channelId, uint256 nonce, address funderAddress, uint256 funderAmount, address partnerAddress, uint256 partnerAmount, bytes funderSignature, bytes partnerSignature) external whenNotPaused{ //verify both signature to check the behavious is valid. require(verifyTransaction(channelId, nonce, funderAddress, funderAmount, partnerAddress, partnerAmount, funderSignature, partnerSignature) == true, "verify signature"); require(getChannelStatus(channelId) == OPENING, "check channel status"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("updateDeposit(bytes32,address,uint256,address,uint256)")), channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); require(callResult == true, "call result"); emit UpdateDeposit(channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); } function withdrawBalance(bytes32 channelId, uint256 nonce, address funder, uint256 funderBalance, address partner, uint256 partnerBalance, bytes closerSignature, bytes partnerSignature) external whenNotPaused{ uint256 totalBalance = 0; //verify both signatures to check the behavious is valid require(verifyTransaction(channelId, nonce, funder, funderBalance, partner, partnerBalance, closerSignature, partnerSignature) == true, "verify signature"); require(nonce == 0, "check nonce"); require((msg.sender == funder || msg.sender == partner), "verify caller"); //channel should be opening require(getChannelStatus(channelId) == OPENING, "check channel status"); //sum of both balance should not larger than total deposited assets totalBalance = funderBalance.add256(partnerBalance); require(totalBalance <= getChannelBalance(channelId),"check channel balance"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("withdrawBalance(bytes32,address,uint256,address,uint256)")), channelId, funder, funderBalance, partner, partnerBalance); require(callResult == true, "call result"); emit QuickCloseChannel(channelId, funder, funderBalance, partner, partnerBalance); } function quickCloseChannel(bytes32 channelId, uint256 nonce, address funder, uint256 funderBalance, address partner, uint256 partnerBalance, bytes closerSignature, bytes partnerSignature) external whenNotPaused{ uint256 closeTotalBalance = 0; //verify both signatures to check the behavious is valid require(verifyTransaction(channelId, nonce, funder, funderBalance, partner, partnerBalance, closerSignature, partnerSignature) == true, "verify signature"); require(nonce == 0, "check nonce"); require((msg.sender == funder || msg.sender == partner), "verify caller"); //channel should be opening require(getChannelStatus(channelId) == OPENING, "check channel status"); //sum of both balance should not larger than total deposited assets closeTotalBalance = funderBalance.add256(partnerBalance); require(closeTotalBalance == getChannelBalance(channelId),"check channel balance"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("quickCloseChannel(bytes32,address,uint256,address,uint256)")), channelId, funder, funderBalance, partner, partnerBalance); require(callResult == true, "call result"); emit QuickCloseChannel(channelId, funder, funderBalance, partner, partnerBalance); } /* * Funcion: 1. set channel status as closing 2. withdraw assets for partner against closer 3. freeze closer settle assets untill setelement timeout or partner confirmed the transaction; * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * settleBalanceA : partnerA will withdraw assets amount; * settleBalanceB : partnerB will withdraw assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * settleNonce: closer provided nonce for settlement; * Return: * Null; */ function closeChannel(bytes32 channelId, uint256 nonce, address founder, uint256 founderBalance, address partner, uint256 partnerBalance, bytes closerSignature, bytes partnerSignature) public whenNotPaused{ bool callResult; uint256 closeTotalBalance = 0; //verify both signatures to check the behavious is valid require(verifyTransaction(channelId, nonce, founder, founderBalance, partner, partnerBalance, closerSignature, partnerSignature) == true, "verify signature"); require(nonce != 0, "check nonce"); require((msg.sender == founder || msg.sender == partner), "check caller"); //channel should be opening require(getChannelStatus(channelId) == OPENING, "check channel status"); //sum of both balance should not larger than total deposited assets closeTotalBalance = founderBalance.add256(partnerBalance); require(closeTotalBalance == getChannelBalance(channelId), "check total balance"); if (msg.sender == founder){ //sender want close channel actively, withdraw partner balance firstly callResult = address(trinityDataContract).call(bytes4(keccak256("closeChannel(bytes32,uint256,address,uint256,address,uint256)")), channelId, nonce, founder, founderBalance, partner, partnerBalance); require(callResult == true); } else if(msg.sender == partner) { callResult = address(trinityDataContract).call(bytes4(keccak256("closeChannel(bytes32,uint256,address,uint256,address,uint256)")), channelId, nonce, partner, partnerBalance, founder, founderBalance); require(callResult == true); } emit CloseChannel(channelId, msg.sender, nonce, getTimeoutBlock(channelId)); } /* * Funcion: After closer apply closed channle, partner update owner final transaction to check whether closer submitted invalid information * 1. if bothe nonce is same, the submitted settlement is valid, withdraw closer assets 2. if partner nonce is larger than closer, then jugement closer have submitted invalid data, withdraw closer assets to partner; 3. if partner nonce is less than closer, then jugement closer submitted data is valid, withdraw close assets. * Parameters: * partnerA: partner that deployed on same channel; * partnerB: partner that deployed on same channel; * updateBalanceA : partnerA will withdraw assets amount; * updateBalanceB : partnerB will withdraw assets amount; * signedStringA: partnerA signature for this transaction; * signedStringB: partnerB signature for this transaction; * settleNonce: closer provided nonce for settlement; * Return: * Null; */ function updateTransaction(bytes32 channelId, uint256 nonce, address partnerA, uint256 updateBalanceA, address partnerB, uint256 updateBalanceB, bytes signedStringA, bytes signedStringB) external whenNotPaused{ uint256 updateTotalBalance = 0; require(verifyTransaction(channelId, nonce, partnerA, updateBalanceA, partnerB, updateBalanceB, signedStringA, signedStringB) == true, "verify signature"); require(nonce != 0, "check nonce"); // only when channel status is closing, node can call it require(getChannelStatus(channelId) == CLOSING, "check channel status"); // channel closer can not call it require(msg.sender == trinityDataContract.getChannelClosingSettler(channelId), "check settler"); //sum of both balance should not larger than total deposited asset updateTotalBalance = updateBalanceA.add256(updateBalanceB); require(updateTotalBalance == getChannelBalance(channelId), "check total balance"); verifyUpdateTransaction(channelId, nonce, partnerA, updateBalanceA, partnerB, updateBalanceB); } function verifyUpdateTransaction(bytes32 channelId, uint256 nonce, address partnerA, uint256 updateBalanceA, address partnerB, uint256 updateBalanceB) internal{ address channelSettler; address channelCloser; uint256 closingNonce; uint256 closerBalance; uint256 settlerBalance; bool callResult; (closingNonce, ,channelCloser,channelSettler,closerBalance,settlerBalance) = trinityDataContract.getClosingSettle(channelId); // if updated nonce is less than (or equal to) closer provided nonce, folow closer provided balance allocation if (nonce <= closingNonce){ } // if updated nonce is equal to nonce+1 that closer provided nonce, folow partner provided balance allocation else if (nonce == (closingNonce + 1)){ channelCloser = partnerA; closerBalance = updateBalanceA; channelSettler = partnerB; settlerBalance = updateBalanceB; } // if updated nonce is larger than nonce+1 that closer provided nonce, determine closer provided invalid transaction, partner will also get closer assets else if (nonce > (closingNonce + 1)){ closerBalance = 0; settlerBalance = getChannelBalance(channelId); } callResult = address(trinityDataContract).call(bytes4(keccak256("closingSettle(bytes32,address,uint256,address,uint256)")), channelId, channelCloser, closerBalance, channelSettler, settlerBalance); require(callResult == true); emit UpdateTransaction(channelId, channelCloser, closerBalance, channelSettler, settlerBalance); } /* * Function: after apply close channnel, closer can withdraw assets until special settle window period time over * Parameters: * partner: partner address that setup in same channel with sender; * Return: Null */ function settleTransaction(bytes32 channelId) external whenNotPaused{ uint256 expectedSettleBlock; uint256 closerBalance; uint256 settlerBalance; address channelCloser; address channelSettler; (, expectedSettleBlock,channelCloser,channelSettler,closerBalance,settlerBalance) = trinityDataContract.getClosingSettle(channelId); // only chanel closer can call the function and channel status must be closing require(msg.sender == channelCloser, "check closer"); require(expectedSettleBlock < block.number, "check settle time"); require(getChannelStatus(channelId) == CLOSING, "check channel status"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("closingSettle(bytes32,address,uint256,address,uint256)")), channelId, channelCloser, closerBalance, channelSettler, settlerBalance); require(callResult == true); emit Settle(channelId, channelCloser, closerBalance, channelSettler, settlerBalance); } function withdraw(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockTime , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature, bytes32 secret) external { require(verifyTimelock(channelId, nonce, sender, receiver, lockTime,lockAmount,lockHash,partnerAsignature,partnerBsignature) == true, "verify signature"); require(nonce != 0, "check nonce"); require(msg.sender == receiver, "check caller"); require(lockTime > block.number, "check lock time"); require(lockHash == keccak256(secret), "verify hash"); require(lockAmount <= getChannelBalance(channelId)); require(verifyWithdraw(channelId,lockHash) == true); bool callResult = address(trinityDataContract).call(bytes4(keccak256("withdrawLocks(bytes32,uint256,uint256,uint256,bytes32)")), channelId, nonce, lockAmount, lockTime, lockHash); bool result = address(trinityDataContract).call(bytes4(keccak256("withdrawPartners(bytes32,address,address,bytes32)")), channelId, sender, receiver, lockHash); require(callResult == true && result == true); emit Withdraw(channelId, msg.sender, nonce, lockHash, secret); } function verifyWithdraw(bytes32 channelId, bytes32 lockHash) internal view returns(bool){ bool withdrawLocked; (, , , , ,withdrawLocked) = trinityDataContract.getTimeLock(channelId,lockHash); require(withdrawLocked == false, "check withdraw status"); return true; } function withdrawUpdate(bytes32 channelId, uint256 nonce, address sender, address receiver, uint256 lockTime , uint256 lockAmount, bytes32 lockHash, bytes partnerAsignature, bytes partnerBsignature) external whenNotPaused{ address withdrawVerifier; require(verifyTimelock(channelId, nonce, sender, receiver, lockTime,lockAmount,lockHash,partnerAsignature,partnerBsignature) == true, "verify signature"); require(nonce != 0, "check nonce"); require(lockTime > block.number, "check lock time"); (withdrawVerifier, , , , , ) = trinityDataContract.getTimeLock(channelId,lockHash); require(msg.sender == withdrawVerifier, "check verifier"); verifyWithdrawUpdate(channelId, lockHash, nonce, lockAmount); } function verifyWithdrawUpdate(bytes32 channelId, bytes32 lockHash, uint256 nonce, uint256 lockAmount) internal{ address withdrawVerifier; address withdrawer; uint256 updateNonce; uint256 channelTotalBalance; bool withdrawLocked; bool callResult = false; (withdrawVerifier,withdrawer, updateNonce, , ,withdrawLocked) = trinityDataContract.getTimeLock(channelId,lockHash); require(withdrawLocked == true, "check withdraw status"); channelTotalBalance = getChannelBalance(channelId); require(lockAmount <= channelTotalBalance); if (nonce <= updateNonce){ channelTotalBalance = channelTotalBalance.sub256(lockAmount); callResult = address(trinityDataContract).call(bytes4(keccak256("withdrawSettle(bytes32,address,uint256,uint256,bytes32)")), channelId, withdrawer, lockAmount, channelTotalBalance, lockHash); } else if(nonce > updateNonce){ callResult = address(trinityDataContract).call(bytes4(keccak256("withdrawSettle(bytes32,address,uint256,uint256,bytes32)")), channelId, withdrawVerifier, channelTotalBalance, 0, lockHash); channelTotalBalance = 0; } require(callResult == true); emit WithdrawUpdate(channelId, lockHash, nonce, channelTotalBalance); } function withdrawSettle(bytes32 channelId, bytes32 lockHash, bytes32 secret) external whenNotPaused{ address _withdrawer; uint256 lockAmount; uint256 lockTime; uint256 _channelTotalBalance; bool withdrawLocked; require(lockHash == keccak256(secret), "verify hash"); (,_withdrawer, ,lockAmount,lockTime,withdrawLocked) = trinityDataContract.getTimeLock(channelId,lockHash); require(withdrawLocked == true, "check withdraw status"); require(msg.sender == _withdrawer, "check caller"); require(lockTime < block.number, "check time lock"); _channelTotalBalance = getChannelBalance(channelId); _channelTotalBalance = _channelTotalBalance.sub256(lockAmount); bool callResult = address(trinityDataContract).call(bytes4(keccak256("withdrawSettle(bytes32,address,uint256,uint256,bytes32)")), channelId, msg.sender, lockAmount, _channelTotalBalance, lockHash); require(callResult == true); emit WithdrawSettle(channelId, lockHash, _channelTotalBalance); } function () public { revert(); } }
verify both signature to check the behavious is valid.if channel have existed, can not create it again
function deposit(bytes32 channelId, uint256 nonce, address funderAddress, uint256 funderAmount, address partnerAddress, uint256 partnerAmount, bytes funderSignature, bytes partnerSignature) external whenNotPaused{ require(verifyTransaction(channelId, nonce, funderAddress, funderAmount, partnerAddress, partnerAmount, funderSignature, partnerSignature) == true); bool channelExist = trinityDataContract.getChannelExist(channelId); require(channelExist == false, "check whether channel exist"); bool callResult = address(trinityDataContract).call(bytes4(keccak256("depositData(bytes32,address,uint256,address,uint256)")), channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); require(callResult == true); emit Deposit(channelId, funderAddress, funderAmount, partnerAddress, partnerAmount); }
14,070,615
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IUniswapV2Router02.sol"; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; contract Multiswap { using SafeMath for uint256; using SafeERC20 for IERC20; // WETH Address address private immutable WETH; // Uniswap Router for swaps IUniswapV2Router02 private immutable uniswapRouter; // Referral data mapping (address => bool) private referrers; mapping (address => uint256) private referralFees; // Data struct struct ContractData { uint160 owner; uint16 swapFeeBase; uint16 swapFeeToken; uint16 referralFee; uint16 maxFee; } ContractData private data; // Modifier for only owner functions modifier onlyOwner { require(msg.sender == address(data.owner), "Not allowed"); _; } /** * @dev Constructor sets values for Uniswap, WETH, and fee data * * These values are the immutable state values for Uniswap and WETH. * */ constructor() { uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); data.owner = uint160(msg.sender); // add extra two digits to percent for accuracy (30 = 0.3) data.swapFeeBase = uint16(30); // 0.3% data.swapFeeToken = uint16(20); // 0.2% per token data.referralFee = uint16(4500); // 45% for referrals data.maxFee = uint16(150); // 1.5% max fee // Add standard referrers referrers[address(this)] = true; referrers[address(0x1190074795DAD0E61b61270De48e108427f8f817)] = true; } /** * @dev Enables receiving ETH with no function call */ receive() external payable {} fallback() external payable {} /** * @dev Checks and returns expected output fom ETH swap. */ function checkOutputsETH( address[] memory _tokens, uint256[] memory _percent, uint256 _total ) external view returns (address[] memory, uint256[] memory, uint256) { require(_tokens.length == _percent.length); uint256 _totalPercent = 0; (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(_total, _tokens.length); uint256[] memory _outputAmount = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; (_outputAmount[i],) = calcOutputEth( _tokens[i], valueToSend.mul(_percent[i]).div(100) ); } require(_totalPercent == 100); return (_tokens, _outputAmount, feeAmount); } /** * @dev Checks and returns expected output from token swap. */ function checkOutputsToken( address[] memory _tokens, uint256[] memory _percent, address _base, uint256 _total ) external view returns (address[] memory, uint256[] memory) { require(_tokens.length == _percent.length); uint256 _totalPercent = 0; uint256[] memory _outputAmount = new uint256[](_tokens.length); address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; path[2] = _tokens[i]; uint256[] memory expected = uniswapRouter.getAmountsOut(_total.mul(_percent[i]).div(100), path); _outputAmount[i] = uint256(expected[1]); } require(_totalPercent == 100); return (_tokens, _outputAmount); } /** * @dev Checks and returns ETH value of token amount. */ function checkTokenValueETH(address _token, uint256 _amount) public view returns (uint256) { address[] memory path = new address[](2); path[0] = _token; path[1] = WETH; uint256[] memory expected = uniswapRouter.getAmountsOut(_amount, path); return expected[1]; } /** * @dev Checks and returns ETH value of portfolio. */ function checkAllValue(address[] memory _tokens, uint256[] memory _amounts) public view returns (uint256) { uint256 totalValue; for (uint i = 0; i < _tokens.length; i++) { totalValue += checkTokenValueETH(_tokens[i], _amounts[i]); } return totalValue; } /** * @dev Internal function to calculate the output from one ETH swap. */ function calcOutputEth(address _token, uint256 _value) internal view returns (uint256, address[] memory) { address[] memory path = new address[](2); path[0] = WETH; path[1] = _token; uint256[] memory expected = uniswapRouter.getAmountsOut(_value, path); return (expected[1], path); } /** * @dev Internal function to calculate the output from one token swap. */ function calcOutputToken(address[] memory _path, uint256 _value) internal view returns (uint256[] memory expected) { expected = uniswapRouter.getAmountsOut(_value, _path); return expected; } /** * @dev Execute ETH swap for each token in portfolio. */ function makeETHSwap(address[] memory _tokens, uint256[] memory _percent, address _referrer) external payable returns (uint256[] memory) { (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(msg.value, _tokens.length); uint256 totalPercent; uint256[] memory outputs = new uint256[](_tokens.length); address[] memory path = new address[](2); path[0] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Exceeded 100%'); path[1] = _tokens[i]; uint256 swapVal = valueToSend.mul(_percent[i]).div(100); uint256[] memory expected = uniswapRouter.getAmountsOut(swapVal, path); uint256[] memory out = uniswapRouter.swapExactETHForTokens{value: swapVal}( expected[1], path, msg.sender, block.timestamp + 1200 ); outputs[i] = out[1]; } require(totalPercent == 100, 'Percent not 100'); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Failed to send referral fee'); } return outputs; } /** * @dev Execute token swap for each token in portfolio. */ function makeTokenSwap( address[] memory _tokens, uint256[] memory _percent, address _base, uint256 _total) external returns (uint256[] memory) { IERC20 token = IERC20(_base); uint256 totalPercent = 0; uint256[] memory outputs = new uint256[](_tokens.length); token.safeTransferFrom(msg.sender, address(this), _total); require(token.approve(address(uniswapRouter), _total), 'Uniswap approval failed'); address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Exceeded 100'); path[2] = _tokens[i]; uint256 swapVal = _total.mul(_percent[i]).div(100); uint256[] memory expected = uniswapRouter.getAmountsOut(swapVal, path); uint256[] memory out = uniswapRouter.swapExactTokensForTokens( expected[0], expected[1], path, msg.sender, block.timestamp + 1200 ); outputs[i] = out[1]; } require(totalPercent == 100, 'Percent not 100'); return outputs; } /** * @dev Swap tokens for ETH */ function makeTokenSwapForETH( address[] memory _tokens, uint256[] memory _amounts, address _referrer ) external payable returns (uint256) { address[] memory path = new address[](2); path[1] = WETH; uint256 totalOutput; for (uint i = 0; i < _tokens.length; i++) { path[0] = _tokens[i]; IERC20 token = IERC20(_tokens[i]); token.transferFrom(msg.sender, address(this), _amounts[i]); token.approve(address(uniswapRouter), _amounts[i]); uint256[] memory expected = uniswapRouter.getAmountsOut(_amounts[i], path); uint256[] memory swapOutput = uniswapRouter.swapExactTokensForETH(expected[0], expected[1], path, address(this), block.timestamp + 1200); totalOutput = totalOutput.add(swapOutput[1]); } (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(totalOutput, _tokens.length); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Failed to send referral fee'); } (bool delivered, ) = msg.sender.call{value: valueToSend}(""); require(delivered, 'Failed to send swap output'); return valueToSend; } /** * @dev Apply fee to total value amount for ETH swap. */ function applyFeeETH(uint256 _amount, uint256 _numberOfTokens) private view returns (uint256 valueToSend, uint256 feeAmount) { uint256 feePercent = _numberOfTokens.mul(data.swapFeeToken); feePercent -= data.swapFeeToken; feePercent += data.swapFeeBase; feeAmount = _amount.mul(feePercent).div(10000); valueToSend = _amount.sub(feeAmount); return (valueToSend, feeAmount); } /** * @dev Take referral fee and distribute */ function takeReferralFee(uint256 _fee, address _referrer) internal returns (uint256) { require(referrers[_referrer], 'Not signed up as referrer'); uint256 referralFee = _fee.mul(data.referralFee).div(10000); referralFees[_referrer] = referralFees[_referrer].add(referralFee); return referralFee; } /** * @dev Owner only function to update contract fees. */ function updateFee( uint16 _newFeeBase, uint16 _newFeeToken, uint16 _newFeeReferral, uint16 _newMaxFee ) public onlyOwner returns (bool) { data.swapFeeBase = _newFeeBase; data.swapFeeToken = _newFeeToken; data.referralFee = _newFeeReferral; data.maxFee = _newMaxFee; return true; } /** * @dev Returns current app fees. */ function getCurrentFee() external view returns ( uint16, uint16, uint16, uint16 ) { return (data.swapFeeBase, data.swapFeeToken, data.referralFee, data.maxFee); } /** * @dev Owner only function to change contract owner. */ function changeOwner(address newOwner) external onlyOwner returns (bool) { data.owner = uint160(newOwner); return true; } /** * @dev Owner only function to change contract owner. */ function addReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = true; return true; } /** * @dev Owner only function to change contract owner. */ function removeReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = false; return true; } /** * @dev Return owner address */ function getOwner() external view returns (address) { return address(data.owner); } /** * @dev Function to see referral balancees */ function getReferralFees(address _referrer) external view returns (uint256) { return referralFees[_referrer]; } /** * @dev Owner only function to retreive ETH fees */ function retrieveEthFees() external onlyOwner { (bool sent, ) = address(data.owner).call{value: address(this).balance}(""); require(sent, 'Transfer failed'); } } // 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.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; import "./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; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
Internal function to calculate the output from one ETH swap./
function calcOutputEth(address _token, uint256 _value) internal view returns (uint256, address[] memory) { address[] memory path = new address[](2); path[0] = WETH; path[1] = _token; uint256[] memory expected = uniswapRouter.getAmountsOut(_value, path); return (expected[1], path); }
548,216
pragma solidity ^0.4.24; contract POOHMOevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 POOHAmount, uint256 genAmount, uint256 potAmount ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 POOHAmount, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 POOHAmount, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 POOHAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract POOHMO is POOHMOevents { using SafeMath for *; using NameFilter for string; using KeysCalc for uint256; PlayerBookInterface private PlayerBook; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; address private flushDivs; string constant public name = "POOHMO"; string constant public symbol = "POOHMO"; uint256 private rndExtra_ = 1 minutes; // length of the very first ICO uint256 private rndGap_ = 1 minutes; // length of ICO phase, set to 1 year for EOS. uint256 private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer uint256 private rndMax_ = 6 hours; // max length a round timer can be uint256[6] private timerLengths = [30 minutes,60 minutes,120 minutes,360 minutes,720 minutes,1440 minutes]; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => POOHMODatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => POOHMODatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => POOHMODatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => POOHMODatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => POOHMODatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor(address whaleContract, address playerbook) public { flushDivs = whaleContract; PlayerBook = PlayerBookInterface(playerbook); //no teams... only POOH-heads // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = POOHMODatasets.TeamFee(47,10); //30% to pot, 10% to aff, 2% to com, 1% potSwap potSplit_[0] = POOHMODatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0); require(_addr == tx.origin); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000); require(_eth <= 100000000000000000000000); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data POOHMODatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data POOHMODatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data POOHMODatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data POOHMODatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit POOHMOevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.POOHAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit POOHMOevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3] //12 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, POOHMODatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, 0, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit POOHMOevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.POOHAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, POOHMODatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, 0, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit POOHMOevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.POOHAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000) { uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][0] = _eth.add(rndTmEth_[_rID][0]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 0, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, 0, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, 0, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook)); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook)); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(POOHMODatasets.EventReturns memory _eventData_) private returns (POOHMODatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, POOHMODatasets.EventReturns memory _eventData_) private returns (POOHMODatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(POOHMODatasets.EventReturns memory _eventData_) private returns (POOHMODatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; //48% uint256 _dev = (_pot / 50); //2% uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _POOH = (_pot.mul(potSplit_[_winTID].pooh)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_dev)).sub(_gen)).sub(_POOH); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards admin.transfer(_dev); flushDivs.transfer((_POOH.sub(_POOH / 3)).mul(2)); // 2/3 round_[_rID].pot = _pot.add(_POOH / 3); // 1/3 // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.POOHAmount = _POOH; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(timerLengths[determineNextRoundLength()]); round_[_rID].pot = _res; rndMax_ = round_[_rID].end; return(_eventData_); } function determineNextRoundLength() internal view returns(uint256 time) { uint256 roundTime = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))) % 6; return roundTime; } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to com, aff, and pooh */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_) private returns(POOHMODatasets.EventReturns) { // pay 1% out to dev uint256 _dev = _eth / 100; // 1% uint256 _POOH; if (!address(admin).call.value(_dev)()) { _POOH = _dev; _dev = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit POOHMOevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _POOH = _aff; } // pay out POOH _POOH = _POOH.add((_eth.mul(fees_[_team].pooh)) / (100)); if (_POOH > 0) { // deposit to divies contract uint256 _potAmount = _POOH / 2; flushDivs.transfer(_POOH.sub(_potAmount)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.POOHAmount = _POOH.add(_eventData_.POOHAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit POOHMOevents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_) private returns(POOHMODatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].pooh)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit POOHMOevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.POOHAmount, _eventData_.genAmount, _eventData_.potAmount ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin); // can only be ran once require(activated_ == false); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library POOHMODatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 POOHAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 pooh; // % of buy in thats paid to POOH holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 pooh; // % of pot thats paid to POOH holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library KeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78); require(_temp[1] != 0x58); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a)); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)=====================_|======================================================= logic runs whenever a buy order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ setup local rID grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
function buyCore(uint256 _pID, uint256 _affID, POOHMODatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, 0, _eventData_); if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit POOHMOevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.POOHAmount, _eventData_.genAmount ); } } }
9,997,509
// _ // (` ). _ // ( ). .:(` )`. // ) _( '`. :( . ) // .=(`( . ) .-- `. ( ) ) // (( (..__.:'-' .+( ) ` _` ) ) // `. `( ) ) ( . ) ( ) ._ // ) ` __.:' ) ( ( )) `-'.-(` ) // ) ) ( ) --' `- __.' :( )) // .-' (_.' .') `( ) )) // (_ ) dreaming gardens ` __.:' // // --..,___.--,--'`,---..-.--+--.,,-,,..._.--..-._.-a:f--. // // by @eddietree pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; contract DreamGardensNFT is ERC721Tradable { // JSONS string private _prerevealMetaURI = "https://gateway.pinata.cloud/ipfs/QmSX9UEjufVvifmszeUJENiCtMLFq8wA7jGhTJFdxeCACU/"; string private _revealedMetaURI = "https://gateway.pinata.cloud/ipfs/QmRA71NveXF5EFUSds873WqxkVuT8HvvATgz65ev3ea9d5/"; string private _nightmareMetaURI = "https://gateway.pinata.cloud/ipfs/QmbpWLqDtN3sdFtev4TkWca3tasGmAHgJkpXA21GBkLDke/"; // states bool public saleIsActive = false; bool public isRevealed = false; uint256 public constant MAX_SUPPLY = 128; uint256 public constant MAX_PUBLIC_MINT = 16; uint256 public constant PRICE_PER_TOKEN = 0.064 ether; bool [MAX_SUPPLY] private _nightmareMap; mapping(address => uint8) private _allowList; constructor(address _proxyRegistryAddress) ERC721Tradable("Dream Gardens NFT", "DREAMGARDEN", _proxyRegistryAddress) public { for(uint i = 0; i < MAX_SUPPLY; i+=1) { _nightmareMap[i] = false; } } function setSaleState(bool newState) public onlyOwner { saleIsActive = newState; } function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } function allowListNumAvailableToMint(address addr) external view returns (uint8) { return _allowList[addr]; } function revealAll() public onlyOwner { isRevealed = true; } ///////////////////// URI function setPreRevealURI(string memory _value) public onlyOwner { _prerevealMetaURI = _value; } function setRevealedURI(string memory _value) public onlyOwner { _revealedMetaURI = _value; } function setNightmareURI(string memory _value) public onlyOwner { _nightmareMetaURI = _value; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_tokenId >= 1 && _tokenId <= MAX_SUPPLY, "Not valid token range"); if (!isRevealed) { // prereveal return string(abi.encodePacked(_prerevealMetaURI, Strings.toString(_tokenId), ".json")); } else if (isNightmare(_tokenId)) { // nightmare return string(abi.encodePacked(_nightmareMetaURI, Strings.toString(_tokenId), ".json")); } else { // revealed return string(abi.encodePacked(_revealedMetaURI, Strings.toString(_tokenId), ".json")); } } /////////////// nightmare function isNightmare(uint256 _tokenId) public view returns (bool) { require(_tokenId >= 1 && _tokenId <= MAX_SUPPLY, "Not valid token range"); return _nightmareMap[_tokenId-1]; } function setNightmareMode(uint256 _tokenId) public { require(_tokenId >= 1 && _tokenId <= MAX_SUPPLY, "Not valid token range"); address ownerOfToken = ownerOf(_tokenId); require(ownerOfToken == msg.sender, "Not the owner"); // make sure owner owns this token if (ownerOfToken == msg.sender) { _nightmareMap[_tokenId-1] = true; } } function forceNightmareMode(uint256 _tokenId, bool _nightmareMode) public onlyOwner { require(_tokenId >= 1 && _tokenId <= MAX_SUPPLY, "Not valid token range"); _nightmareMap[_tokenId-1] = _nightmareMode; } function nightmareCount() public view returns (uint) { uint count = 0; for(uint i = 0; i < MAX_SUPPLY; i+=1) { count += _nightmareMap[i] == true ? 1 : 0; } return count; } /////////////// mint function reserveGarden(uint numberOfTokens) public onlyOwner { uint256 ts = totalSupply(); require(ts + numberOfTokens <= MAX_SUPPLY, "Mint would exceed max tokens"); for (uint256 i = 0; i < numberOfTokens; i++) { mintTo(msg.sender); } } function reserveGardenGift(uint numberOfTokens, address addr) public onlyOwner { uint256 ts = totalSupply(); require(ts + numberOfTokens <= MAX_SUPPLY, "Mint would exceed max tokens"); for (uint256 i = 0; i < numberOfTokens; i++) { mintTo(addr); } } function mintGardenAllowlist(uint8 numberOfTokens) public payable { uint256 ts = totalSupply(); require(numberOfTokens > 0, "Need to mint at least 1 token"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(numberOfTokens <= _allowList[msg.sender], "Exceeded max available to purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PRICE_PER_TOKEN * numberOfTokens <= msg.value, "Ether value sent is not correct"); _allowList[msg.sender] -= numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { mintTo(msg.sender); } } function mintGarden(uint numberOfTokens) public payable { uint256 ts = totalSupply(); require(saleIsActive, "Sale must be active to mint tokens"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PRICE_PER_TOKEN * numberOfTokens <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < numberOfTokens; i++) { mintTo(msg.sender); } } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ERC721, ContextMixin, NativeMetaTransaction, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _nextTokenId; address proxyRegistryAddress; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; // nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter _nextTokenId.increment(); _initializeEIP712(_name); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) internal { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(_to, currentTokenId); } /** @dev Returns the total tokens minted so far. 1 is always subtracted from the Counter since it tracks the next available tokenId. */ function totalSupply() public view returns (uint256) { return _nextTokenId.current() - 1; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
make sure owner owns this token
function setNightmareMode(uint256 _tokenId) public { require(_tokenId >= 1 && _tokenId <= MAX_SUPPLY, "Not valid token range"); address ownerOfToken = ownerOf(_tokenId); require(ownerOfToken == msg.sender, "Not the owner"); if (ownerOfToken == msg.sender) { _nightmareMap[_tokenId-1] = true; } }
5,801,678
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LENGTH659(UintSet storage set) internal view returns (uint256) {
14,087,573
// 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 Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string internal _name; // Token symbol string internal _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), "ERC721: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @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 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]; } } } /** * @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 ERC721URIStorage, 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), "Enumerable: 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(), "Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /** * @dev External interface of the EaselyContractInitializer. Formatted to enable ContractFactory * to have a single method that can deploy a wide variety of different contracts. */ interface IEaselyContractInitializer { function init(bool[8] memory bools, address[8] memory addresses, uint256[32] memory uints, string[8] memory strings) external; } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable(address primaryPayout, address[] memory royalties, uint256[] memory bps) external payable; } /** * @dev This implements three things on top of the standard ERC extensions. * 1. The ability for contract owners to mint claimable (burnable) tokens that can optionally * generate another token. * 2. The ability for current token owners to create ascending auctions, which locks the token for * the duration of the auction. * 3. The ability for current token owners to lazily sell their tokens in this contract instead of * needing a marketplace contract. */ contract EaselyStandardCollection is ERC721Enumerable, Ownable, IEaselyContractInitializer { using Strings for uint256; /** * @dev Auction structure that includes: * * @param address topBidder - Current top bidder who has already paid the price param below. Is * initialized with address(0) when there have been no bids. When a bidder gets outBid, * the old topBidder will get the price they paid returned. * @param uint256 price - Current top price paid by the topBidder. * @param uint256 startTimestamp - When the auction can start getting bidded on. * @param uint256 endTimestamp - When the auction can no longer get bid on. * @param uint256 minBidIncrement - The minimum each new bid has to be greater than the previous * bid in order to be the next topBidder. * @param uint256 minLastBidDuration - The minimum time each bid must hold the highest price before * the auction can settle. If people keep bidding, the auction can last for much longer than * the initial endTimestamp, and endTimestamp will continually be updated. */ struct Auction { address topBidder; uint256 price; uint256 startTimestamp; uint256 endTimestamp; uint256 minBidIncrement; uint256 minLastBidDuration; } /* Determines if every token in this contract is burnable/claimable by default */ bool public burnable; bool private hasInit = false; /* see {IEaselyPayout} for more */ address public constant payoutContractAddress = 0x68f5C1e24677Ac4ae845Dde07504EAaD98f82572; /* Optional addresses to distribute royalties for primary sales of this collection */ address[] public royalties; /* Optional basis points for above royalties addresses for primary sales of this collection */ uint256[] public royaltiesBPS; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public secondaryOwnerBPS; uint256 private nextTokenId = 0; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public timePerDecrement = 300; uint256 public constant maxRoyaltiesBPS = 9500; uint256 public constant maxSecondaryBPS = 1000; /* Mapping if a tokenId has an active auction or not */ mapping(uint256 => Auction) private _tokenIdToAuction; /* Mapping if a tokenId can be claimed */ mapping(uint256 => bool) private _tokenIdIsClaimable; /* Mapping for what the generated token's URI is if the token is claim */ mapping(uint256 => string) private _tokenIdToPostClaimURI; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) private _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) private _cancelledOrFinalizedSales; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration, address seller); event AuctionEndTimeAltered(uint256 tokenId, uint256 endTime, address seller); event AuctionCancelled(uint256 tokenId, address seller); event AuctionBidded(uint256 tokenId, uint256 newPrice, address bidder); event AuctionSettled(uint256 tokenId, uint256 price, address buyer, address seller); event ClaimableClaimed(address claimer, uint256 originalTokenId, uint256 newTokenId, string originalIpfs); event SaleCancelled(bytes32 hash); event SaleCompleted(bytes32 hash); /** * @dev Constructor function */ constructor( bool[8] memory bools, address[8] memory addresses, uint256[32] memory uints, string[8] memory strings ) ERC721(strings[0], strings[1]) { addresses[0] = _msgSender(); _init(bools, addresses, uints, strings); } function init( bool[8] memory bools, address[8] memory addresses, uint256[32] memory uints, string[8] memory strings ) external override { _init(bools, addresses, uints, strings); } function _init( bool[8] memory bools, address[8] memory addresses, uint256[32] memory uints, string[8] memory strings ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _owner = addresses[0]; address[4] memory royaltiesAddrs = [addresses[1], addresses[2], addresses[3], addresses[4]]; // Only used for local testing. // payoutContractAddress = addresses[5]; _name = strings[0]; _symbol = strings[1]; _setSecondary(uints[0]); _setRoyalties(royaltiesAddrs, [uints[1], uints[2], uints[3], uints[4]]); if (uints[5] != 0) { timePerDecrement = uints[5]; } } /** * @dev Sets secondary BPS amount */ function _setSecondary(uint256 secondary) internal { secondaryOwnerBPS = secondary; require(secondaryOwnerBPS <= maxSecondaryBPS, "Cannot take more than 10% of secondaries"); } /** * @dev Sets primary royalties */ function _setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) internal { require(bps[0] + bps[1] + bps[2] + bps[3] <= maxRoyaltiesBPS, "Royalties too high"); royalties = newRoyalties; royaltiesBPS = bps; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } /** * @dev Changing _beforeTokenTransfer to lock tokens that are in an auction so * that owner cannot transfer the token as people are bidding on it. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!_validAuction(_tokenIdToAuction[tokenId]), "Cannot transfer a token in an auction"); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev checks if a token is in an auction or not. We make sure that no active auction can * have an endTimestamp of 0. */ function _validAuction(Auction memory auction) internal pure returns (bool) { return auction.endTimestamp != 0; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = secondaryOwnerBPS; return ownerBPS; } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheck( address owner, uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash, bool claimable ) internal view returns (bytes32) { return _toEthSignedMessageHash(_hash(owner, version, tokenId, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable)); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashForSale( address owner, uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash, bool claimable, uint8 v, bytes32 r, bytes32 s ) internal { bytes32 hash = _hashToCheck(owner, version, tokenId, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require(ecrecover(hash, v, r, s) == owner, "Not signed by current token owner"); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hash( address owner, uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash, bool claimable ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner, version, tokenId, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable)); } /** * @dev Current price for a sale which is calculated for the case of a descending auction. So * the ending price must be less than the starting price and the auction must have already started. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require(startingTimestamp < endingTimestamp, "Must end after it starts"); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / timePerDecrement; // This cannot equal 0 because if endingTimestamp == startingTimestamp, requirements will fail uint256 totalDecrements = (endingTimestamp - startingTimestamp) / timePerDecrement; return startingPrice - diff / totalDecrements * decrements; } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || interfaceId == type(Ownable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns the current auction variables for a tokenId if the auction is present */ function getAuction(uint256 tokenId) external view returns (Auction memory) { require(_validAuction(_tokenIdToAuction[tokenId]), "This auction does not exist"); return _tokenIdToAuction[tokenId]; } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyExistingToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token because unlike auctions * sales would be immediate. */ function hashToSignToSellToken( uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hash(_msgSender(), version, tokenId, pricesAndTimestamps, "", "", false); } /** * @dev Usable by the owner of this collection to sell a new token. The owner can decide what * the tokenURI of it will be and if the token is claimable and what the claimable hash would be */ function hashToSignToSellNewToken( bool claimable, uint256 version, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash ) external view onlyOwner returns (bytes32) { require(bytes(ipfsHash).length > 0, "Invalid ipfsHash"); return _hash(_msgSender(), version, 0, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. These are all considered secondary sales and will give a cut to the * owner of the contract based on the secondaryOwnerBPS. */ function buyExistingToken( address seller, uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint8 v, bytes32 r, bytes32 s ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require(_addressToActiveVersion[seller] == version, "Incorrect signature version"); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashForSale(seller, version, tokenId, pricesAndTimestamps, "", "", false, v, r, s); _transfer(seller, _msgSender(), tokenId); IEaselyPayout(payoutContractAddress).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev With a hash signed by the method {hashToSignToSellNewToken} any user sending enough value can * mint the token from the contract. These are all considered primary sales and will give a cut to the * royalties defined in the contract. */ function buyNewToken( bool claimable, uint256 version, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash, uint8 v, bytes32 r, bytes32 s ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require(_addressToActiveVersion[owner()] == version, "Incorrect signature version"); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashForSale(owner(), version, 0, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable, v, r, s); _safeMint(_msgSender(), nextTokenId); _setTokenURI(nextTokenId, ipfsHash); if (claimable) { _tokenIdIsClaimable[nextTokenId] = true; _tokenIdToPostClaimURI[nextTokenId] = claimedIpfsHash; } nextTokenId = nextTokenId + 1; IEaselyPayout(payoutContractAddress).splitPayable{ value: currentPrice }(owner(), royalties, royaltiesBPS); payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from both {hashToSignToSellNewToken} and {hashToSignToSellToken} */ function cancelSale( bool claimable, uint256 version, uint256 tokenId, uint256[4] memory pricesAndTimestamps, string memory ipfsHash, string memory claimedIpfsHash ) external { bytes32 hash = _hashToCheck(_msgSender(), version, tokenId, pricesAndTimestamps, ipfsHash, claimedIpfsHash, claimable); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(hash); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; } /** * @dev For any user who owns a token that is claimable. If the token has an * associated post claim hash then the claimer will get a newly minted token * with that hash after claiming. * * Claimed tokens that refer to off-chain benefits will be facillitated * by Easely, but are the responsibility of the contract creator to * deliver on the promises. */ function claimToken(uint256 tokenId) external { require(_exists(tokenId), "tokenId must exist"); require(_tokenIdIsClaimable[tokenId] || burnable, "tokenId must be claimable"); require(ownerOf(tokenId) == _msgSender(), "Only current tokenOwner can claim"); // lock the token from being claimed and thus also from being transferred _tokenIdIsClaimable[tokenId] = false; // If URI is set, mint the tagged token if (bytes(_tokenIdToPostClaimURI[tokenId]).length > 0) { _safeMint(_msgSender(), nextTokenId); _setTokenURI(nextTokenId, _tokenIdToPostClaimURI[tokenId]); emit ClaimableClaimed(_msgSender(), tokenId, nextTokenId, tokenURI(tokenId)); nextTokenId = nextTokenId + 1; } _burn(tokenId); } /** * @dev Creates an auction for a token and locks it from being transferred until the auction ends * the auction can end if the endTimestamp has been reached and can be cancelled prematurely if * there has been no bids yet. * * @param tokenId uint256 for the token to put on auction. Must exist and be on the auction already * @param startingPrice uint256 for the starting price an interested owner must bid * @param startingTimestamp uint256 for when the auction can start taking bids * @param endingTimestamp uint256 for when the auction has concluded and can no longer take bids * @param minBidIncrement uint256 the minimum each interested owner must bid over the latest bid * @param minLastBidDuration uint256 the minimum time a bid needs to be live before the auction can end. * this means that an auction can extend past its original endingTimestamp */ function createAuction( uint256 tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration ) external { require(endingTimestamp > block.timestamp, "Cannot create an auction in the past"); require(!_validAuction(_tokenIdToAuction[tokenId]), "Token is already on auction"); require(minBidIncrement > 0, "Min bid must be a positive number"); require(_msgSender() == ownerOf(tokenId), "Must own token to create auction"); Auction memory auction = Auction(address(0), startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration); // This locks the token from being sold _tokenIdToAuction[tokenId] = auction; emit AuctionCreated(tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration, ownerOf(tokenId)); } /** * @dev Lets the token owner alter the end time of an auction in case they want to end an auction early or extend * the auction. This can only be called when the auction has not yet been concluded and is not within * a minLastBidDuration from concluding. */ function alterEndTime(uint256 tokenId, uint256 endTime) external { // 0 EndTimestamp is reserved to check if a tokenId is on auction or not require(endTime != 0, "End time cannot be 0"); require(_msgSender() == ownerOf(tokenId), "Only token owner can alter end time"); Auction memory auction = _tokenIdToAuction[tokenId]; require(auction.endTimestamp > block.timestamp + auction.minLastBidDuration, "Auction has already ended"); auction.endTimestamp = endTime; _tokenIdToAuction[tokenId] = auction; emit AuctionEndTimeAltered(tokenId, endTime, ownerOf(tokenId)); } /** * @dev Allows the token owner to cancel an auction that does not yet have a bid. */ function cancelAuction(uint256 tokenId) external { require(_msgSender() == ownerOf(tokenId), "Only token owner can cancel auction"); Auction memory auction = _tokenIdToAuction[tokenId]; require(auction.topBidder == address(0), "Cannot cancel an auction with a bid"); delete _tokenIdToAuction[tokenId]; emit AuctionCancelled(tokenId, ownerOf(tokenId)); } /** * @dev Method that anyone can call to settle the auction. It is available to everyone * because the settlement is not dependent on the message sender, and will allow either * the buyer, the seller, or a third party to cover the gas fees to settle. The burdern of * the auction to settle should be on the seller, but in case there are issues with * the seller settling we will not be locked from settling. * * If the seller is the contract owner, this is considered a primary sale and royalties will * be paid to primiary royalties. If the seller is a user then it is a secondary sale and * the contract owner will get a secondary sale cut. */ function settleAuction(uint256 tokenId) external { Auction memory auction = _tokenIdToAuction[tokenId]; address tokenOwner = ownerOf(tokenId); require(block.timestamp > auction.endTimestamp, "Auction must end to be settled"); require(auction.topBidder != address(0), "No bidder, cancel the auction instead"); // This will allow transfers again delete _tokenIdToAuction[tokenId]; _transfer(tokenOwner, auction.topBidder, tokenId); if (tokenOwner == owner()) { IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, royalties, royaltiesBPS); } else { address[] memory ownerRoyalties = new address[](1); uint256[] memory ownerBPS = new uint256[](1); ownerRoyalties[0] = owner(); ownerBPS[0] = secondaryOwnerBPS; IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, ownerRoyalties, ownerBPS); } emit AuctionSettled(tokenId, auction.price, auction.topBidder, tokenOwner); } /** * @dev Allows any potential buyer to submit a bid on a token with an auction. When outbidding the current topBidder * the contract returns the value that the previous bidder had escrowed to the contract. */ function bidOnAuction(uint256 tokenId) external payable { uint256 timestamp = block.timestamp; Auction memory auction = _tokenIdToAuction[tokenId]; uint256 msgValue = msg.value; // Tokens that are not on auction always have an endTimestamp of 0 require(timestamp <= auction.endTimestamp, "Auction has already ended"); require(timestamp >= auction.startTimestamp, "Auction has not started yet"); uint256 minPrice = auction.price + auction.minBidIncrement; if (auction.topBidder == address(0)) { minPrice = auction.price; } require(msgValue >= minPrice, "Bid is too small"); uint256 endTime = auction.endTimestamp; if (endTime < auction.minLastBidDuration + timestamp) { endTime = timestamp + auction.minLastBidDuration; } Auction memory newAuction = Auction(_msgSender(), msgValue, auction.startTimestamp, endTime, auction.minBidIncrement, auction.minLastBidDuration); if (auction.topBidder != address(0)) { // Give the old top bidder their money back payable(auction.topBidder).transfer(auction.price); } _tokenIdToAuction[tokenId] = newAuction; emit AuctionBidded(tokenId, newAuction.price, newAuction.topBidder); } /** * @dev see {_setRoyalties} */ function setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) external onlyOwner { _setRoyalties(newRoyalties, bps); } /** * @dev see {_setSecondary} */ function setSecondaryBPS(uint256 bps) external onlyOwner() { _setSecondary(bps); } /** * @dev Allows the owner to create a new token with ipfsHash as the tokenURI. */ function mint(address collectorAddress, string memory ipfsHash) external onlyOwner { // mint token _safeMint(collectorAddress, nextTokenId); _setTokenURI(nextTokenId, ipfsHash); nextTokenId = nextTokenId + 1; } /** * @dev Adds a claimable hash to an existing token. If claimedIpfsHash is exactly "" then * no token will be created when the token is claimed, otherwise a new token with that hash * will be given to the token owner when they call {claimToken} */ function addClaimable( uint256 tokenId, string memory claimedIpfsHash ) external onlyOwner { require(_exists(tokenId), "tokenId must exist"); require(!_tokenIdIsClaimable[tokenId], "Claimable already exists"); _tokenIdIsClaimable[tokenId] = true; _tokenIdToPostClaimURI[tokenId] = claimedIpfsHash; } /** * @dev Allows the owner to create a new token with ipfsHash as the tokenURI that is also claimable. * If claimedIpfsHash is exactly "" then no token will be created when the token is claimed, otherwise * a new token with hash claimedIpfsHash will be given to the token owner when they call {claimToken} */ function mintClaimable( address collectorAddress, string memory ipfsHash, string memory claimedIpfsHash ) external onlyOwner { // mint token _safeMint(collectorAddress, nextTokenId); _setTokenURI(nextTokenId, ipfsHash); _tokenIdIsClaimable[nextTokenId] = true; _tokenIdToPostClaimURI[nextTokenId] = claimedIpfsHash; nextTokenId = nextTokenId + 1; } }
Changing _beforeTokenTransfer to lock tokens that are in an auction so that owner cannot transfer the token as people are bidding on it./
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!_validAuction(_tokenIdToAuction[tokenId]), "Cannot transfer a token in an auction"); super._beforeTokenTransfer(from, to, tokenId); }
1,178,430
/*** * 888b d888 8888888 * 8888b d8888 888 * 88888b.d88888 888 * 888Y88888P888 .d88b. 88888b. .d88b. .d88b. .d88b. .d8888b .d88b. 888 88888b. 888 888 * 888 Y888P 888 d88""88b 888 "88b d88P"88b d88""88b d88""88b 88K d8P Y8b 888 888 "88b 888 888 * 888 Y8P 888 888 888 888 888 888 888 888 888 888 888 "Y8888b. 88888888 888 888 888 888 888 * 888 " 888 Y88..88P 888 888 Y88b 888 Y88..88P Y88..88P X88 Y8b. 888 888 888 Y88b 888 * 888 888 "Y88P" 888 888 "Y88888 "Y88P" "Y88P" 88888P' "Y8888 8888888 888 888 "Y88888 * 888 * Y8b d88P * "Y88P" * * Yep, it has come to this... * Telegram: https://t.me/MongooseInu * */ // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract MongooseInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; //address payable public devAddress; address payable public liquidityAddress; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e13 * 1e9; // 100 Trillion uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Mongoose Inu"; string private constant _symbol = "MONGOOSEINU"; uint8 private constant _decimals = 9; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 1; uint256 public _buyLiquidityFee = 0; uint256 public _buyMarketingFee = 7; uint256 public _sellTaxFee = 1; uint256 public _sellLiquidityFee = 0; uint256 public _sellMarketingFee = 14; uint256 public tradingActiveBlock = 0; // 0 means trading is not active mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; //bool private gasLimitActive = false; //Changing this to false to facilitate smoother launches. //uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); //event BoughtEarly(address indexed sniper); //event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _rOwned[_msgSender()] = _rTotal / 1000 * 30; _rOwned[address(this)] = _rTotal / 1000 * 970; maxTransactionAmount = _tTotal * 15 / 1000; // 1.5% maxTransactionAmountTxn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0x5eEbEda785Fa9aC478F966a6cA781bb1e9f1AE14); // Marketing Address //devAddress = payable(0x0); // Dev Address liquidityAddress = payable(owner()); // Liquidity Address (switches to dead address once launch happens) - not really _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; //_isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), _msgSender(), _tTotal * 30 / 1000); emit Transfer(address(0), address(this), _tTotal * 970 / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; //gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; earlyBuyPenaltyEnd = block.timestamp + 72 hours; } // send tokens and ETH for liquidity to contract directly, then call this function. //(not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot relaunch."); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i]; _transfer(msg.sender, wallet, amount); } enableTrading(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require(address(this).balance > 0, "Must have ETH on contract to launch"); addLiquidity(balanceOf(address(this)), address(this).balance); //setLiquidityAddress(address(0xdead)); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } /*function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 200); gasPriceLimit = gas * 1 gwei; }*/ function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { //########### MARKER ############################################ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading not active yet!"); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){ boughtEarly[to] = true; //emit BoughtEarly(to); } // only use to prevent sniper buys in the first blocks. /*if (gasLimitActive && automatedMarketMakerPairs[from]) { //TODO: automatedMarketMakerPairs should be eliminated require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); }*/ // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[to] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[to] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } else { // Buy if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; buyOrSellSwitch = BUY; } // Sell else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; buyOrSellSwitch = SELL; // higher tax if bought in the same block as trading active for 72 hours (sniper protect) if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){ _taxFee = _taxFee * 5; _liquidityFee = _liquidityFee * 5; } // Normal transfers do not get taxed } else { require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mongoose Inu admin."); removeAllFee(); buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } } _tokenTransfer(from, to, amount, takeFee); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; // Halve the amount of liquidity tokens uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); //uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 goes to dev //ethForMarketing -= ethForDev; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; (bool success,) = address(marketingAddress).call{value: ethForMarketing}(""); //(success,) = address(devAddress).call{value: ethForDev}(""); if(tokensForLiquidity > 0) { //Either tokensForLiquidity > 0 or ethForLiquidity > 0 will work. addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // send leftover ETH to the marketing wallet so it doesn't get stuck on the contract. if(address(this).balance > 1e17){ (success,) = address(marketingAddress).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function removeBoughtEarly(address account) external onlyOwner { boughtEarly[account] = false; //emit RemovedSniper(account); } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; //emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; //emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 10, "Must keep buy taxes below 10%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 15, "Must keep sell taxes below 15%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
emit IncludeInFee(account);
function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; }
230,984
/* * Offer to respond to a proposal. */ contract Offer { /* * The seller who made this offer. */ address public owner; /* * Price offered at the minimum amount. */ uint public price; /* * Minimum amount of products to be bought. */ uint public minimumAmount; /* * Card ID used for payouts */ string public cardId; function setPrice(uint p){ if(tx.origin != owner) return; price = p; } function setMinimumAmount(uint a){ if(tx.origin != owner) return; minimumAmount = a; } function setCardId(string cId){ if(tx.origin != owner) return; cardId = cId; } function Offer(uint p, uint ma, string cId) { owner = tx.origin; price = p; minimumAmount = ma; cardId = cId; } } /* * A sungle buying proposal. */ contract Proposal { /* * Reference to the registry that this proposal is part of, to check the owner. */ ProposalRegistry public registry; /* * Name of the product to be bought. */ string public productName; /* * A description of the product that is unambiguous to all the stakeholders. */ string public productDescription; /* * The SKU (unique identification number) of the product. */ string public productSku; /* * Description of the indivisible unit size. E.g. "box of 12 cans". */ string public productUnitSize; /* * The product category in plain text. Future vevrsions might contain a more * advanced taxonomy of categories. */ string public mainCategory; /* * The product category in plain text. Future vevrsions might contain a more * advanced taxonomy of categories. */ string public subCategory; /* * Maximum price the buyers are willing to pay. */ uint public maxPrice; /* * Date after which this proposal is terminated. It can be terminated by * accepting a valid offer, or */ string public endDate; /* * Ultimate date when the products should be delivered to the buyers. */ string public ultimateDeliveryDate; // COULD DO: make it a contract of its own, so it can have functions. However // the getXXXamount functions still need to live in the Proposal because it // has the percentages. Unless we give the Backing contract a reference of // course... struct Backing { /* * Blockchain address of the buyer */ address buyerAddress; /* * Amount of products the buyer has committed to buy.s */ // TODO: rename to "count". "amount" is reserved for amounts of money. uint amount; /* * Transaction ID of the pledge payment (before closing a deal). * Transaction ID's currently are always 32 bytes. Therefore we * could change them to bytes32. That would allow string compare. * However there's no current need and it would require some code * changes. So sticking with string for now. */ string pledgePaymentTransactionID; /* * Amount of the pledge payment. */ uint pledgePaymentAmount; /* * Transaction ID of the initial payment (at moment of backing). */ string startPaymentTransactionID; /* * Amount of initial payment. */ uint startPaymentAmount; /* * Transaction ID of the final payment (after deliery). */ string endPaymentTransactionID; /* * Amount of the final payment. */ int endPaymentAmount; /* * Indicates whether the delivery has been reported by the backer. */ bool isDeliveryReported; /* * Indicates whether the delivery is correct according to the backer. * Any further details about the nature of what is or isn't correct * are discussed outside of the contract. */ bool isDeliveryCorrect; /* * Uphold card ID used for payments. */ string cardId; } /* * Prospective buyers backing this proposal. */ mapping(uint => Backing) public backers; uint public backerIndex; /* * Prospective buyers backing this proposal. */ mapping(uint => Offer) public offers; uint public offerIndex; /* * Index to help access the backer mapping. */ mapping(address => uint) public offerIndexByAddress; /* * Returns whether the proposal has been closed. */ bool public isClosed; /* * The offer that has been accepted. */ Offer public acceptedOffer; address public owner; function Proposal(string pn, string mc, string sc, uint mp, string ed, string udd) { productName = pn; mainCategory = mc; subCategory = sc; maxPrice = mp; endDate = ed; ultimateDeliveryDate = udd; owner = tx.origin; registry = ProposalRegistry(msg.sender); } function setDetails(string pd, string ps, string pus) { // Only to be called by the proposal owner. if(tx.origin != owner) return; productDescription = pd; productSku = ps; productUnitSize = pus; } // Payment schedule, currently fixed. uint public pledgePaymentPercentage = 5; uint public startPaymentPercentage = 45; // End payment percentage: there's no such thing. The end payment is the rest. // In case of an offer below pledge + start, it can even be a reimbursement. function getBestPrice() constant returns (uint price) { uint bestOfferIndex = getBestOfferIndex(); // Is there a best offer? if(bestOfferIndex == 0) return; price = offers[bestOfferIndex].price(); } function getPledgePaymentAmount(uint backerIndex) constant returns (uint amount) { amount = backers[backerIndex].amount * pledgePaymentPercentage * maxPrice / 100; // For very low prices: force a very low amount. Settled in end payment. if (amount == 0) amount = 1; } function getStartPaymentAmount(uint backerIndex) constant returns (uint amount) { amount = backers[backerIndex].amount * startPaymentPercentage * maxPrice / 100; // For very low prices: force a very low amount. Settled in end payment. if (amount == 0) amount = 1; } function getEndPaymentAmount(uint backerIndex) constant returns (int amount) { // The end payment amount is "the rest". // In case of an offer below pledge + start, it can even be a reimbursement, hence // a negative amount. // We can only compute this once there is an accepted offer. However when // there is none, the end payment will be minus the currently paid amount, // hence a full reimbursement. amount = (int(backers[backerIndex].amount) * int(acceptedOffer.price())) // Total amount to be paid // Minus the amount already paid by this backer. We use the // actually registered amounts to handle any cases where e.g. // a single backer hasn't paid the start payment. - int(backers[backerIndex].pledgePaymentAmount) - int(backers[backerIndex].startPaymentAmount); } /* * Back the proposal, i.e. pledge to buy a certain amount. */ function back(uint am, string cardId) { if(am == 0) return; // No backing after closing. if(isClosed) return; // No checks on multiple backings per buyer. Buyers can buy more later (not less). backerIndex++; backers[backerIndex].amount = am; backers[backerIndex].buyerAddress = tx.origin; backers[backerIndex].cardId = cardId; } /* * Register a payment for a backer. To be called by the registry owner. The * call should only be made after the payment has been verified as having * the correct amount, source and destination. * * @param backerIndex the backer index * @param paymentType 1=pledge, 2=start, 3=end * @param transactionID the external transaction ID of the payment * @param amount the payment amount */ function setPaid(uint backerIndex, uint paymentType, string transactionID, int amount) { // The registry owner is the trusted party to confirm payments. if(tx.origin != registry.owner()) return; // Validate this is an existing backer. // Ideally we would want to verify this from the original backer address. // The backer could send a transaction claiming they paid a certain backing // (checking the address), and then the registry administrator can confirm // this, also checking that the tx ID corresponds to a tx of the right amount // that has been sent to the right address. // So then this would be split into: // - claimPaid(uint backerIndex, uint paymentType, string transactionID, int amount) // -> to be called by the backer // - confirmPaid(uint backerIndex, uint paymentType, string transactionID, int amount) // -> to be called by the registry admin. Or in future cases, by a set of oracles. // - or denyPaid(uint backerIndex, uint paymentType), to be called by the admin/oracles, // leading to a reversion. Could also be used to correct incorrect calls. if(backerIndex == 0) return; Backing b = backers[backerIndex]; if (paymentType == 1) { // Pledge payment // Can only register once if(b.pledgePaymentAmount != 0) return; // Validate correct amount if(amount != int(getPledgePaymentAmount(backerIndex))) return; b.pledgePaymentTransactionID = transactionID; b.pledgePaymentAmount = uint(amount); } else if (paymentType == 2) { // Start payment // Validate that the BuyCo was closed if(!isClosed) return; // Can only register once if(b.startPaymentAmount != 0) return; // There should be an accepted offer. If not, the pledge payments // should be refunded. if(address(acceptedOffer) == 0x0) return; // Validate pledge payment if(b.pledgePaymentAmount == 0) return; if(amount != int(getStartPaymentAmount(backerIndex))) return; b.startPaymentTransactionID = transactionID; b.startPaymentAmount = uint(amount); } else if (paymentType == 3) { // End payment // Validate that start payment was registered if(b.startPaymentAmount == 0) return; // Can only register once if(b.endPaymentAmount != 0) return; // Validate correct amount if(amount != getEndPaymentAmount(backerIndex)) return; b.endPaymentTransactionID = transactionID; b.endPaymentAmount = amount; } } /* * Make an offer */ function offer(uint price, uint minimumAmount, string cardId) returns (Offer o){ // No free offers allowed. Also for safety purposes (empty might end up as 0). if(price == 0) return; if(price > maxPrice) return; if(minimumAmount == 0) return; if(isClosed) return; // Check for an existing offer of this seller if(offerIndexByAddress[tx.origin] > 0) { // Because this is a related contract, we can't set public properties. // TODO: check if there are default setters, maybe set_price() or similar? offers[offerIndexByAddress[tx.origin]].setPrice(price); offers[offerIndexByAddress[tx.origin]].setMinimumAmount(minimumAmount); offers[offerIndexByAddress[tx.origin]].setCardId(cardId); return; } offerIndex++; offerIndexByAddress[tx.origin] = offerIndex; o = new Offer(price, minimumAmount, cardId); offers[offerIndex] = o; return o; } /* * Cancel the offer of a seller if the proposal is still open. */ function cancelOffer(){ // TODO } function getTotalBackedAmount() constant returns (uint amount){ for (uint i = 1; i <= backerIndex; i++) { var b = backers[i]; // Only count backers that have paid the pledge payment. if(b.pledgePaymentAmount == 0) continue; amount += b.amount; } return amount; } function getBestOfferIndex() constant returns (uint bestOfferIndex) { uint totalBackedAmount = getTotalBackedAmount(); uint lowestPrice = maxPrice; // Find the matching offer with the best price. for (uint i = 1; i <= offerIndex; i++) { var o = offers[i]; if (o.price() <= lowestPrice && o.minimumAmount() <= totalBackedAmount) { // This is a better offer than previously found. bestOfferIndex = i; } } } /* * Attempt to close the proposal if the closing conditions are met: * - the end date has been reached (this can not be checked yet) * - a valid offer has been made */ function close() { // To be called by the registry owner. if(tx.origin != registry.owner()) return; // Checking whether the end time is the responsibility of the registry // owner. We currently have no way to deal with time within the contract. // The proposal gets closed no matter whether there's a valid offer or // not. // Get the best offer. uint bestOfferIndex = getBestOfferIndex(); // Did we find a valid offer? if (bestOfferIndex > 0) { acceptedOffer = offers[bestOfferIndex]; } isClosed = true; } /* * Returns whether all the start (and pledge) payments have been received * from the backers. */ function isStartPaymentComplete() constant public returns (bool isComplete) { // No backers? Then not complete. if(getTotalBackedAmount() == 0) return; for (uint i = 1; i <= backerIndex; i++) { // Only consider real backers. if(backers[i].pledgePaymentAmount == 0) continue; if(backers[i].startPaymentAmount == 0) return; } isComplete = true; } /* * Returns whether all the payments have been received from the backers. */ function isPaymentComplete() constant public returns (bool isComplete) { // Start payment not complete? Then end payment surely not complete. if(!isStartPaymentComplete()) return; for (uint i = 1; i <= backerIndex; i++) { // Only consider real backers. if(backers[i].pledgePaymentAmount == 0) continue; if(backers[i].endPaymentAmount == 0) return; } isComplete = true; } /* * Report on the delivery of the goods. To be called by the backer. */ function reportDelivery(uint backerIndex, bool isCorrect) { Backing b = backers[backerIndex]; // There has to be an accepted offer to report any delivery. if(address(acceptedOffer) == 0x0) return; // To be called by the backer. if(b.buyerAddress != tx.origin) return; // Is it a real backer? if(b.pledgePaymentAmount == 0) return; // A delivery reported as correct cannot be unreported. if(b.isDeliveryReported && b.isDeliveryCorrect) return; b.isDeliveryReported = true; b.isDeliveryCorrect = isCorrect; } /* * The minimum percentage of deliveries reported as correct (calculated by * product count) to consider the delivery complete and ready for final * payout. In future versions this could be a parameter of the proposal. */ uint public minimumReportedCorrectDeliveryPercentage = 50; function getMinimumCorrectDeliveryCount() constant returns (uint count) { count = minimumReportedCorrectDeliveryPercentage * getTotalBackedAmount() / 100; } /* * Returns the total count of products that have been reported as correctly * delivered. */ function getCorrectDeliveryCount() constant returns (uint count) { for (uint i = 1; i <= backerIndex; i++) { if(backers[i].isDeliveryCorrect) count += backers[i].amount; } } /* * Returns whether delivery is complete according to the agreed upon * treshold. */ function isDeliveryComplete() constant returns (bool isComplete) { isComplete = getCorrectDeliveryCount() >= getMinimumCorrectDeliveryCount(); } // Payments to the seller uint public startPayoutAmount; string public startPayoutTransactionID; uint public endPayoutAmount; string public endPayoutTransactionID; /* * Returns whether the start payout to the seller may be done. */ function isReadyForStartPayout() constant returns (bool isReady) { isReady = isClosed && isStartPaymentComplete(); } /* * Returns whether the start payout to the seller may be done. */ function isReadyForEndPayout() constant returns (bool isReady) { isReady = isClosed && isPaymentComplete() && isDeliveryComplete() // Start payout has to be done before end payout. && startPayoutAmount != 0; } function getStartPayoutAmount() constant returns (uint amount) { amount = acceptedOffer.price() * getTotalBackedAmount() * (pledgePaymentPercentage + startPaymentPercentage) / 100; } function getEndPayoutAmount() constant returns (uint amount) { // TODO: Handle refunds. If the ultimateDeliveryDate has passed, there // can be two situations: // 1. isDeliveryComplete == true: end payment should be made to seller // 2. isDeliveryComplete == false: end payout should be negative (refund) // and end payment to backers should be negative (refund). // Currently refunds are not supported; any BuyCo is assumed to be // successfully fulfilled within the ultimateDeliveryDate. amount = acceptedOffer.price() * getTotalBackedAmount() - getStartPayoutAmount(); } /* * Confirm that the start payout sum has been paid to the accepted seller. */ function registerStartPayout(string txId, uint amount) { // Payments are confirmed by the registry owner. if(tx.origin != registry.owner()) return; // Can only register once if(startPayoutAmount != 0) return; if(!isReadyForStartPayout()) return; if(amount != getStartPayoutAmount()) return; startPayoutAmount = amount; startPayoutTransactionID = txId; } /* * Confirm thath the end payout sum has been paid to the accepted seller. */ function registerEndPayout(string txId, uint amount) { // Payments are confirmed by the registry owner. if(tx.origin != registry.owner()) return; // Can only register once if(endPayoutAmount != 0) return; if(!isReadyForEndPayout()) return; if(amount != getEndPayoutAmount()) return; endPayoutAmount = amount; endPayoutTransactionID = txId; } /**************** START STATISTICS **************/ /* * Gets the total amount deposited by backers. */ function getTotalPaymentAmount() constant returns (uint amount) { int computedAmount; for (uint i = 1; i <= backerIndex; i++) { var b = backers[i]; computedAmount += int(b.pledgePaymentAmount); computedAmount += int(b.startPaymentAmount); computedAmount += b.endPaymentAmount; } amount = uint(computedAmount); } /** * Gets the total amount paid out to the seller. */ function getTotalPayoutAmount() constant returns (uint amount) { amount = startPayoutAmount + endPayoutAmount; } /** * Gets the total amount currently held in escrow. */ function getTotalEscrowAmount() constant returns (uint amount) { return getTotalPaymentAmount() - getTotalPayoutAmount(); } /**************** END STATISTICS **************/ } /* * Central registry for buyng proposals. This contract is deployed once. The * contract instance corresponds to one BuyCo service. */ contract ProposalRegistry { /* * Name of the registry, e.g. "BuyCo" */ string public name; /* * The owner of the registry, e.g. BuyCo Ltd */ address public owner; /* * Version of the regstriy for simple version checking. The code is currently * compatible with only a single version of the contracts. After any change, * this number should be increased. The code compares it with a variable in * contractInterfaces. */ string public version = "0.8.6"; function ProposalRegistry(string n){ name = n; owner = tx.origin; } /* * All current and historical proposals. */ mapping (uint=>Proposal) public proposals; uint public proposalIndex; function addProposal(string productName, string productCategory, string productSubCategory, uint maxPrice, string endDate, string ultimateDeliveryDate) returns (Proposal p) { proposalIndex++; p = new Proposal(productName, productCategory, productSubCategory, maxPrice, endDate, ultimateDeliveryDate); proposals[proposalIndex] = p; return p; } }
Is there a best offer?
function getBestPrice() constant returns (uint price) { uint bestOfferIndex = getBestOfferIndex(); if(bestOfferIndex == 0) return; price = offers[bestOfferIndex].price(); }
14,070,251
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: @openzeppelin/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } // File: contracts/NasiToken.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; contract NasiToken is Ownable, ERC20Detailed('NasiToken', 'NAS', 18), ERC20Pausable, ERC20Burnable, ERC20Mintable { function mint(address _to, uint256 _amount) public onlyMinter returns (bool) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); return true; } mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "NASI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "NASI::delegateBySig: invalid nonce"); require(now <= expiry, "NASI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "NASI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NASIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "NASI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/NasiLiquidityPoolFactory.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; interface IMigrator { /** * Perform LP token migration from legacy UniswapV2 to NasiSwap. * Take the current LP token address and return the new LP token address. * Migrator should have full access to the caller's LP token. * XXX Migrator must have allowance access to UniswapV2 LP tokens. * NasiSwap must mint EXACTLY the same amount of NasiSwap LP tokens or * else something bad will happen. Traditional UniswapV2 does not * do that so be careful! */ function migrate(address token) external returns (address); } contract NasiLiquidityPoolFactory is Ownable { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @param amountOfLpToken * @param rewardDebt */ struct UserInfo { uint256 amountOfLpToken; uint256 rewardDebt; } struct PoolInfo { address lpTokenAddress; uint256 allocationPoint; uint256 lastRewardBlock; uint256 accumulatedNasiPerShare; } NasiToken public nasiToken; uint256 public nasiPerBlock; uint256 public endBlock; uint256 public endBlockWeek1; uint256 public endBlockWeek2; uint256 public endBlockWeek3; uint256 public endBlockWeek4; uint256 public poolCounter; address public migrator; address public devaddr; mapping (uint256 => PoolInfo) public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocationPoint; uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _nasiAddress, address _devaddr, uint256 _nasiPerBlock, uint256 _startBlock ) public { nasiToken = NasiToken(_nasiAddress); devaddr = _devaddr; nasiPerBlock = _nasiPerBlock; startBlock = _startBlock; endBlockWeek1 = _startBlock.add(45500); endBlockWeek2 = endBlockWeek1.add(45500); endBlockWeek3 = endBlockWeek2.add(45500); endBlockWeek4 = endBlockWeek3.add(45500); endBlock = _startBlock.add(1137500); } /** * @notice Set the migrator contract. Can only be called by the owner. */ function setMigrator(address _migrator) public onlyOwner { require(_migrator != address(0), 'Migrator can not equal address0'); migrator = _migrator; } /** * @notice Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. */ function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = IERC20(pool.lpTokenAddress); uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); address newLpToken = IMigrator(migrator).migrate(pool.lpTokenAddress); require(bal == IERC20(newLpToken).balanceOf(address(this)), "migrate: bad"); pool.lpTokenAddress = newLpToken; } /** * @notice Deposit LP tokens to Factory for nasi allocation. */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid <= poolCounter, 'Invalid pool id!'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amountOfLpToken > 0) { uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); if(pending > 0) { _safeNasiTransfer(msg.sender, pending); } } IERC20(pool.lpTokenAddress).safeTransferFrom(address(msg.sender), address(this), _amount); user.amountOfLpToken = user.amountOfLpToken.add(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); emit Deposit(msg.sender, _pid, _amount); } /** * @notice Add a new lp to the pool. Can only be called by the owner. */ function addLpToken(uint256 _allocationPoint, address _lpTokenAddress, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } poolCounter++; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocationPoint = totalAllocationPoint.add(_allocationPoint); poolInfo[poolCounter] = PoolInfo( _lpTokenAddress, _allocationPoint, lastRewardBlock, 0 ); } function massUpdatePools() public { for (uint256 _pid = 1; _pid <= poolCounter; _pid++) { updatePool(_pid); } } /** * @notice Update reward variables of the given pool to be up-to-date. */ function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplier.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); nasiToken.mint(address(this), nasiReward); nasiToken.mint(devaddr, nasiReward.div(50)); pool.accumulatedNasiPerShare = pool.accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Get the bonus multiply ratio at the initial time. */ function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0; uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0; uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0; uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0; uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0; return week1.add(week2).add(week3).add(week4).add(end); } function pendingNasi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accumulatedNasiPerShare = pool.accumulatedNasiPerShare; uint256 lpSupply = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { return 0; } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplierBonus = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplierBonus.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); accumulatedNasiPerShare = accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); } return (user.amountOfLpToken.mul(accumulatedNasiPerShare).sub(user.rewardDebt).div(1e12)); } /** * @notice Withdraw LP tokens from Factory */ function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amountOfLpToken >= _amount, "Not enough funds!"); updatePool(_pid); uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); _safeNasiTransfer(msg.sender, pending); user.amountOfLpToken = user.amountOfLpToken.sub(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amountOfLpToken; user.amountOfLpToken = 0; user.rewardDebt = 0; IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the given pool's NASI allocation point. Can only be called by the owner. function setAllocationPoint(uint256 _pid, uint256 _allocationPoint, bool _withUpdate) public onlyOwner { require(_pid <= poolCounter, 'Invalid pool id!'); if (_withUpdate) { massUpdatePools(); } totalAllocationPoint = totalAllocationPoint.sub(poolInfo[_pid].allocationPoint).add(_allocationPoint); poolInfo[_pid].allocationPoint = _allocationPoint; } function _safeNasiTransfer(address _to, uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.transfer(_to, nasiBalance); } else { nasiToken.transfer(_to, _amount); } } function _safeNasiBurn(uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.burn(nasiBalance); } else { nasiToken.burn(_amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Add a new lp to the pool. Can only be called by the owner./
function addLpToken(uint256 _allocationPoint, address _lpTokenAddress, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } poolCounter++; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocationPoint = totalAllocationPoint.add(_allocationPoint); poolInfo[poolCounter] = PoolInfo( _lpTokenAddress, _allocationPoint, lastRewardBlock, 0 ); }
55,006
./full_match/80001/0xD4b7bd77B3a04c4000387dBF711040f23C31Ef4b/sources/contracts/ERC721A.sol
Gas spent here starts off proportional to the maximum mint batch size. It gradually moves to O(1) as tokens get transferred around in the collection over time./ unchecked {
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; }
5,568,948
pragma solidity ^0.5.2; /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice 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 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 SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * Phat Cats - Crypto-Cards * - https://crypto-cards.io * - https://phatcats.co * * Copyright 2019 (c) Phat Cats, Inc. */ /** * @title Crypto-Cards Payroll */ contract CryptoCardsPayroll is Ownable, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event PayeeUpdated(address account, uint256 sharesAdded, uint256 totalShares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; uint256 private _totalReleasedAllTime; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Constructor */ constructor () public {} /** * @dev payable fallback */ function () external payable { emit PaymentReceived(msg.sender, msg.value); } /** * @return the total shares of the contract. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @return the total amount already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @return the total amount already released. */ function totalReleasedAllTime() public view returns (uint256) { return _totalReleasedAllTime; } /** * @return the total amount of funds in the contract. */ function totalFunds() public view returns (uint256) { return address(this).balance; } /** * @return the shares of an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @return the shares of an account. */ function sharePercentage(address account) public view returns (uint256) { if (_totalShares == 0 || _shares[account] == 0) { return 0; } return _shares[account].mul(100).div(_totalShares); } /** * @return the amount already released to an account. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @return the amount available for release to an account. */ function available(address account) public view returns (uint256) { uint256 totalReceived = address(this).balance.add(_totalReleased); uint256 totalCut = totalReceived.mul(_shares[account]).div(_totalShares); if (block.number < _released[account]) { return 0; } //injected CONTRACT AFFECTED BY MINERS return totalCut.sub(_released[account]); } /** * @return the address of a payee. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Release payee's proportional payment. */ function release() external nonReentrant { address payable account = address(uint160(msg.sender)); require(_shares[account] > 0, "Account not eligible for payroll"); uint256 payment = available(account); require(payment != 0, "No payment available for account"); _release(account, payment); } /** * @dev Release payment for all payees and reset state */ function releaseAll() public onlyOwner { _releaseAll(); _resetAll(); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function addNewPayee(address account, uint256 shares_) public onlyOwner { require(account != address(0), "Invalid account"); require(Address.isContract(account) == false, "Account cannot be a contract"); require(shares_ > 0, "Shares must be greater than zero"); require(_shares[account] == 0, "Payee already exists"); require(_totalReleased == 0, "Must release all existing payments first"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.add(shares_); emit PayeeAdded(account, shares_); } /** * @dev Increase he shares of an existing payee * @param account The address of the payee to increase. * @param shares_ The number of shares to add to the payee. */ function increasePayeeShares(address account, uint256 shares_) public onlyOwner { require(account != address(0), "Invalid account"); require(shares_ > 0, "Shares must be greater than zero"); require(_shares[account] > 0, "Payee does not exist"); require(_totalReleased == 0, "Must release all existing payments first"); _shares[account] = _shares[account].add(shares_); _totalShares = _totalShares.add(shares_); emit PayeeUpdated(account, shares_, _shares[account]); } /** * @dev Release one of the payee's proportional payment. * @param account Whose payments will be released. */ function _release(address payable account, uint256 payment) private { _released[account] = _released[account].add(payment); _totalReleased = _totalReleased.add(payment); _totalReleasedAllTime = _totalReleasedAllTime.add(payment); account.transfer(payment); emit PaymentReleased(account, payment); } /** * @dev Release payment for all payees */ function _releaseAll() private { for (uint256 i = 0; i < _payees.length; i++) { _release(address(uint160(_payees[i])), available(_payees[i])); } } /** * @dev Reset state of released payments for all payees */ function _resetAll() private { for (uint256 i = 0; i < _payees.length; i++) { _released[_payees[i]] = 0; } _totalReleased = 0; } }
Release payee's proportional payment./
function release() external nonReentrant { address payable account = address(uint160(msg.sender)); require(_shares[account] > 0, "Account not eligible for payroll"); uint256 payment = available(account); require(payment != 0, "No payment available for account"); _release(account, payment); }
14,066,571
./full_match/80001/0x5d48686cDA92F10a93b421E2498CfC1EC2eF1843/sources/contracts/BourbonNBlockchainRewards.sol
Function allowing super-admin to unpause reward claiming for all users/
function unpauseRewards() public onlyRole(DEFAULT_ADMIN_ROLE) { rewardsPaused = false; }
5,598,942
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/SafeMath.sol
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; unchecked { c = a + b; } require(c >= a, "SafeMath: addition overflow"); return c; }
2,594,754
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../utils/SafeDecimalMath.sol"; import {Order, OrderQueue, LibOrderQueue} from "./LibOrderQueue.sol"; import { UnsettledBuyTrade, UnsettledSellTrade, UnsettledTrade, LibUnsettledBuyTrade, LibUnsettledSellTrade } from "./LibUnsettledTrade.sol"; import "./ExchangeRoles.sol"; import "./Staking.sol"; /// @title Tranchess's Exchange Contract /// @notice A decentralized exchange to match premium-discount orders and clear trades /// @author Tranchess contract Exchange is ExchangeRoles, Staking { /// @dev Reserved storage slots for future base contract upgrades uint256[32] private _reservedSlots; using SafeDecimalMath for uint256; using LibOrderQueue for OrderQueue; using SafeERC20 for IERC20; using LibUnsettledBuyTrade for UnsettledBuyTrade; using LibUnsettledSellTrade for UnsettledSellTrade; /// @notice A maker bid order is placed. /// @param maker Account placing the order /// @param tranche Tranche of the share to buy /// @param pdLevel Premium-discount level /// @param quoteAmount Amount of quote asset in the order, rounding precision to 18 /// for quote assets with precision other than 18 decimal places /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue event BidOrderPlaced( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version, uint256 orderIndex ); /// @notice A maker ask order is placed. /// @param maker Account placing the order /// @param tranche Tranche of the share to sell /// @param pdLevel Premium-discount level /// @param baseAmount Amount of base asset in the order /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue event AskOrderPlaced( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 baseAmount, uint256 version, uint256 orderIndex ); /// @notice A maker bid order is canceled. /// @param maker Account placing the order /// @param tranche Tranche of the share /// @param pdLevel Premium-discount level /// @param quoteAmount Original amount of quote asset in the order, rounding precision to 18 /// for quote assets with precision other than 18 decimal places /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue /// @param fillable Unfilled amount when the order is canceled, rounding precision to 18 for /// quote assets with precision other than 18 decimal places event BidOrderCanceled( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version, uint256 orderIndex, uint256 fillable ); /// @notice A maker ask order is canceled. /// @param maker Account placing the order /// @param tranche Tranche of the share to sell /// @param pdLevel Premium-discount level /// @param baseAmount Original amount of base asset in the order /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue /// @param fillable Unfilled amount when the order is canceled event AskOrderCanceled( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 baseAmount, uint256 version, uint256 orderIndex, uint256 fillable ); /// @notice Matching result of a taker bid order. /// @param taker Account placing the order /// @param tranche Tranche of the share /// @param quoteAmount Matched amount of quote asset, rounding precision to 18 for quote assets /// with precision other than 18 decimal places /// @param version Rebalance version of this trade /// @param lastMatchedPDLevel Premium-discount level of the last matched maker order /// @param lastMatchedOrderIndex Index of the last matched maker order in its order queue /// @param lastMatchedBaseAmount Matched base asset amount of the last matched maker order event BuyTrade( address indexed taker, uint256 indexed tranche, uint256 quoteAmount, uint256 version, uint256 lastMatchedPDLevel, uint256 lastMatchedOrderIndex, uint256 lastMatchedBaseAmount ); /// @notice Matching result of a taker ask order. /// @param taker Account placing the order /// @param tranche Tranche of the share /// @param baseAmount Matched amount of base asset /// @param version Rebalance version of this trade /// @param lastMatchedPDLevel Premium-discount level of the last matched maker order /// @param lastMatchedOrderIndex Index of the last matched maker order in its order queue /// @param lastMatchedQuoteAmount Matched quote asset amount of the last matched maker order, /// rounding precision to 18 for quote assets with precision /// other than 18 decimal places event SellTrade( address indexed taker, uint256 indexed tranche, uint256 baseAmount, uint256 version, uint256 lastMatchedPDLevel, uint256 lastMatchedOrderIndex, uint256 lastMatchedQuoteAmount ); /// @notice Settlement of unsettled trades of maker orders. /// @param account Account placing the related maker orders /// @param epoch Epoch of the settled trades /// @param amountM Amount of Token M added to the account's available balance /// @param amountA Amount of Token A added to the account's available balance /// @param amountB Amount of Token B added to the account's available balance /// @param quoteAmount Amount of quote asset transfered to the account, rounding precision to 18 /// for quote assets with precision other than 18 decimal places event MakerSettled( address indexed account, uint256 epoch, uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ); /// @notice Settlement of unsettled trades of taker orders. /// @param account Account placing the related taker orders /// @param epoch Epoch of the settled trades /// @param amountM Amount of Token M added to the account's available balance /// @param amountA Amount of Token A added to the account's available balance /// @param amountB Amount of Token B added to the account's available balance /// @param quoteAmount Amount of quote asset transfered to the account, rounding precision to 18 /// for quote assets with precision other than 18 decimal places event TakerSettled( address indexed account, uint256 epoch, uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ); uint256 private constant EPOCH = 30 minutes; // An exchange epoch is 30 minutes long /// @dev Maker reserves 110% of the asset they want to trade, which would stop /// losses for makers when the net asset values turn out volatile uint256 private constant MAKER_RESERVE_RATIO = 1.1e18; /// @dev Premium-discount level ranges from -10% to 10% with 0.25% as step size uint256 private constant PD_TICK = 0.0025e18; uint256 private constant MIN_PD = 0.9e18; uint256 private constant MAX_PD = 1.1e18; uint256 private constant PD_START = MIN_PD - PD_TICK; uint256 private constant PD_LEVEL_COUNT = (MAX_PD - MIN_PD) / PD_TICK + 1; /// @notice Minumum quote amount of maker bid orders with 18 decimal places uint256 public immutable minBidAmount; /// @notice Minumum base amount of maker ask orders uint256 public immutable minAskAmount; /// @notice Minumum base or quote amount of maker orders during guarded launch uint256 public immutable guardedLaunchMinOrderAmount; /// @dev A multipler that normalizes a quote asset balance to 18 decimal places. uint256 private immutable _quoteDecimalMultiplier; /// @notice Mapping of rebalance version => tranche => an array of order queues mapping(uint256 => mapping(uint256 => OrderQueue[PD_LEVEL_COUNT + 1])) public bids; mapping(uint256 => mapping(uint256 => OrderQueue[PD_LEVEL_COUNT + 1])) public asks; /// @notice Mapping of rebalance version => best bid premium-discount level of the three tranches. /// Zero indicates that there is no bid order. mapping(uint256 => uint256[TRANCHE_COUNT]) public bestBids; /// @notice Mapping of rebalance version => best ask premium-discount level of the three tranches. /// Zero or `PD_LEVEL_COUNT + 1` indicates that there is no ask order. mapping(uint256 => uint256[TRANCHE_COUNT]) public bestAsks; /// @notice Mapping of account => tranche => epoch => unsettled trade mapping(address => mapping(uint256 => mapping(uint256 => UnsettledTrade))) public unsettledTrades; /// @dev Mapping of epoch => rebalance version mapping(uint256 => uint256) private _epochVersions; constructor( address fund_, address chessSchedule_, address chessController_, address quoteAssetAddress_, uint256 quoteDecimals_, address votingEscrow_, uint256 minBidAmount_, uint256 minAskAmount_, uint256 makerRequirement_, uint256 guardedLaunchStart_, uint256 guardedLaunchMinOrderAmount_ ) public ExchangeRoles(votingEscrow_, makerRequirement_) Staking(fund_, chessSchedule_, chessController_, quoteAssetAddress_, guardedLaunchStart_) { minBidAmount = minBidAmount_; minAskAmount = minAskAmount_; guardedLaunchMinOrderAmount = guardedLaunchMinOrderAmount_; require(quoteDecimals_ <= 18, "Quote asset decimals larger than 18"); _quoteDecimalMultiplier = 10**(18 - quoteDecimals_); } /// @notice Return end timestamp of the epoch containing a given timestamp. /// @param timestamp Timestamp within a given epoch /// @return The closest ending timestamp function endOfEpoch(uint256 timestamp) public pure returns (uint256) { return (timestamp / EPOCH) * EPOCH + EPOCH; } function getBidOrder( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external view returns ( address maker, uint256 amount, uint256 fillable ) { Order storage order = bids[version][tranche][pdLevel].list[index]; maker = order.maker; amount = order.amount; fillable = order.fillable; } function getAskOrder( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external view returns ( address maker, uint256 amount, uint256 fillable ) { Order storage order = asks[version][tranche][pdLevel].list[index]; maker = order.maker; amount = order.amount; fillable = order.fillable; } /// @notice Get all tranches' net asset values of a given time /// @param timestamp Timestamp of the net asset value /// @return estimatedNavM Token M's net asset value /// @return estimatedNavA Token A's net asset value /// @return estimatedNavB Token B's net asset value function estimateNavs(uint256 timestamp) public view returns ( uint256, uint256, uint256 ) { uint256 price = fund.twapOracle().getTwap(timestamp); require(price != 0, "Price is not available"); return fund.extrapolateNav(timestamp, price); } /// @notice Place a bid order for makers /// @param tranche Tranche of the base asset /// @param pdLevel Premium-discount level /// @param quoteAmount Quote asset amount with 18 decimal places /// @param version Current rebalance version. Revert if it is not the latest version. function placeBid( uint256 tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version ) external onlyMaker { require(block.timestamp >= guardedLaunchStart + 8 days, "Guarded launch: market closed"); if (block.timestamp < guardedLaunchStart + 4 weeks) { require(quoteAmount >= guardedLaunchMinOrderAmount, "Guarded launch: amount too low"); } else { require(quoteAmount >= minBidAmount, "Quote amount too low"); } uint256 bestAsk = bestAsks[version][tranche]; require( pdLevel > 0 && pdLevel < (bestAsk == 0 ? PD_LEVEL_COUNT + 1 : bestAsk), "Invalid premium-discount level" ); require(version == fund.getRebalanceSize(), "Invalid version"); _transferQuoteFrom(msg.sender, quoteAmount); uint256 index = bids[version][tranche][pdLevel].append(msg.sender, quoteAmount, version); if (bestBids[version][tranche] < pdLevel) { bestBids[version][tranche] = pdLevel; } emit BidOrderPlaced(msg.sender, tranche, pdLevel, quoteAmount, version, index); } /// @notice Place an ask order for makers /// @param tranche Tranche of the base asset /// @param pdLevel Premium-discount level /// @param baseAmount Base asset amount /// @param version Current rebalance version. Revert if it is not the latest version. function placeAsk( uint256 tranche, uint256 pdLevel, uint256 baseAmount, uint256 version ) external onlyMaker { require(block.timestamp >= guardedLaunchStart + 8 days, "Guarded launch: market closed"); if (block.timestamp < guardedLaunchStart + 4 weeks) { require(baseAmount >= guardedLaunchMinOrderAmount, "Guarded launch: amount too low"); } else { require(baseAmount >= minAskAmount, "Base amount too low"); } require( pdLevel > bestBids[version][tranche] && pdLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level" ); require(version == fund.getRebalanceSize(), "Invalid version"); _lock(tranche, msg.sender, baseAmount); uint256 index = asks[version][tranche][pdLevel].append(msg.sender, baseAmount, version); uint256 oldBestAsk = bestAsks[version][tranche]; if (oldBestAsk > pdLevel || oldBestAsk == 0) { bestAsks[version][tranche] = pdLevel; } emit AskOrderPlaced(msg.sender, tranche, pdLevel, baseAmount, version, index); } /// @notice Cancel a bid order /// @param version Order's rebalance version /// @param tranche Tranche of the order's base asset /// @param pdLevel Order's premium-discount level /// @param index Order's index in the order queue function cancelBid( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external { OrderQueue storage orderQueue = bids[version][tranche][pdLevel]; Order storage order = orderQueue.list[index]; require(order.maker == msg.sender, "Maker address mismatched"); uint256 fillable = order.fillable; emit BidOrderCanceled(msg.sender, tranche, pdLevel, order.amount, version, index, fillable); orderQueue.cancel(index); // Update bestBid if (bestBids[version][tranche] == pdLevel) { uint256 newBestBid = pdLevel; while (newBestBid > 0 && bids[version][tranche][newBestBid].isEmpty()) { newBestBid--; } bestBids[version][tranche] = newBestBid; } _transferQuote(msg.sender, fillable); } /// @notice Cancel an ask order /// @param version Order's rebalance version /// @param tranche Tranche of the order's base asset /// @param pdLevel Order's premium-discount level /// @param index Order's index in the order queue function cancelAsk( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external { OrderQueue storage orderQueue = asks[version][tranche][pdLevel]; Order storage order = orderQueue.list[index]; require(order.maker == msg.sender, "Maker address mismatched"); uint256 fillable = order.fillable; emit AskOrderCanceled(msg.sender, tranche, pdLevel, order.amount, version, index, fillable); orderQueue.cancel(index); // Update bestAsk if (bestAsks[version][tranche] == pdLevel) { uint256 newBestAsk = pdLevel; while (newBestAsk <= PD_LEVEL_COUNT && asks[version][tranche][newBestAsk].isEmpty()) { newBestAsk++; } bestAsks[version][tranche] = newBestAsk; } if (tranche == TRANCHE_M) { _rebalanceAndUnlock(msg.sender, fillable, 0, 0, version); } else if (tranche == TRANCHE_A) { _rebalanceAndUnlock(msg.sender, 0, fillable, 0, version); } else { _rebalanceAndUnlock(msg.sender, 0, 0, fillable, version); } } /// @notice Buy Token M /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyM( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (uint256 estimatedNav, , ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_M, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Buy Token A /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyA( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (, uint256 estimatedNav, ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_A, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Buy Token B /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyB( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (, , uint256 estimatedNav) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_B, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Sell Token M /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token M willing to trade function sellM( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (uint256 estimatedNav, , ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_M, minPDLevel, estimatedNav, baseAmount); } /// @notice Sell Token A /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token A willing to trade function sellA( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (, uint256 estimatedNav, ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_A, minPDLevel, estimatedNav, baseAmount); } /// @notice Sell Token B /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token B willing to trade function sellB( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (, , uint256 estimatedNav) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_B, minPDLevel, estimatedNav, baseAmount); } /// @notice Settle trades of a specified epoch for makers /// @param account Address of the maker /// @param epoch A specified epoch's end timestamp /// @return amountM Token M amount added to msg.sender's available balance /// @return amountA Token A amount added to msg.sender's available balance /// @return amountB Token B amount added to msg.sender's available balance /// @return quoteAmount Quote asset amount transfered to msg.sender, rounding precison to 18 /// for quote assets with precision other than 18 decimal places function settleMaker(address account, uint256 epoch) external returns ( uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ) { (uint256 estimatedNavM, uint256 estimatedNavA, uint256 estimatedNavB) = estimateNavs(epoch.add(EPOCH)); uint256 quoteAmountM; uint256 quoteAmountA; uint256 quoteAmountB; (amountM, quoteAmountM) = _settleMaker(account, TRANCHE_M, estimatedNavM, epoch); (amountA, quoteAmountA) = _settleMaker(account, TRANCHE_A, estimatedNavA, epoch); (amountB, quoteAmountB) = _settleMaker(account, TRANCHE_B, estimatedNavB, epoch); uint256 version = _epochVersions[epoch]; (amountM, amountA, amountB) = _rebalanceAndClearTrade( account, amountM, amountA, amountB, version ); quoteAmount = quoteAmountM.add(quoteAmountA).add(quoteAmountB); _transferQuote(account, quoteAmount); emit MakerSettled(account, epoch, amountM, amountA, amountB, quoteAmount); } /// @notice Settle trades of a specified epoch for takers /// @param account Address of the maker /// @param epoch A specified epoch's end timestamp /// @return amountM Token M amount added to msg.sender's available balance /// @return amountA Token A amount added to msg.sender's available balance /// @return amountB Token B amount added to msg.sender's available balance /// @return quoteAmount Quote asset amount transfered to msg.sender, rounding precison to 18 /// for quote assets with precision other than 18 decimal places function settleTaker(address account, uint256 epoch) external returns ( uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ) { (uint256 estimatedNavM, uint256 estimatedNavA, uint256 estimatedNavB) = estimateNavs(epoch.add(EPOCH)); uint256 quoteAmountM; uint256 quoteAmountA; uint256 quoteAmountB; (amountM, quoteAmountM) = _settleTaker(account, TRANCHE_M, estimatedNavM, epoch); (amountA, quoteAmountA) = _settleTaker(account, TRANCHE_A, estimatedNavA, epoch); (amountB, quoteAmountB) = _settleTaker(account, TRANCHE_B, estimatedNavB, epoch); uint256 version = _epochVersions[epoch]; (amountM, amountA, amountB) = _rebalanceAndClearTrade( account, amountM, amountA, amountB, version ); quoteAmount = quoteAmountM.add(quoteAmountA).add(quoteAmountB); _transferQuote(account, quoteAmount); emit TakerSettled(account, epoch, amountM, amountA, amountB, quoteAmount); } /// @dev Buy share /// @param version Current rebalance version. Revert if it is not the latest version. /// @param tranche Tranche of the base asset /// @param maxPDLevel Maximal premium-discount level accepted /// @param estimatedNav Estimated net asset value of the base asset /// @param quoteAmount Amount of quote assets willing to trade with 18 decimal places function _buy( uint256 version, uint256 tranche, uint256 maxPDLevel, uint256 estimatedNav, uint256 quoteAmount ) internal onlyActive { require(maxPDLevel > 0 && maxPDLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level"); require(version == fund.getRebalanceSize(), "Invalid version"); require(estimatedNav > 0, "Zero estimated NAV"); UnsettledBuyTrade memory totalTrade; uint256 epoch = endOfEpoch(block.timestamp); // Record rebalance version in the first transaction in the epoch if (_epochVersions[epoch] == 0) { _epochVersions[epoch] = version; } UnsettledBuyTrade memory currentTrade; uint256 orderIndex = 0; uint256 pdLevel = bestAsks[version][tranche]; if (pdLevel == 0) { // Zero best ask indicates that no ask order is ever placed. // We set pdLevel beyond the largest valid level, forcing the following loop // to exit immediately. pdLevel = PD_LEVEL_COUNT + 1; } for (; pdLevel <= maxPDLevel; pdLevel++) { uint256 price = pdLevel.mul(PD_TICK).add(PD_START).multiplyDecimal(estimatedNav); OrderQueue storage orderQueue = asks[version][tranche][pdLevel]; orderIndex = orderQueue.head; while (orderIndex != 0) { Order storage order = orderQueue.list[orderIndex]; // If the order initiator is no longer qualified for maker, // we skip the order and the linked-list-based order queue // would never traverse the order again if (!isMaker(order.maker)) { orderIndex = order.next; continue; } // Calculate the current trade assuming that the taker would be completely filled. currentTrade.frozenQuote = quoteAmount.sub(totalTrade.frozenQuote); currentTrade.reservedBase = currentTrade.frozenQuote.mul(MAKER_RESERVE_RATIO).div( price ); if (currentTrade.reservedBase < order.fillable) { // Taker is completely filled. currentTrade.effectiveQuote = currentTrade.frozenQuote.divideDecimal( pdLevel.mul(PD_TICK).add(PD_START) ); } else { // Maker is completely filled. Recalculate the current trade. currentTrade.frozenQuote = order.fillable.mul(price).div(MAKER_RESERVE_RATIO); currentTrade.effectiveQuote = order.fillable.mul(estimatedNav).div( MAKER_RESERVE_RATIO ); currentTrade.reservedBase = order.fillable; } totalTrade.frozenQuote = totalTrade.frozenQuote.add(currentTrade.frozenQuote); totalTrade.effectiveQuote = totalTrade.effectiveQuote.add( currentTrade.effectiveQuote ); totalTrade.reservedBase = totalTrade.reservedBase.add(currentTrade.reservedBase); unsettledTrades[order.maker][tranche][epoch].makerSell.add(currentTrade); // There is no need to rebalance for maker; the fact that the order could // be filled here indicates that the maker is in the latest version _tradeLocked(tranche, order.maker, currentTrade.reservedBase); uint256 orderNewFillable = order.fillable.sub(currentTrade.reservedBase); if (orderNewFillable > 0) { // Maker is not completely filled. Matching ends here. order.fillable = orderNewFillable; break; } else { // Delete the completely filled maker order. orderIndex = orderQueue.fill(orderIndex); } } orderQueue.updateHead(orderIndex); if (orderIndex != 0) { // This premium-discount level is not completely filled. Matching ends here. if (bestAsks[version][tranche] != pdLevel) { bestAsks[version][tranche] = pdLevel; } break; } } emit BuyTrade( msg.sender, tranche, totalTrade.frozenQuote, version, pdLevel, orderIndex, orderIndex == 0 ? 0 : currentTrade.reservedBase ); if (orderIndex == 0) { // Matching ends by completely filling all orders at and below the specified // premium-discount level `maxPDLevel`. // Find the new best ask beyond that level. for (; pdLevel <= PD_LEVEL_COUNT; pdLevel++) { if (!asks[version][tranche][pdLevel].isEmpty()) { break; } } bestAsks[version][tranche] = pdLevel; } require( totalTrade.frozenQuote > 0, "Nothing can be bought at the given premium-discount level" ); _transferQuoteFrom(msg.sender, totalTrade.frozenQuote); unsettledTrades[msg.sender][tranche][epoch].takerBuy.add(totalTrade); } /// @dev Sell share /// @param version Current rebalance version. Revert if it is not the latest version. /// @param tranche Tranche of the base asset /// @param minPDLevel Minimal premium-discount level accepted /// @param estimatedNav Estimated net asset value of the base asset /// @param baseAmount Amount of base assets willing to trade function _sell( uint256 version, uint256 tranche, uint256 minPDLevel, uint256 estimatedNav, uint256 baseAmount ) internal onlyActive { require(minPDLevel > 0 && minPDLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level"); require(version == fund.getRebalanceSize(), "Invalid version"); require(estimatedNav > 0, "Zero estimated NAV"); UnsettledSellTrade memory totalTrade; uint256 epoch = endOfEpoch(block.timestamp); // Record rebalance version in the first transaction in the epoch if (_epochVersions[epoch] == 0) { _epochVersions[epoch] = version; } UnsettledSellTrade memory currentTrade; uint256 orderIndex; uint256 pdLevel = bestBids[version][tranche]; for (; pdLevel >= minPDLevel; pdLevel--) { uint256 price = pdLevel.mul(PD_TICK).add(PD_START).multiplyDecimal(estimatedNav); OrderQueue storage orderQueue = bids[version][tranche][pdLevel]; orderIndex = orderQueue.head; while (orderIndex != 0) { Order storage order = orderQueue.list[orderIndex]; // If the order initiator is no longer qualified for maker, // we skip the order and the linked-list-based order queue // would never traverse the order again if (!isMaker(order.maker)) { orderIndex = order.next; continue; } currentTrade.frozenBase = baseAmount.sub(totalTrade.frozenBase); currentTrade.reservedQuote = currentTrade .frozenBase .multiplyDecimal(MAKER_RESERVE_RATIO) .multiplyDecimal(price); if (currentTrade.reservedQuote < order.fillable) { // Taker is completely filled currentTrade.effectiveBase = currentTrade.frozenBase.multiplyDecimal( pdLevel.mul(PD_TICK).add(PD_START) ); } else { // Maker is completely filled. Recalculate the current trade. currentTrade.frozenBase = order.fillable.divideDecimal(price).divideDecimal( MAKER_RESERVE_RATIO ); currentTrade.effectiveBase = order .fillable .divideDecimal(estimatedNav) .divideDecimal(MAKER_RESERVE_RATIO); currentTrade.reservedQuote = order.fillable; } totalTrade.frozenBase = totalTrade.frozenBase.add(currentTrade.frozenBase); totalTrade.effectiveBase = totalTrade.effectiveBase.add(currentTrade.effectiveBase); totalTrade.reservedQuote = totalTrade.reservedQuote.add(currentTrade.reservedQuote); unsettledTrades[order.maker][tranche][epoch].makerBuy.add(currentTrade); uint256 orderNewFillable = order.fillable.sub(currentTrade.reservedQuote); if (orderNewFillable > 0) { // Maker is not completely filled. Matching ends here. order.fillable = orderNewFillable; break; } else { // Delete the completely filled maker order. orderIndex = orderQueue.fill(orderIndex); } } orderQueue.updateHead(orderIndex); if (orderIndex != 0) { // This premium-discount level is not completely filled. Matching ends here. if (bestBids[version][tranche] != pdLevel) { bestBids[version][tranche] = pdLevel; } break; } } emit SellTrade( msg.sender, tranche, totalTrade.frozenBase, version, pdLevel, orderIndex, orderIndex == 0 ? 0 : currentTrade.reservedQuote ); if (orderIndex == 0) { // Matching ends by completely filling all orders at and above the specified // premium-discount level `minPDLevel`. // Find the new best bid beyond that level. for (; pdLevel > 0; pdLevel--) { if (!bids[version][tranche][pdLevel].isEmpty()) { break; } } bestBids[version][tranche] = pdLevel; } require( totalTrade.frozenBase > 0, "Nothing can be sold at the given premium-discount level" ); _tradeAvailable(tranche, msg.sender, totalTrade.frozenBase); unsettledTrades[msg.sender][tranche][epoch].takerSell.add(totalTrade); } /// @dev Settle both buy and sell trades of a specified epoch for takers /// @param account Taker address /// @param tranche Tranche of the base asset /// @param estimatedNav Estimated net asset value for the base asset /// @param epoch The epoch's end timestamp function _settleTaker( address account, uint256 tranche, uint256 estimatedNav, uint256 epoch ) internal returns (uint256 baseAmount, uint256 quoteAmount) { UnsettledTrade storage unsettledTrade = unsettledTrades[account][tranche][epoch]; // Settle buy trade UnsettledBuyTrade memory takerBuy = unsettledTrade.takerBuy; if (takerBuy.frozenQuote > 0) { (uint256 executionQuote, uint256 executionBase) = _buyTradeResult(takerBuy, estimatedNav); baseAmount = executionBase; quoteAmount = takerBuy.frozenQuote.sub(executionQuote); delete unsettledTrade.takerBuy; } // Settle sell trade UnsettledSellTrade memory takerSell = unsettledTrade.takerSell; if (takerSell.frozenBase > 0) { (uint256 executionQuote, uint256 executionBase) = _sellTradeResult(takerSell, estimatedNav); quoteAmount = quoteAmount.add(executionQuote); baseAmount = baseAmount.add(takerSell.frozenBase.sub(executionBase)); delete unsettledTrade.takerSell; } } /// @dev Settle both buy and sell trades of a specified epoch for makers /// @param account Maker address /// @param tranche Tranche of the base asset /// @param estimatedNav Estimated net asset value for the base asset /// @param epoch The epoch's end timestamp function _settleMaker( address account, uint256 tranche, uint256 estimatedNav, uint256 epoch ) internal returns (uint256 baseAmount, uint256 quoteAmount) { UnsettledTrade storage unsettledTrade = unsettledTrades[account][tranche][epoch]; // Settle buy trade UnsettledSellTrade memory makerBuy = unsettledTrade.makerBuy; if (makerBuy.frozenBase > 0) { (uint256 executionQuote, uint256 executionBase) = _sellTradeResult(makerBuy, estimatedNav); baseAmount = executionBase; quoteAmount = makerBuy.reservedQuote.sub(executionQuote); delete unsettledTrade.makerBuy; } // Settle sell trade UnsettledBuyTrade memory makerSell = unsettledTrade.makerSell; if (makerSell.frozenQuote > 0) { (uint256 executionQuote, uint256 executionBase) = _buyTradeResult(makerSell, estimatedNav); quoteAmount = quoteAmount.add(executionQuote); baseAmount = baseAmount.add(makerSell.reservedBase.sub(executionBase)); delete unsettledTrade.makerSell; } } /// @dev Calculate the result of an unsettled buy trade with a given NAV /// @param buyTrade Buy trade result of this particular epoch /// @param nav Net asset value for the base asset /// @return executionQuote Real amount of quote asset waiting for settlment /// @return executionBase Real amount of base asset waiting for settlment function _buyTradeResult(UnsettledBuyTrade memory buyTrade, uint256 nav) internal pure returns (uint256 executionQuote, uint256 executionBase) { uint256 reservedBase = buyTrade.reservedBase; uint256 reservedQuote = reservedBase.multiplyDecimal(nav); uint256 effectiveQuote = buyTrade.effectiveQuote; if (effectiveQuote < reservedQuote) { // Reserved base is enough to execute the trade. // nav is always positive here return (buyTrade.frozenQuote, effectiveQuote.divideDecimal(nav)); } else { // Reserved base is not enough. The trade is partially executed // and a fraction of frozenQuote is returned to the taker. return (buyTrade.frozenQuote.mul(reservedQuote).div(effectiveQuote), reservedBase); } } /// @dev Calculate the result of an unsettled sell trade with a given NAV /// @param sellTrade Sell trade result of this particular epoch /// @param nav Net asset value for the base asset /// @return executionQuote Real amount of quote asset waiting for settlment /// @return executionBase Real amount of base asset waiting for settlment function _sellTradeResult(UnsettledSellTrade memory sellTrade, uint256 nav) internal pure returns (uint256 executionQuote, uint256 executionBase) { uint256 reservedQuote = sellTrade.reservedQuote; uint256 effectiveQuote = sellTrade.effectiveBase.multiplyDecimal(nav); if (effectiveQuote < reservedQuote) { // Reserved quote is enough to execute the trade. return (effectiveQuote, sellTrade.frozenBase); } else { // Reserved quote is not enough. The trade is partially executed // and a fraction of frozenBase is returned to the taker. return (reservedQuote, sellTrade.frozenBase.mul(reservedQuote).div(effectiveQuote)); } } /// @dev Transfer quote asset to an account. Transfered amount is rounded down. /// @param account Recipient address /// @param amount Amount to transfer with 18 decimal places function _transferQuote(address account, uint256 amount) private { uint256 amountToTransfer = amount / _quoteDecimalMultiplier; if (amountToTransfer == 0) { return; } IERC20(quoteAssetAddress).safeTransfer(account, amountToTransfer); } /// @dev Transfer quote asset from an account. Transfered amount is rounded up. /// @param account Sender address /// @param amount Amount to transfer with 18 decimal places function _transferQuoteFrom(address account, uint256 amount) private { uint256 amountToTransfer = amount.add(_quoteDecimalMultiplier - 1) / _quoteDecimalMultiplier; IERC20(quoteAssetAddress).safeTransferFrom(account, address(this), amountToTransfer); } modifier onlyActive() { require(fund.isExchangeActive(block.timestamp), "Exchange is inactive"); _; } }
Sell Token B version Current rebalance version. Revert if it is not the latest version. minPDLevel Minimal premium-discount level accepted baseAmount Amount of Token B willing to trade
function sellB( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (, , uint256 estimatedNav) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_B, minPDLevel, estimatedNav, baseAmount); }
2,497,717
import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./Repayment.sol"; import { RoleManagement } from "./RoleManagement.sol"; pragma solidity ^0.5.0; contract Mortgage is Ownable { //Variables uint ETHER=(10**18); uint public MortgageCount=0; bool public contractPaused = false; address[] public repayments; mapping (uint => address[]) public parties; mapping (uint => mapping(address => bool)) public isParty; mapping (uint => BankContract) public mortgages; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => uint) pendingWithdrawals; //Structs struct BankContract{ address payable bank; address payable beneficiary; //mapping (address => bool) isParty; uint required; //address[] parties; address payable pin_owner; uint pin; uint amount; uint rates; uint length; bool executed; } //events event Submission(uint indexed transactionId); event Deposit(address indexed sender, uint value); event Confirmation(address indexed sender, uint indexed transactionId); event Execution(uint indexed transactionId); event Revocation(uint transactionId,address indexed sender); event ExecutionFailure(uint indexed transactionId); event CreateRepaymentContract(address addr); //modifiers // If the contract is paused, stop the modified function attached modifier checkIfPaused() { require(contractPaused == false); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /// @dev Contract constructor sets initial owners and required number of confirmations. constructor() public { } /// @dev circuitbreaker function that allows to stop the contract for time for any reason function circuitBreaker() public onlyOwner() { if (contractPaused == false) { contractPaused = true; } else { contractPaused = false; } } /// @dev allows anyone to check the balance of the contract /// @return returns the contract balance function getDeposit() public view returns (uint256){ return address(this).balance; } /// @dev Allows the contract to give the money to the owner of the property after everybody signed /// @param transactionId Transaction ID function withdraw(uint transactionId) internal{ require(isParty[transactionId][msg.sender],"Only party"); // against re-entrancy attack require(pendingWithdrawals[mortgages[transactionId].pin_owner]!=0); pendingWithdrawals[mortgages[transactionId].pin_owner]=0; mortgages[transactionId].pin_owner.transfer(address(this).balance); } /// @dev Allows anyone to submit and confirm a transaction. /// @param _bank represent the one that lend money /// @param _beneficiary represent the one whom the money has been lent to /// @param _pin_owner represent the owner of the property that the beneficiary wants to buy /// @param _pin represent the property identification number /// @param _amount represent the nb of ether lent /// @param _rates represent the interest /// @param _length the amount of time the beneficiary has to pay back the _bank /// @param addr the address of the contract that holds the registry /// @return Returns transaction ID. function submitTransaction(address payable _bank,address payable _beneficiary,address payable _pin_owner, uint _pin, uint _amount,uint _rates, uint _length,address addr) payable public checkIfPaused() returns (uint transactionId) { BankContract memory trx = BankContract(_bank,_beneficiary,3, _pin_owner,_pin,_amount,_rates,_length,false); transactionId = addTransaction(trx); parties[transactionId].push(_bank); parties[transactionId].push(_beneficiary); parties[transactionId].push(_pin_owner); for (uint i=0; i<parties[transactionId].length; i++) { require(!isParty[transactionId][parties[transactionId][i]] && parties[transactionId][i] != address(0)); isParty[transactionId][parties[transactionId][i]] = true; } pendingWithdrawals[_pin_owner]=_amount*ETHER; require(msg.value == _amount*ETHER,"The sender has to deposit the exact price of the loan in the contract"); address(this).transfer(_amount*ETHER); confirmTransaction(transactionId,addr); return transactionId; } /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param txx is the bankcontract just initialized /// @return Returns transaction ID. function addTransaction(BankContract memory txx) internal returns (uint transactionId) { transactionId = MortgageCount; mortgages[transactionId] = txx; MortgageCount += 1; emit Submission(transactionId); } /// @dev Check if the transaction has been executed /// @param transactionId Transaction ID. function isExecuted(uint transactionId)public view returns (bool){ return mortgages[transactionId].executed; } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. /// @param addr is the address of the contract representing the land registry function confirmTransaction(uint transactionId,address addr) public checkIfPaused() { require(confirmations[transactionId][msg.sender] == false); require(isParty[transactionId][msg.sender]==true); confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId,addr); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public { require(confirmations[transactionId][msg.sender] == true); require(isParty[transactionId][msg.sender]==true); confirmations[transactionId][msg.sender] = false; emit Revocation(transactionId,msg.sender); } function createRepayment(uint tId,address addr)internal returns(address){ Repayment repay = new Repayment(mortgages[tId].bank,mortgages[tId].beneficiary, tId, mortgages[tId].amount,mortgages[tId].rates, mortgages[tId].length,addr,mortgages[tId].pin); repayments.push(address(repay)); emit CreateRepaymentContract(address(repay)); return address(repay); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. /// @param addr is the address of the contract representing the land registry function executeTransaction(uint transactionId,address addr) public payable { if (isConfirmed(transactionId)) { //pin_owner.transfer(mortgages[transactionId].amount); mortgages[transactionId].executed=true; emit Execution(transactionId); withdraw(transactionId); Registry r = Registry(addr); r.updateProperty(mortgages[transactionId].beneficiary,mortgages[transactionId].pin); address repay =createRepayment(transactionId,addr); r.grantPermission(repay,'Admin'); }else{ emit ExecutionFailure(transactionId); } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) internal view returns (bool) { uint count = 0; for (uint i=0; i<parties[transactionId].length; i++) { if (confirmations[transactionId][parties[transactionId][i]]) count += 1; if (count == mortgages[transactionId].required) return true; } } }
Allows an owner to confirm a transaction. transactionId Transaction ID. addr is the address of the contract representing the land registry
function confirmTransaction(uint transactionId,address addr) public checkIfPaused() { require(confirmations[transactionId][msg.sender] == false); require(isParty[transactionId][msg.sender]==true); confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId,addr); }
6,486,854
./full_match/56/0xF6C48fb39Cd9D21E5103b1F01b26C6B2cEB2c1C7/sources/GameFactory.sol
Removes the provided address to the whitelist _removedAddress address to be removed from the whitelist/
function removeFromWhitelist(address _removedAddress) external onlyRole(CMO_ROLE) { _unWhitelist(_removedAddress); emit RemoveFromWhitelist(_removedAddress); }
3,258,983
./full_match/43113/0xD3068FBB4358A9B97c62f9EE3078465574b5880D/sources/WonkoIceCreamFactory_flat.sol
Get the list of all the tokens currently in sale
function tokensInSale() public view returns(uint256[] memory) { if(inSale == 0) { return new uint256[](0); } uint256[] memory result = new uint256[](inSale); uint256 index = 0; for(uint256 i = 0; i < totalSupply(); i++) { if(tokensInSaleMapping[i] == 1) { result[index] = i; index++; if(index == inSale) { return result; } } } return result; }
7,149,446
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { Governance } from "tornado-governance/contracts/Governance.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ITornadoVault } from "../interfaces/ITornadoVault.sol"; /// @title Version 2 Governance contract of the tornado.cash governance contract GovernanceVaultUpgrade is Governance { using SafeMath for uint256; // vault which stores user TORN ITornadoVault public immutable userVault; // call Governance v1 constructor constructor(address _userVault) public Governance() { userVault = ITornadoVault(_userVault); } /// @notice Withdraws TORN from governance if conditions permit /// @param amount the amount of TORN to withdraw function unlock(uint256 amount) public virtual override { require(getBlockTimestamp() > canWithdrawAfter[msg.sender], "Governance: tokens are locked"); lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount, "Governance: insufficient balance"); userVault.withdrawTorn(msg.sender, amount); } /// @notice checker for success on deployment /// @return returns precise version of governance function version() external pure virtual returns (string memory) { return "2.vault-migration"; } /// @notice transfers tokens from the contract to the vault, withdrawals are unlock() /// @param owner account/contract which (this) spender will send to the user vault /// @param amount amount which spender will send to the user vault function _transferTokens(address owner, uint256 amount) internal virtual override { require(torn.transferFrom(owner, address(userVault), amount), "TORN: transferFrom failed"); lockedBalance[owner] = lockedBalance[owner].add(amount); } }
Withdraws TORN from governance if conditions permit amount the amount of TORN to withdraw
function unlock(uint256 amount) public virtual override { require(getBlockTimestamp() > canWithdrawAfter[msg.sender], "Governance: tokens are locked"); lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount, "Governance: insufficient balance"); userVault.withdrawTorn(msg.sender, amount); }
12,640,293
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol
Harvest rewards of all epochs during estimation for each strategy _strategyPower Accumulated strategy power per epoch _protocolPower Accumulated protocol power per epoch _startingQuarter Starting quarter for calculations _numQuarters Total number of quarters for the calculation return the baseline estimated rewards for the strategy/ last quarter - we need to take proportional supply for that timeframe despite the epoch has not finished yet
function _harvestStrategyRewards( uint256[] memory _strategyPower, uint256[] memory _protocolPower, uint256 _startingQuarter, uint256 _numQuarters ) internal view returns (uint256) { uint256 strategyRewards; uint256 percentage = 1e18; for (uint256 i = 0; i < _numQuarters; i++) { if (i.add(1) == _numQuarters) { uint256 slotEnding = START_TIME.add(_startingQuarter.add(i).mul(EPOCH_DURATION)); percentage = block.timestamp.sub(slotEnding.sub(EPOCH_DURATION)).preciseDiv( slotEnding.sub(slotEnding.sub(EPOCH_DURATION)) ); } uint256 rewardsPerQuarter = _strategyPower[i] .preciseDiv(_protocolPower[i] == 0 ? 1 : _protocolPower[i]) .preciseMul(_tokenSupplyPerQuarter(_startingQuarter.add(i))) .preciseMul(percentage); strategyRewards = strategyRewards.add(rewardsPerQuarter); } return strategyRewards; }
3,050,177
pragma solidity ^0.4.24; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.24; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.24; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.24; /** * Interface for the standard token. * Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract EIP20Token { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** ** Optional functions * function name() public view returns (string name); function symbol() public view returns (string symbol); function decimals() public view returns (uint8 decimals); * **/ } pragma solidity ^0.4.24; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } pragma solidity ^0.4.24; // Interface for burning tokens contract Burnable { // @dev Destroys tokens for an account // @param account Account whose tokens are destroyed // @param value Amount of tokens to destroy function burnTokens(address account, uint value) internal; event Burned(address account, uint value); } pragma solidity ^0.4.24; /** * Authored by https://www.coinfabrik.com/ */ /** * Internal interface for the minting of tokens. */ contract Mintable { /** * @dev Mints tokens for an account * This function should the Minted event. */ function mintInternal(address receiver, uint amount) internal; /** Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); } /** * @title Standard token * @dev Basic implementation of the EIP20 standard token (also known as ERC20 token). */ contract StandardToken is EIP20Token, Burnable, Mintable { using SafeMath for uint; uint private total_supply; mapping(address => uint) private balances; mapping(address => mapping (address => uint)) private allowed; function totalSupply() public view returns (uint) { return total_supply; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint value) public returns (bool success) { 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 account The address whose balance is to be queried. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address account) public view returns (uint balance) { return balances[account]; } /** * @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 uint the amout of tokens to be transfered */ function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; // Check is not needed because sub(allowance, value) will already throw if this condition is not met // require(value <= allowance); // SafeMath uses assert instead of require though, beware when using an analysis tool balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); emit Transfer(from, to, value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses' // allowance to zero by calling `approve(spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require (value == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param account address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address spender, uint addedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][spender]; allowed[msg.sender][spender] = oldValue.add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address spender, uint subtractedValue) public returns (bool success) { uint oldVal = allowed[msg.sender][spender]; if (subtractedValue > oldVal) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldVal.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * @dev Provides an internal function for destroying tokens. Useful for upgrades. */ function burnTokens(address account, uint value) internal { balances[account] = balances[account].sub(value); total_supply = total_supply.sub(value); emit Transfer(account, 0, value); emit Burned(account, value); } /** * @dev Provides an internal minting function. */ function mintInternal(address receiver, uint amount) internal { total_supply = total_supply.add(amount); balances[receiver] = balances[receiver].add(amount); emit Minted(receiver, amount); // Beware: Address zero may be used for special transactions in a future fork. // This will make the mint transaction appear in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); } } pragma solidity ^0.4.24; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardToken, Ownable { /* The finalizer contract that allows lifting the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Set the contract that can call release and make the token transferable. * * Since the owner of this contract is (or should be) the crowdsale, * it can only be called by a corresponding exposed API in the crowdsale contract in case of input error. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to have a normal wallet address to act as a release agent. releaseAgent = addr; } /** * Owner can allow a particular address (e.g. a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens into the wild. * * Can be called only from the release agent that should typically be the finalize agent ICO contract. * In the scope of the crowdsale, it is only called if the crowdsale has been a success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** * Limit token transfer until the crowdsale is over. */ modifier canTransfer(address sender) { require(released || transferAgents[sender]); _; } /** The function can be called only before or after the tokens have been released */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** We restrict transfer by overriding it */ function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(to, value); } /** We restrict transferFrom by overriding it */ function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(from, to, value); } } pragma solidity ^0.4.24; /** * First envisioned by Golem and Lunyr projects. * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.24; /** * Inspired by Lunyr. * Originally from https://github.com/TokenMarketNet/ico */ /** * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. * * The Upgrade agent is the interface used to implement a token * migration in the case of an emergency. * The function upgradeFrom has to implement the part of the creation * of new tokens on behalf of the user doing the upgrade. * * The new token can implement this interface directly, or use. */ contract UpgradeAgent { /** This value should be the same as the original token's total supply */ uint public originalSupply; /** Interface to ensure the contract is correctly configured */ function isUpgradeAgent() public pure returns (bool) { return true; } /** Upgrade an account When the token contract is in the upgrade status the each user will have to call `upgrade(value)` function from UpgradeableToken. The upgrade function adjust the balance of the user and the supply of the previous token and then call `upgradeFrom(value)`. The UpgradeAgent is the responsible to create the tokens for the user in the new contract. * @param from Account to upgrade. * @param value Tokens to upgrade. */ function upgradeFrom(address from, uint value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * */ contract UpgradeableToken is EIP20Token, Burnable { using SafeMath for uint; /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint public totalUpgraded = 0; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can begin * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet. This allows changing the upgrade agent while there is time. * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed from, address to, uint value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ constructor(address master) internal { setUpgradeMaster(master); } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint value) public { UpgradeState state = getUpgradeState(); // Ensure it's not called in a bad state require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value. require(value != 0); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); // Take tokens out from circulation burnTokens(msg.sender, value); totalUpgraded = totalUpgraded.add(value); emit Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles the upgrade process */ function setUpgradeAgent(address agent) onlyMaster external { // Check whether the token is in a state that we could think of upgrading require(canUpgrade()); require(agent != 0x0); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply()); emit UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function changeUpgradeMaster(address new_master) onlyMaster public { setUpgradeMaster(new_master); } /** * Internal upgrade master setter. */ function setUpgradeMaster(address new_master) private { require(new_master != 0x0); upgradeMaster = new_master; } /** * Child contract can override to provide the condition in which the upgrade can begin. */ function canUpgrade() public view returns(bool) { return true; } modifier onlyMaster() { require(msg.sender == upgradeMaster); _; } } pragma solidity ^0.4.24; /** * Authored by https://www.coinfabrik.com/ */ // This contract aims to provide an inheritable way to recover tokens from a contract not meant to hold tokens // To use this contract, have your token-ignoring contract inherit this one and implement getLostAndFoundMaster to decide who can move lost tokens. // Of course, this contract imposes support costs upon whoever is the lost and found master. contract LostAndFoundToken { /** * @return Address of the account that handles movements. */ function getLostAndFoundMaster() internal view returns (address); /** * @param agent Address that will be able to move tokens with transferFrom * @param tokens Amount of tokens approved for transfer * @param token_contract Contract of the token */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { require(msg.sender == getLostAndFoundMaster()); // We use approve instead of transfer to minimize the possibility of the lost and found master // getting them stuck in another address by accident. token_contract.approve(agent, tokens); } } pragma solidity ^0.4.24; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ /** * A public interface to increase the supply of a token. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, usually contracts whitelisted by the owner, can mint new tokens. * */ contract MintableToken is Mintable, Ownable { using SafeMath for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); constructor(uint initialSupply, address multisig, bool mintable) internal { require(multisig != address(0)); // Cannot create a token without supply and no minting require(mintable || initialSupply != 0); // Create initially all balance on the team multisig if (initialSupply > 0) mintInternal(multisig, initialSupply); // No more new supply allowed after the token creation mintingFinished = !mintable; } /** * Create new tokens and allocate them to an address. * * Only callable by a mint agent (e.g. crowdsale contract). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { mintInternal(receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; emit MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only mint agents are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * A crowdsale token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through the approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * - ERC20 tokens transferred to this contract can be recovered by a lost and found master * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken { string public name = "Kryptobits"; string public symbol = "KBE"; uint8 public decimals; address public lost_and_found_master; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param initial_supply How many tokens we start with. * @param token_decimals Number of decimal places. * @param team_multisig Address of the multisig that receives the initial supply and is set as the upgrade master. * @param token_retriever Address of the account that handles ERC20 tokens that were accidentally sent to this contract. */ constructor(uint initial_supply, uint8 token_decimals, address team_multisig, address token_retriever) public UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, true) { require(token_retriever != address(0)); decimals = token_decimals; lost_and_found_master = token_retriever; } /** * When token is released to be transferable, prohibit new token creation. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality to kick in only if the crowdsale was a success. */ function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } function burn(uint value) public { burnTokens(msg.sender, value); } function getLostAndFoundMaster() internal view returns(address) { return lost_and_found_master; } }
Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to value uint the amout of tokens to be transfered/ Check is not needed because sub(allowance, value) will already throw if this condition is not met require(value <= allowance); SafeMath uses assert instead of require though, beware when using an analysis tool
function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); emit Transfer(from, to, value); return true; }
1,243,489
pragma solidity ^0.4.17; import "./token/ILivepeerToken.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/token/TokenVesting.sol"; import "zeppelin-solidity/contracts/token/TokenTimelock.sol"; contract GenesisManager is Ownable { using SafeMath for uint256; // LivepeerToken contract ILivepeerToken public token; // Address of the token distribution contract address public tokenDistribution; // Address of the Livepeer bank multisig address public bankMultisig; // Address of the Minter contract in the Livepeer protocol address public minter; // Initial token supply issued uint256 public initialSupply; // Crowd's portion of the initial token supply uint256 public crowdSupply; // Company's portion of the initial token supply uint256 public companySupply; // Team's portion of the initial token supply uint256 public teamSupply; // Investors' portion of the initial token supply uint256 public investorsSupply; // Community's portion of the initial token supply uint256 public communitySupply; // Token amount in grants for the team uint256 public teamGrantsAmount; // Token amount in grants for investors uint256 public investorsGrantsAmount; // Token amount in grants for the community uint256 public communityGrantsAmount; // Timestamp at which vesting grants begin their vesting period // and timelock grants release locked tokens uint256 public grantsStartTimestamp; // Map receiver addresses => contracts holding receivers' vesting tokens mapping (address => address) public vestingHolders; // Map receiver addresses => contracts holding receivers' time locked tokens mapping (address => address) public timeLockedHolders; enum Stages { // Stage for setting the allocations of the initial token supply GenesisAllocation, // Stage for the creating token grants and the token distribution GenesisStart, // Stage for the end of genesis when ownership of the LivepeerToken contract // is transferred to the protocol Minter GenesisEnd } // Current stage of genesis Stages public stage; // Check if genesis is at a particular stage modifier atStage(Stages _stage) { require(stage == _stage); _; } /** * @dev GenesisManager constructor * @param _token Address of the Livepeer token contract * @param _tokenDistribution Address of the token distribution contract * @param _bankMultisig Address of the company bank multisig * @param _minter Address of the protocol Minter */ function GenesisManager( address _token, address _tokenDistribution, address _bankMultisig, address _minter, uint256 _grantsStartTimestamp ) public { token = ILivepeerToken(_token); tokenDistribution = _tokenDistribution; bankMultisig = _bankMultisig; minter = _minter; grantsStartTimestamp = _grantsStartTimestamp; stage = Stages.GenesisAllocation; } /** * @dev Set allocations for the initial token supply at genesis * @param _initialSupply Initial token supply at genesis * @param _crowdSupply Tokens allocated for the crowd at genesis * @param _companySupply Tokens allocated for the company (for future distribution) at genesis * @param _teamSupply Tokens allocated for the team at genesis * @param _investorsSupply Tokens allocated for investors at genesis * @param _communitySupply Tokens allocated for the community at genesis */ function setAllocations( uint256 _initialSupply, uint256 _crowdSupply, uint256 _companySupply, uint256 _teamSupply, uint256 _investorsSupply, uint256 _communitySupply ) external onlyOwner atStage(Stages.GenesisAllocation) { require(_crowdSupply.add(_companySupply).add(_teamSupply).add(_investorsSupply).add(_communitySupply) == _initialSupply); initialSupply = _initialSupply; crowdSupply = _crowdSupply; companySupply = _companySupply; teamSupply = _teamSupply; investorsSupply = _investorsSupply; communitySupply = _communitySupply; } /** * @dev Start genesis */ function start() external onlyOwner atStage(Stages.GenesisAllocation) { // Mint the initial supply token.mint(this, initialSupply); stage = Stages.GenesisStart; } /** * @dev Add a team grant for tokens with a vesting schedule * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addTeamGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = teamGrantsAmount.add(_amount); // Amount of tokens included in team grants cannot exceed the team supply during genesis require(updatedGrantsAmount <= teamSupply); teamGrantsAmount = updatedGrantsAmount; addVestingGrant(_receiver, _amount, _timeToCliff, _vestingDuration); } /** * @dev Add an investor grant for tokens with a vesting schedule * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addInvestorGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = investorsGrantsAmount.add(_amount); // Amount of tokens included in investor grants cannot exceed the investor supply during genesis require(updatedGrantsAmount <= investorsSupply); investorsGrantsAmount = updatedGrantsAmount; addVestingGrant(_receiver, _amount, _timeToCliff, _vestingDuration); } /** * @dev Add a community grant for tokens that are locked until a predetermined time in the future * @param _receiver Grant receiver address * @param _amount Amount of tokens included in the grant */ function addCommunityGrant( address _receiver, uint256 _amount ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = communityGrantsAmount.add(_amount); // Amount of tokens included in investor grants cannot exceed the community supply during genesis require(updatedGrantsAmount <= communitySupply); communityGrantsAmount = updatedGrantsAmount; // Receiver must not have already received a grant with timelocked tokens require(timeLockedHolders[_receiver] == address(0)); // Create a timelocked holder contract to act as the holder of the grant's tokens TokenTimelock holder = new TokenTimelock(token, _receiver, grantsStartTimestamp); timeLockedHolders[_receiver] = holder; token.transfer(holder, _amount); } /** * @dev End genesis */ function end() external onlyOwner atStage(Stages.GenesisStart) { // Transfer the crowd supply to the token distribution contract token.transfer(tokenDistribution, crowdSupply); // Transfer company supply to the bank multisig token.transfer(bankMultisig, companySupply); // Transfer ownership of the LivepeerToken contract to the protocol Minter token.transferOwnership(minter); stage = Stages.GenesisEnd; } /** * @dev Add a grant for tokens with a vesting schedule. An internal helper function used by addTeamGrant and addInvestorGrant * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addVestingGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) internal { // Receiver must not have already received a grant with a vesting schedule require(vestingHolders[_receiver] == address(0)); // Create a vesting holder contract to act as the holder of the grant's tokens // Note: the vesting grant is revokable TokenVesting holder = new TokenVesting(_receiver, grantsStartTimestamp, _timeToCliff, _vestingDuration, true); vestingHolders[_receiver] = holder; // Transfer ownership of the vesting holder to the bank multisig // giving the bank multisig the ability to revoke the grant holder.transferOwnership(bankMultisig); token.transfer(holder, _amount); } }
Set allocations for the initial token supply at genesis _initialSupply Initial token supply at genesis _crowdSupply Tokens allocated for the crowd at genesis _companySupply Tokens allocated for the company (for future distribution) at genesis _teamSupply Tokens allocated for the team at genesis _investorsSupply Tokens allocated for investors at genesis _communitySupply Tokens allocated for the community at genesis/
function setAllocations( uint256 _initialSupply, uint256 _crowdSupply, uint256 _companySupply, uint256 _teamSupply, uint256 _investorsSupply, uint256 _communitySupply ) external onlyOwner atStage(Stages.GenesisAllocation) { require(_crowdSupply.add(_companySupply).add(_teamSupply).add(_investorsSupply).add(_communitySupply) == _initialSupply); initialSupply = _initialSupply; crowdSupply = _crowdSupply; companySupply = _companySupply; teamSupply = _teamSupply; investorsSupply = _investorsSupply; communitySupply = _communitySupply; }
6,451,114
/** *Submitted for verification at Etherscan.io on 2021-11-18 */ // 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.8.0; contract KoolKittensNFT is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; uint256 public cost = 20000000000000000; // 0.02 eth uint256 public maxSupply = 3333; uint256 public maxMintAmount = 20; bool public paused = false; mapping(address => bool) public whitelisted; constructor() ERC721("Kool Kittens", "KoolKittens") { } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(msg.value >= cost); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(whitelisted[msg.sender] != true) { require(msg.value >= cost * _mintAmount); } } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } } // free function mintFREE(address _to, uint256 _claimAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_claimAmount > 0); require(_claimAmount <= 1); require(supply + _claimAmount <= 300); for (uint256 i = 1; i <= _claimAmount; i++) { _safeMint(_to, 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())) : ""; } //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 pause(bool _state) public onlyOwner { paused = _state; } function whitelistUser(address _user) public onlyOwner { whitelisted[_user] = true; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; } function withdraw() onlyOwner public { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); __/\\\______________/\\\\\\\\\\\\\_______/\\\\\\\\\___________/\\\\\\\\\_ pragma solidity ^0.8.0; }
2,085,677
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol'; import "@openzeppelin/contracts/utils/Counters.sol"; import './Utils.sol'; /** * @title HappyRobotWhitelistToken * HappyRobotWhitelistToken - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract HappyRobotWhitelistToken is ERC1155, Ownable { using Counters for Counters.Counter; uint8 constant TOKEN_ID = 1; uint16 private tokenSupply = 0; // Contract name string public name; // Contract symbol string public symbol; uint8 constant SALE_STATUS_NONE = 0; uint8 saleStatus = SALE_STATUS_NONE; address[] private minters; mapping(address => uint8) mintsMap; mapping(address => uint8) burnsMap; uint16 private totalMints = 0; uint16 private totalBurns = 0; uint8 private maxPerWallet = 2; uint16 private maxWLTokens = 300; uint256 private mintFee = 0.075 ether; address payable constant public walletMaster = payable(0x4846063Ec8b9A428fFEe1640E790b8F825D4AbF0); address payable constant public walletDevTeam = payable(0x52BD82C6B851AdAC6A77BC0F9520e5A062CD9a78); address payable constant public walletArtist = payable(0x22d57ccD4e05DD1592f52A4B0f909edBB82e8D26); address proxyRegistryAddress; event MintedWLToken(address _owner, uint16 _quantity, uint256 _totalOwned); constructor( string memory _uri, address _proxyRegistryAddress ) ERC1155(_uri) { name = "HRF Token"; symbol = "HRFTOKEN"; proxyRegistryAddress = _proxyRegistryAddress; } /** * Require msg.sender to be the master or dev team */ modifier onlyMaster() { require(isMaster(msg.sender), "Happy Robot Whitelist Token: You are not a Master"); _; } /** * require none sale status */ modifier onlyNonSaleStatus() { require(saleStatus == SALE_STATUS_NONE, "Happy Robot Whitelist Token: It is sale period"); _; } /** * get account is master or not * @param _account address * @return true or false */ function isMaster(address _account) public pure returns (bool) { return walletMaster == payable(_account) || walletDevTeam == payable(_account); } /** * get token amount * @return token amount */ function totalSupply() public view returns (uint16) { return tokenSupply; } /** * get uri * @return uri */ function tokenUri() public view returns (string memory) { return ERC1155.uri(TOKEN_ID); } /** * set token uri * @param _uri token uri */ function setURI(string memory _uri) public onlyOwner { _setURI(_uri); } /** * get token quantity of account * @param _account account * @return token quantity of account */ function quantityOf(address _account) public view returns (uint256) { return balanceOf(_account, TOKEN_ID); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * get max wl tokens per wallet * @return max wl tokens per wallet */ function getMaxPerWallet() public view returns (uint8) { return maxPerWallet; } /** * set max wl tokens per wallet * @param _maxPerWallet max wl tokens per wallet */ function setMaxPerWallet(uint8 _maxPerWallet) public onlyMaster { maxPerWallet = _maxPerWallet; } /** * get whitelist token mint fee * @return whitelist token mint fee */ function getMintFee() public view returns (uint256) { return mintFee; } /** * set whitelist token mint fee * @param _mintFee mint fee */ function setMintFee(uint256 _mintFee) public onlyMaster { mintFee = _mintFee; } /** * get sale status * @return sale status */ function getSaleStatus() public view returns (uint8) { return saleStatus; } /** * set sale status * @param _saleStatus sale status */ function setSaleStatus(uint8 _saleStatus) public onlyMaster { saleStatus = _saleStatus; } /** * get max wl tokens * @return max wl tokens */ function getMaxWLTokens() public view returns (uint16) { return maxWLTokens; } /** * set max wl tokens * @param _maxWLTokens max wl tokens */ function setMaxWLTokens(uint8 _maxWLTokens) public onlyMaster { maxWLTokens = _maxWLTokens; } /** * get whitelist token minters */ function getMinters() public view returns (address[] memory) { return minters; } /** * check if _account is in the whitelist token minters * @param _account address * @return */ function existInMinters(address _account) public view returns (bool) { for (uint256 i = 0; i < minters.length; i++) { if (minters[i] == _account) return true; } return false; } /** * add an address into the whitelist * @param _account address */ function addToMinters(address _account) internal { // if already registered, skip for (uint16 i = 0; i < minters.length; i++) { if (minters[i] == _account) return; } // add address to the list minters.push(_account); } /** * remove an address from the minter list * @param _account address */ function removeFromMinters(address _account) internal { // find index of _from uint256 index = 0xFFFF; uint256 len = minters.length; for (uint256 i = 0; i < len; i++) { if (minters[i] == _account) { index = i; break; } } // remove it if (index != 0xFFFF && len > 0) { minters[index] = minters[len - 1]; minters.pop(); } } /** * get number of total minted whitelist tokens * @return number of total minted whitelist tokens */ function getTotalMinted() public view returns (uint16) { return totalMints; } /** * get number of total burned whitelist tokens * @return number of total burned whitelist tokens */ function getTotalBurned() public view returns (uint16) { return totalBurns; } /** * get number of minted count for account * @param _account address * @return number of minted count for account */ function getMints(address _account) public view returns (uint8) { return mintsMap[_account]; } /** * get number of burned count for account * @param _account address * @return number of burned count for account */ function getBurns(address _account) public view returns (uint8) { return burnsMap[_account]; } /** * get number of owned whitelist token(including burned count) for account * @param _account address * @return number of owned whitelist token(including burned count) for account */ function getOwned(address _account) public view returns (uint8) { unchecked { return uint8(quantityOf(_account)) + burnsMap[_account]; } } /** * check if mint is possible for account * @param _account account * @param _quantity quantity * @return true or false */ function canMintForAccount(address _account, uint16 _quantity) internal view returns (bool) { if (isMaster(_account)) return true; unchecked { uint8 balance = uint8(quantityOf(_account)); uint8 totalOwned = balance + burnsMap[_account]; return totalOwned + _quantity - 1 < maxPerWallet; } } /** * mint whitelist token * @param _quantity token amount */ function mint(uint8 _quantity) external payable onlyNonSaleStatus { require(canMintForAccount(msg.sender, _quantity) == true, "Happy Robot Whitelist Token: Maximum whitelist token mint already reached for the account"); require(totalSupply() + _quantity - 1 < maxWLTokens, "Happy Robot Whitelist Token: Maximum whitelist token already reached"); if (!isMaster(msg.sender)) { require(msg.value > mintFee * _quantity - 1, "Happy Robot Whitelist Token: Not enough ETH sent"); // perform mint mint(msg.sender, _quantity); unchecked { uint256 fee = mintFee * _quantity; uint256 feeForDev = (uint256)(fee / 200); // 0.5% to the dev walletDevTeam.transfer(feeForDev); uint256 feeForArtist = (uint256)(fee / 40); // 2.5% to the dev walletArtist.transfer(feeForArtist); // return back remain value uint256 remainVal = msg.value - fee; address payable caller = payable(msg.sender); caller.transfer(remainVal); } } else { // no price for master wallet // perform mint mint(msg.sender, _quantity); // return back the ethers address payable caller = payable(msg.sender); caller.transfer(msg.value); } } /** * mint tokens * @param _to address to mint * @param _quantity token quantity */ function mint(address _to, uint8 _quantity) internal { _mint(_to, TOKEN_ID, _quantity, ''); addToMinters(_to); unchecked { totalMints += _quantity; mintsMap[_to] += _quantity; // add mints map tokenSupply += _quantity; } // trigger whitelist token minted event emit MintedWLToken(_to, _quantity, totalMints); } /** * burn token * @param _from address to burn * @param _quantity token quantity */ function burn(address _from, uint8 _quantity) public onlyOwner { _burn(_from, TOKEN_ID, _quantity); unchecked { totalBurns += _quantity; burnsMap[_from] += _quantity; // add burns map tokenSupply -= _quantity; } } /** * withdraw balance to only master wallet */ function withdrawAll() external onlyMaster { address payable to = payable(msg.sender); to.transfer(address(this).balance); } } // 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 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract OwnableDelegateProxy { } /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // 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/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
remove an address from the minter list _account address/ find index of _from remove it
function removeFromMinters(address _account) internal { uint256 index = 0xFFFF; uint256 len = minters.length; for (uint256 i = 0; i < len; i++) { if (minters[i] == _account) { index = i; break; } } if (index != 0xFFFF && len > 0) { minters[index] = minters[len - 1]; minters.pop(); } }
14,513,359
./full_match/97/0x1a989668cd602fefa19CC58373161C94002318BE/sources/project_/contracts/Viddly.sol
Retrieves the distribution fee percentages return The owner, level, and creator fee percentages/
function getDistributionFeePercentage() external view override returns (uint256, uint256, uint256) { return (_ownerPercentage, _levelPercentage, _creatorPercentage); }
3,288,985
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // 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 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. */ 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; } } contract Prop { function noFeeTransfer(address _to, uint256 _value) public returns (bool); function mintTokens(address _atAddress, uint256 _amount) public; } contract BST { function balanceOf(address _owner) public constant returns (uint256 _balance); } contract FirstBuyers is Ownable { using SafeMath for uint256; /* Modifiers */ modifier onlyFirstBuyer() { require(firstBuyers[msg.sender].tokensReceived > 0); _; } /* Struct */ struct FirstBuyer { uint256 lastTransactionIndex; uint256 tokensReceived; uint256 weightedContribution; } /* Mappings */ mapping(address => FirstBuyer) firstBuyers; mapping(uint256 => uint256) transactions; mapping(uint256 => address) firstBuyerIndex; /* Private variables */ uint256 numOfTransaction; uint256 numOfFirstBuyers = 0; uint256 totalWeightedContribution; Prop property; BST bst; event FirstBuyerWhitdraw(address indexed _firstBuyer, uint256 _amount); event NewTransactionOfTokens(uint256 _amount, uint256 _index); /** * @dev constructor function, creates new FirstBuyers * @param _property Address of property * @param _owner Owner of this ICO **/ constructor(address _property, address _owner) public { property = Prop(_property); owner = _owner; bst = BST(0x509A38b7a1cC0dcd83Aa9d06214663D9eC7c7F4a); } /** * @dev add first buyers * @param _addresses Array of first buyer addresses * @param _amount Array of first buyer tokens **/ function addFirstBuyers(address[] _addresses, uint256[] _amount) public onlyOwner { require(_addresses.length == _amount.length); for(uint256 i = 0; i < _addresses.length; i++) { uint256 weightedContribution = (bst.balanceOf(_addresses[i]).mul(_amount[i])).div(10**18); FirstBuyer storage buyer = firstBuyers[_addresses[i]]; uint256 before = buyer.tokensReceived; buyer.tokensReceived = buyer.tokensReceived.add(_amount[i]); buyer.weightedContribution = buyer.weightedContribution.add(weightedContribution); property.mintTokens(_addresses[i], _amount[i]); firstBuyers[_addresses[i]] = buyer; totalWeightedContribution = totalWeightedContribution.add(weightedContribution); if(before == 0) { firstBuyerIndex[numOfFirstBuyers] = _addresses[i]; numOfFirstBuyers++; } } } /** * @dev allows First buyers to collect fee from transactions **/ function withdrawTokens() public onlyFirstBuyer { FirstBuyer storage buyer = firstBuyers[msg.sender]; require(numOfTransaction >= buyer.lastTransactionIndex); uint256 iterateOver = numOfTransaction.sub(buyer.lastTransactionIndex); if (iterateOver > 30) { iterateOver = 30; } uint256 iterate = buyer.lastTransactionIndex.add(iterateOver); uint256 amount = 0; for (uint256 i = buyer.lastTransactionIndex; i < iterate; i++) { uint256 ratio = ((buyer.weightedContribution.mul(10**14)).div(totalWeightedContribution)); amount = amount.add((transactions[buyer.lastTransactionIndex].mul(ratio)).div(10**14)); buyer.lastTransactionIndex = buyer.lastTransactionIndex.add(1); } assert(property.noFeeTransfer(msg.sender, amount)); emit FirstBuyerWhitdraw(msg.sender, amount); } /** * @dev save every transaction that BSPT sends * @param _amount Amount of tokens taken as fee **/ function incomingTransaction(uint256 _amount) public { require(msg.sender == address(property)); transactions[numOfTransaction] = _amount; numOfTransaction += 1; emit NewTransactionOfTokens(_amount, numOfTransaction); } /** * @dev get transaction index of last transaction that First buyer claimed * @param _firstBuyer First buyer address * @return Return transaction index **/ function getFirstBuyer(address _firstBuyer) constant public returns (uint256, uint256, uint256) { return (firstBuyers[_firstBuyer].lastTransactionIndex,firstBuyers[_firstBuyer].tokensReceived,firstBuyers[_firstBuyer].weightedContribution); } /** * @dev get number of first buyers * @return Number of first buyers **/ function getNumberOfFirstBuyer() constant public returns(uint256) { return numOfFirstBuyers; } /** * @dev get address of first buyer by index * @param _index Index of first buyer * @return Address of first buyer **/ function getFirstBuyerAddress(uint256 _index) constant public returns(address) { return firstBuyerIndex[_index]; } /** * @dev get total number of transactions * @return Total number of transactions that came in **/ function getNumberOfTransactions() constant public returns(uint256) { return numOfTransaction; } /** * @dev get total weighted contribution * @return Total sum of all weighted contribution **/ function getTotalWeightedContribution() constant public returns(uint256) { return totalWeightedContribution; } /** * @dev fallback function to prevent any ether to be sent to this contract **/ function () public payable { revert(); } } /*****************************/ /* STANDARD ERC20 TOKEN */ /*****************************/ contract ERC20Token { /** Functions needed to be implemented by ERC20 standard **/ function totalSupply() public constant returns (uint256 _totalSupply); function balanceOf(address _owner) public constant returns (uint256 _balance); function transfer(address _to, uint256 _amount) public returns (bool _success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool _success); function approve(address _spender, uint256 _amount) public returns (bool _success); function allowance(address _owner, address _spender) public constant returns (uint256 _remaining); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } contract Data { function canMakeNoFeeTransfer(address _from, address _to) constant public returns(bool); function getNetworkFee() public constant returns (uint256); function getBlocksquareFee() public constant returns (uint256); function getCPFee() public constant returns (uint256); function getFirstBuyersFee() public constant returns (uint256); function hasPrestige(address _owner) public constant returns(bool); } /*****************/ /* PROPERTY */ /*****************/ contract PropToken is ERC20Token, Ownable { using SafeMath for uint256; struct Prop { string primaryPropertyType; string secondaryPropertyType; uint64 cadastralMunicipality; uint64 parcelNumber; uint64 id; } /* Info about property */ string mapURL = "https://www.google.com/maps/place/Tehnolo%C5%A1ki+park+Ljubljana+d.o.o./@46.0491873,14.458252,17z/data=!3m1!4b1!4m5!3m4!1s0x477ad2b1cdee0541:0x8e60f36e738253f0!8m2!3d46.0491873!4d14.4604407"; string public name = "PropToken BETA 000000000001"; // Name of property string public symbol = "BSPT-BETA-000000000001"; // Symbol for property uint8 public decimals = 18; // Decimals uint8 public numOfProperties; bool public tokenFrozen; // Can property be transfered /* Fee-recievers */ FirstBuyers public firstBuyers; //FirstBuyers address public networkReserveFund; // Address of Reserve funds address public blocksquare; // Address of Blocksquare address public certifiedPartner; // Address of partner who is selling property /* Private variables */ uint256 supply; //Current supply, at end total supply uint256 MAXSUPPLY = 100000 * 10 ** 18; // Total supply uint256 feePercent; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowances; Data data; Prop[] properties; /* Events */ event TokenFrozen(bool _frozen, string _reason); event Mint(address indexed _to, uint256 _value); /** * @dev constructor **/ constructor() public { owner = msg.sender; tokenFrozen = true; feePercent = 2; networkReserveFund = address(0x7E8f1b7655fc05e48462082E5A12e53DBc33464a); blocksquare = address(0x84F4CE7a40238062edFe3CD552cacA656d862f27); certifiedPartner = address(0x3706E1CdB3254a1601098baE8D1A8312Cf92f282); firstBuyers = new FirstBuyers(this, owner); } /** * @dev add new property under this BSPT * @param _primaryPropertyType Primary type of property * @param _secondaryPropertyType Secondary type of property * @param _cadastralMunicipality Cadastral municipality * @param _parcelNumber Parcel number * @param _id Id of property **/ function addProperty(string _primaryPropertyType, string _secondaryPropertyType, uint64 _cadastralMunicipality, uint64 _parcelNumber, uint64 _id) public onlyOwner { properties.push(Prop(_primaryPropertyType, _secondaryPropertyType, _cadastralMunicipality, _parcelNumber, _id)); numOfProperties++; } /** * @dev set data factory * @param _data Address of data factory **/ function setDataFactory(address _data) public onlyOwner { data = Data(_data); } /** * @dev send tokens without fee * @param _from Address of sender. * @param _to Address of recipient. * @param _amount Amount to send. * @return Whether the transfer was successful or not. **/ function noFee(address _from, address _to, uint256 _amount) private returns (bool) { require(!tokenFrozen); require(balances[_from] >= _amount); balances[_to] = balances[_to].add(_amount); balances[_from] = balances[_from].sub(_amount); emit Transfer(_from, _to, _amount); return true; } /** * @dev allows first buyers contract to transfer BSPT without fee * @param _to Where to send BSPT * @param _amount Amount of BSPT to send * @return True if transfer was successful, false instead **/ function noFeeTransfer(address _to, uint256 _amount) public returns (bool) { require(msg.sender == address(firstBuyers)); return noFee(msg.sender, _to, _amount); } /** * @dev calculate and distribute fee for fee-recievers * @param _fee Fee amount **/ function distributeFee(uint256 _fee) private { balances[networkReserveFund] = balances[networkReserveFund].add((_fee.mul(data.getNetworkFee())).div(100)); balances[blocksquare] = balances[blocksquare].add((_fee.mul(data.getBlocksquareFee())).div(100)); balances[certifiedPartner] = balances[certifiedPartner].add((_fee.mul(data.getCPFee())).div(100)); balances[address(firstBuyers)] = balances[address(firstBuyers)].add((_fee.mul(data.getFirstBuyersFee())).div(100)); firstBuyers.incomingTransaction((_fee.mul(data.getFirstBuyersFee())).div(100)); } /** * @dev send tokens * @param _from Address of sender. * @param _to Address of recipient. * @param _amount Amount to send. **/ function _transfer(address _from, address _to, uint256 _amount) private { require(_to != 0x0); require(_to != address(this)); require(balances[_from] >= _amount); uint256 fee = (_amount.mul(feePercent)).div(100); distributeFee(fee); balances[_to] = balances[_to].add(_amount.sub(fee)); balances[_from] = balances[_from].sub(_amount); emit Transfer(_from, _to, _amount.sub(fee)); } /** * @dev send tokens from your address. * @param _to Address of recipient. * @param _amount Amount to send. * @return Whether the transfer was successful or not. **/ function transfer(address _to, uint256 _amount) public returns (bool) { require(!tokenFrozen); if (data.canMakeNoFeeTransfer(msg.sender, _to) || data.hasPrestige(msg.sender)) { noFee(msg.sender, _to, _amount); } else { _transfer(msg.sender, _to, _amount); } return true; } /** * @dev set allowance for someone to spend tokens from your address * @param _spender Address of spender. * @param _amount Max amount allowed to spend. * @return Whether the approve was successful or not. **/ function approve(address _spender, uint256 _amount) public returns (bool) { allowances[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev send tokens * @param _from Address of sender. * @param _to Address of recipient. * @param _amount Amount of token to send. * @return Whether the transfer was successful or not. **/ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowances[_from][msg.sender]); require(!tokenFrozen); _transfer(_from, _to, _amount); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount); return true; } /** * @dev mint tokens, can only be done by first buyers contract * @param _atAddress Adds tokens to address * @param _amount Amount of tokens to add **/ function mintTokens(address _atAddress, uint256 _amount) public { require(msg.sender == address(firstBuyers)); require(balances[_atAddress].add(_amount) > balances[_atAddress]); require((supply.add(_amount)) <= MAXSUPPLY); supply = supply.add(_amount); balances[_atAddress] = balances[_atAddress].add(_amount); emit Mint(_atAddress, _amount); emit Transfer(0x0, _atAddress, _amount); } /** * @dev changes status of frozen * @param _reason Reason for freezing or unfreezing token **/ function changeFreezeTransaction(string _reason) public onlyOwner { tokenFrozen = !tokenFrozen; emit TokenFrozen(tokenFrozen, _reason); } /** * @dev change fee percent * @param _fee New fee percent **/ function changeFee(uint256 _fee) public onlyOwner { feePercent = _fee; } /** * @dev get allowance * @param _owner Owner address * @param _spender Spender address * @return Return amount allowed to spend from '_owner' by '_spender' **/ function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } /** * @dev total amount of token * @return Total amount of token **/ function totalSupply() public constant returns (uint256) { return supply; } /** * @dev check balance of address * @param _owner Address * @return Amount of token in possession **/ function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } /** * @dev get information about property * @param _index Index of property * @return Primary type, secondary type, cadastral municipality, parcel number and id of property **/ function getPropertyInfo(uint8 _index) public constant returns (string, string, uint64, uint64, uint64) { return (properties[_index].primaryPropertyType, properties[_index].secondaryPropertyType, properties[_index].cadastralMunicipality, properties[_index].parcelNumber, properties[_index].id); } /** * @dev get google maps url of property location **/ function getMap() public constant returns (string) { return mapURL; } }
get total weighted contribution return Total sum of all weighted contribution/
function getTotalWeightedContribution() constant public returns(uint256) { return totalWeightedContribution; }
13,884,793
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.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.7.5; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./exchange/Exchange.sol"; import "./registry/ProxyRegistry.sol"; import "./modules/VindergoodTransferProxy.sol"; import "./modules/ERC20.sol"; contract VindergoodExchange is Exchange { string public constant name = "Vindergood Exchange"; /** * @dev Initialize a VindergoodExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ function initialize( ProxyRegistry registryAddress, VindergoodTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress ) public initializer { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/ArrayUtils.sol"; import "../libraries/SaleKindInterface.sol"; import "../registry/ProxyRegistry.sol"; import "../modules/VindergoodTransferProxy.sol"; import "../registry/AuthenticatedProxy.sol"; import "./ExchangeMain.sol"; contract Exchange is ExchangeMain { /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice( SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint256 basePrice, uint256 extra, uint256 listingTime, uint256 expirationTime, uint256 amount ) public view returns (uint256) { return SaleKindInterface.calculateFinalPrice( side, saleKind, basePrice, extra, listingTime, expirationTime, amount ); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata ) public pure returns (bytes32) { return hashOrder( Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ) ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata ) public pure returns (bytes32) { return hashToSign( Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ) ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata ) public view returns (bool) { Order memory order = Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ); return validateOrderParameters(order); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata, uint8 v, bytes32 r, bytes32 s ) public view returns (bool) { Order memory order = Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ); return validateOrder(hashToSign(order), order, Sig(v, r, s)); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata, bool orderbookInclusionDesired ) public { Order memory order = Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata, uint8 v, bytes32 r, bytes32 s ) public { return cancelOrder( Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ), Sig(v, r, s) ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] memory addrs, uint256[7] memory uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes memory callData, bytes memory replacementPattern, bytes memory staticExtradata, uint256 amount ) public view returns (uint256) { return calculateCurrentPrice( Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ), amount ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] memory addrs, uint256[14] memory uints, uint8[8] memory feeMethodsSidesKindsHowToCalls, bytes memory calldataBuy, bytes memory calldataSell, bytes memory replacementPatternBuy, bytes memory replacementPatternSell, bytes memory staticExtradataBuy, bytes memory staticExtradataSell ) public view returns (bool) { Order memory buy = Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ); Order memory sell = Order( addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13] ); return ordersCanMatch(buy, sell); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch( bytes memory buyCalldata, bytes memory buyReplacementPattern, bytes memory sellCalldata, bytes memory sellReplacementPattern ) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace( buyCalldata, sellCalldata, buyReplacementPattern ); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace( sellCalldata, buyCalldata, sellReplacementPattern ); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] memory addrs, uint256[14] memory uints, uint8[8] memory feeMethodsSidesKindsHowToCalls, bytes memory calldataBuy, bytes memory calldataSell, bytes memory replacementPatternBuy, bytes memory replacementPatternSell, bytes memory staticExtradataBuy, bytes memory staticExtradataSell, uint256 amount ) public view returns (uint256) { Order memory buy = Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ); Order memory sell = Order( addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13] ); return calculateMatchPrice(buy, sell, amount); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] memory addrs, uint256[14] memory uints, uint8[8] memory feeMethodsSidesKindsHowToCalls, bytes memory calldataBuy, bytes memory calldataSell, bytes memory replacementPatternBuy, bytes memory replacementPatternSell, bytes memory staticExtradataBuy, bytes memory staticExtradataSell, uint8[2] memory vs, bytes32[5] memory rssMetadata ) public payable { return atomicMatch( Order( addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind( feeMethodsSidesKindsHowToCalls[2] ), addrs[4], AuthenticatedProxy.HowToCall( feeMethodsSidesKindsHowToCalls[3] ), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6] ), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order( addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind( feeMethodsSidesKindsHowToCalls[6] ), addrs[11], AuthenticatedProxy.HowToCall( feeMethodsSidesKindsHowToCalls[7] ), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13] ), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../libraries/LibPart.sol"; import "../royalties/RoyaltiesV2.sol"; import "../libraries/ArrayUtils.sol"; import "../libraries/SaleKindInterface.sol"; import "../registry/ProxyRegistry.sol"; import "../modules/ERC20.sol"; import "../modules/VindergoodTransferProxy.sol"; import "../registry/AuthenticatedProxy.sol"; import "../interfaces/IVindergoodStore.sol"; contract ExchangeMain is ReentrancyGuardUpgradeable { /* The token used to pay exchange fees. */ ERC20 public exchangeToken; bytes4 constant ERC1155_SIGNATURE = 0x127217d6; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ VindergoodTransferProxy public tokenTransferProxy; struct SellRemaining { bool tracking; uint256 left; } mapping(bytes32 => SellRemaining) public sellOrderAmountRemaining; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ mapping(bytes32 => bool) public approvedOrders; // /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ // uint public minimumMakerProtocolFee = 0; // /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ // uint public minimumTakerProtocolFee = 0; // /* Recipient of protocol fees. */ // address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint256 public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint256 makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint256 takerRelayerFee; // /* Maker protocol fee of the order, unused for taker order. */ // uint makerProtocolFee; // /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ // uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes callData; bytes replacementPattern; /* Calldata replacement pattern, or an empty byte array for no replacement. */ // bytes replacementPattern; // /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint256 basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint256 extra; /* Listing timestamp. */ uint256 listingTime; /* Expiration timestamp - 0 for no expiry. */ uint256 expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint256 salt; } event OrderApprovedPartOne( bytes32 indexed hash, address exchange, address indexed maker, address taker, uint256 makerRelayerFee, uint256 takerRelayerFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target ); event OrderApprovedPartTwo( bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, address staticTarget, bytes staticExtradata, address paymentToken, uint256 basePrice, uint256 extra, uint256 listingTime, uint256 expirationTime, uint256 salt, bool orderbookInclusionDesired ); // event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); // event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled(bytes32 indexed hash); event OrdersMatched( bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint256 price, bytes32 indexed metadata ); // /** // * @dev Change the minimum maker fee paid to the protocol (owner only) // * @param newMinimumMakerProtocolFee New fee to set in basis points // */ // function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) // public // onlyOwner // { // minimumMakerProtocolFee = newMinimumMakerProtocolFee; // } // /** // * @dev Change the minimum taker fee paid to the protocol (owner only) // * @param newMinimumTakerProtocolFee New fee to set in basis points // */ // function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) // public // onlyOwner // { // minimumTakerProtocolFee = newMinimumTakerProtocolFee; // } // /** // * @dev Change the protocol fee recipient (owner only) // * @param newProtocolFeeRecipient New protocol fee recipient address // */ // function changeProtocolFeeRecipient(address newProtocolFeeRecipient) // public // onlyOwner // { // protocolFeeRecipient = newProtocolFeeRecipient; // } // function changeDefaultCollection(address _newCollection) public onlyOwner { // require( // _newCollection != defaultCollection, // "VindergoodExchange::New collection address is the same" // ); // defaultCollection = _newCollection; // } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens( address token, address from, address to, uint256 amount ) internal { if (amount > 0) { tokenTransferProxy.transferFrom(token, from, to, amount); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee( address from, address to, uint256 amount ) internal { transferTokens(address(exchangeToken), from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param callData Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) */ // function staticCall(address target, bytes memory callData, bytes memory extradata) // public // view // returns (bool result) // { // bytes memory combined = new bytes(callData.length + extradata.length); // uint index; // assembly { // index := add(combined, 0x20) // } // index = ArrayUtils.unsafeWriteBytes(index, extradata); // ArrayUtils.unsafeWriteBytes(index, callData); // assembly { // result := staticcall(gas(), target, add(combined, 0x20), mload(combined), mload(0x40), 0) // } // return result; // } /** * Calculate size of an order struct when tightly packed * * @param order Order to calculate size of * @return Size in bytes */ function sizeOf(Order memory order) internal pure returns (uint256) { return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length); // return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length); } /** * @dev Hash an order, returning the canonical order hash, without the message prefix * @param order Order to hash */ function hashOrder(Order memory order) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint256 size = sizeOf(order); bytes memory array = new bytes(size); uint256 index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteAddress(index, order.exchange); index = ArrayUtils.unsafeWriteAddress(index, order.maker); index = ArrayUtils.unsafeWriteAddress(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); // index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); // index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddress(index, order.target); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes(index, order.callData); index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern); index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata); index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @param order Order to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", hashOrder(order) ) ); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig) internal view returns (bytes32) { bytes32 hash = hashToSign(order); require(validateOrder(hash, order, sig), "INVALID_ORDER_HASH"); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must possess valid sale kind parameter combination. */ if ( !SaleKindInterface.validateParameters( order.saleKind, order.expirationTime ) ) { return false; } // /* If using the split fee method, order must have sufficient protocol fees. */ // if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { // return false; // } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder( bytes32 hash, Order memory order, Sig memory sig ) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Order authentication. Order must be either: /* (a) previously approved */ if (approvedOrders[hash]) { return true; } /* or (b) ECDSA-signed by maker. */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } return false; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order); /* Assert order has not already been approved. */ require(!approvedOrders[hash]); /* EFFECTS */ /* Mark order as approved. */ approvedOrders[hash] = true; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne( hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target ); } { emit OrderApprovedPartTwo( hash, order.howToCall, order.callData, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired ); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice(Order memory order, uint256 amount) internal view returns (uint256) { return SaleKindInterface.calculateFinalPrice( order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime, amount ); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice( Order memory buy, Order memory sell, uint256 amount ) internal view returns (uint256) { /* Calculate sell price. */ uint256 sellPrice = SaleKindInterface.calculateFinalPrice( sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime, amount ); /* Calculate buy price. */ uint256 buyPrice = SaleKindInterface.calculateFinalPrice( buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime, amount ); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer( Order memory buy, Order memory sell, LibPart.Part memory royalty, uint256 amount ) internal returns (uint256) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint256 price = calculateMatchPrice(buy, sell, amount); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint256 receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint256 requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { // /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ // require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint256 makerRelayerFee = SafeMath.div( SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT ); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub( receiveAmount, makerRelayerFee ); payable(sell.feeRecipient).transfer(makerRelayerFee); } else { transferTokens( sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee ); } } if (sell.takerRelayerFee > 0) { uint256 takerRelayerFee = SafeMath.div( SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT ); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add( requiredAmount, takerRelayerFee ); payable(sell.feeRecipient).transfer(takerRelayerFee); } else { transferTokens( sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee ); } } // if (sell.makerProtocolFee > 0) { // uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); // if (sell.paymentToken == address(0)) { // receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); // protocolFeeRecipient.transfer(makerProtocolFee); // } else { // transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); // } // } // if (sell.takerProtocolFee > 0) { // uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); // if (sell.paymentToken == address(0)) { // requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); // protocolFeeRecipient.transfer(takerProtocolFee); // } else { // transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); // } // } } else { /* Charge maker fee to seller. */ chargeProtocolFee( sell.maker, sell.feeRecipient, sell.makerRelayerFee ); /* Charge taker fee to buyer. */ chargeProtocolFee( buy.maker, sell.feeRecipient, sell.takerRelayerFee ); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); // /* Assert taker fee is less than or equal to maximum fee specified by seller. */ // require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { uint256 makerRelayerFee = SafeMath.div( SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT ); transferTokens( sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee ); } if (buy.takerRelayerFee > 0) { uint256 takerRelayerFee = SafeMath.div( SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT ); transferTokens( sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee ); } // if (buy.makerProtocolFee > 0) { // makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); // transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); // } // if (buy.takerProtocolFee > 0) { // takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); // transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); // } } else { /* Charge maker fee to buyer. */ chargeProtocolFee( buy.maker, buy.feeRecipient, buy.makerRelayerFee ); /* Charge taker fee to seller. */ chargeProtocolFee( sell.maker, buy.feeRecipient, buy.takerRelayerFee ); } } if (royalty.account != address(0) && royalty.value > 0) { uint256 royaltyAmount = SafeMath.div( SafeMath.mul(royalty.value, price), INVERSE_BASIS_POINT ); receiveAmount = SafeMath.sub(receiveAmount, royaltyAmount); if (sell.paymentToken == address(0)) { royalty.account.transfer(royaltyAmount); } if ( sell.paymentToken != address(0) && sell.maker != royalty.account ) { transferTokens( sell.paymentToken, sell.maker, royalty.account, royaltyAmount ); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); payable(sell.maker).transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint256 diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { payable(buy.maker).transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return (/* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder( buy.listingTime, buy.expirationTime ) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder( sell.listingTime, sell.expirationTime )); } function _validatePartialSellingAmount(Order memory buy, Order memory sell) internal returns (bool, uint256) { uint256 buyAmount; uint256 sellAmount; uint256 tokenId; bytes32 hash = hashToSign(sell); SellRemaining storage sellAmountRemaining = sellOrderAmountRemaining[ hash ]; assembly { let sellCallData := mload(add(sell, mul(0x20, 11))) let buyCallData := mload(add(buy, mul(0x20, 11))) tokenId := mload(add(sellCallData, add(mul(0x20, 2), 0x04))) buyAmount := mload(add(buyCallData, add(mul(0x20, 4), 0x04))) sellAmount := mload(add(sellCallData, add(mul(0x20, 4), 0x04))) } if (!sellAmountRemaining.tracking) { sellAmountRemaining.tracking = true; sellAmountRemaining.left = sellAmount; } require( SafeMath.sub(sellAmountRemaining.left, buyAmount) >= 0, "PaceArtExchange::ERC1155 remaining is not enough!" ); sellAmountRemaining.left = SafeMath.sub( sellAmountRemaining.left, buyAmount ); if (sellAmountRemaining.left == 0) { delete sellOrderAmountRemaining[hash]; return (true, buyAmount); } return (false, buyAmount); } function makeStaticCall(Order memory order, bool callMint) internal returns (bytes memory) { if (callMint) { (bool result, bytes memory returnData) = order.target.call( order.callData ); require(result, "Exchange::Failed when call other contract"); return returnData; } else { /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(order.maker); /* Proxy must exist. */ require( address(delegateProxy) != address(0), "User not registed proxy yet!" ); /* Assert implementation. */ require( delegateProxy.implementation() == registry.delegateProxyImplementation() ); /* Execute specified call through proxy. */ (bool result, bytes memory returnData) = AuthenticatedProxy( address(delegateProxy) ).proxy(order.target, order.howToCall, order.callData); require(result, "Exchange::Failed when call other contract"); return returnData; } } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch( Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata ) internal nonReentrant { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = requireValidOrder(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = requireValidOrder(sell, sellSig); } /* Must be matchable. */ require( ordersCanMatch(buy, sell), "VindergoodExchange:: Order not matched" ); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint256 size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); bytes4 signature; bool soldOut = true; uint256 amount = 1; assembly { let sellCallData := mload(add(sell, mul(0x20, 11))) signature := mload(add(sellCallData, 0x20)) } if (signature == ERC1155_SIGNATURE) { (soldOut, amount) = _validatePartialSellingAmount(buy, sell); } /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace( buy.callData, sell.callData, buy.replacementPattern ); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace( sell.callData, buy.callData, sell.replacementPattern ); } require(ArrayUtils.arrayEq(buy.callData, sell.callData)); /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker && soldOut) { cancelledOrFinalized[sellHash] = true; } bytes memory returnData = makeStaticCall(sell, signature == 0xda22caf8); // Transfer Royalty Fee. Prevent stack too deep errors uint256 tokenId = abi.decode(returnData, (uint256)); // /* Execute funds transfer and pay fees. */ uint256 price = executeFundsTransfer( buy, sell, RoyaltiesV2(sell.target).getVindergoodV2Royalties(tokenId), amount ); // /* Log match event. */ emit OrdersMatched( buyHash, sellHash, sell.maker, buy.maker, price, metadata ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "../libraries/LibPart.sol"; interface IVindergoodStore { function singleTransfer( address _from, address _to, uint256 _tokenId ) external returns (uint256); function mintTo(address _to, LibPart.Part memory _royalty) external returns (uint256); function owner() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ArrayUtils * @author Wyvern Protocol Developers */ library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * Modifies the provided byte array parameter in place * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed */ function guardedArrayReplace( bytes memory array, bytes memory desired, bytes memory mask ) internal pure { require( array.length == desired.length, "Arrays have different lengths" ); require( array.length == mask.length, "Array and mask have different lengths" ); uint256 words = array.length / 0x20; uint256 index = words * 0x20; assert(index / 0x20 == words); uint256 i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore( add(array, commonIndex), or( and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))) ) ) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore( add(array, commonIndex), or( and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))) ) ) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * * @dev Arrays must be of equal length, otherwise will return false * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { bool success = true; assembly { let length := mload(a) // if lengths don't match the arrays are not equal switch eq(length, mload(b)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(a, 0x20) let end := add(mc, length) for { let cc := add(b, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } /** * Drop the beginning of an array * * @param _bytes array * @param _start start index * @return Whether or not all bytes in the arrays are equal */ function arrayDrop(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { uint256 _length = SafeMath.sub(_bytes.length, _start); return arraySlice(_bytes, _start, _length); } /** * Take from the beginning of an array * * @param _bytes array * @param _length elements to take * @return Whether or not all bytes in the arrays are equal */ function arrayTake(bytes memory _bytes, uint256 _length) internal pure returns (bytes memory) { return arraySlice(_bytes, 0, _length); } /** * Slice an array * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * * @param _bytes array * @param _start start index * @param _length length to take * @return Whether or not all bytes in the arrays are equal */ function arraySlice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint256 index, bytes memory source) internal pure returns (uint256) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint256 index, address source) internal pure returns (uint256) { uint256 conv = uint256(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint256 index, uint256 source) internal pure returns (uint256) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint256 index, uint8 source) internal pure returns (uint256) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } } // SPDX-License-Identifier: MIT pragma pragma solidity 0.7.5; library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint256 expirationTime) internal pure returns (bool) { /* Auctions must have a set expiration date. */ return (saleKind == SaleKind.FixedPrice || expirationTime > 0); } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint256 listingTime, uint256 expirationTime) internal view returns (bool) { return (listingTime < block.timestamp) && (expirationTime == 0 || block.timestamp < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice( Side side, SaleKind saleKind, uint256 basePrice, uint256 extra, uint256 listingTime, uint256 expirationTime, uint256 amount ) internal view returns (uint256 finalPrice) { if (saleKind == SaleKind.FixedPrice) { return SafeMath.mul(basePrice, amount); } else if (saleKind == SaleKind.DutchAuction) { uint256 diff = SafeMath.div( SafeMath.mul(extra, SafeMath.sub(block.timestamp, listingTime)), SafeMath.sub(expirationTime, listingTime) ); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(SafeMath.mul(basePrice, amount), diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(SafeMath.mul(basePrice, amount), diff); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x095ea7b3, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed" ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0xa9059cbb, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed" ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x23b872dd, from, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./ERC20Basic.sol"; interface ERC20 is ERC20Basic { function allowance(address owner, address spender) external view returns (uint256); function transferFrom( address from, address to, uint256 value ) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface ERC20Basic { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "../registry/ProxyRegistry.sol"; import "../libraries/TransferHelper.sol"; import "./ERC20.sol"; contract VindergoodTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; constructor(ProxyRegistry _registry) { require(address(_registry) != address(0), "INVALID REGISTRY"); registry = _registry; } /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom( address token, address from, address to, uint256 amount ) public { require(registry.contracts(msg.sender)); TransferHelper.safeTransferFrom(token, from, to, amount); } } /* Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions. */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./ProxyRegistry.sol"; import "./TokenRecipient.sol"; import "./proxy/OwnedUpgradeabilityStorage.sol"; /** * @title AuthenticatedProxy * @author Wyvern Protocol Developers */ contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize(address addrUser, ProxyRegistry addrRegistry) public { require(!initialized, "Authenticated proxy already initialized"); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require( msg.sender == user, "Authenticated proxy can only be revoked by its user" ); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param data Calldata to send * @return result Result of the call (success or failure) */ function proxy( address dest, HowToCall howToCall, bytes memory data ) public returns (bool result, bytes memory ret) { require( msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access" ); if (howToCall == HowToCall.Call) { (result, ret) = dest.call(data); } else if (howToCall == HowToCall.DelegateCall) { (result, ret) = dest.delegatecall(data); } } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param data Calldata to send */ function proxyAssert( address dest, HowToCall howToCall, bytes memory data ) public { (bool result, ) = proxy(dest, howToCall, data); require(result, "Proxy assertion failed"); } } /* OwnableDelegateProxy */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./proxy/OwnedUpgradeabilityProxy.sol"; /** * @title OwnableDelegateProxy * @author Wyvern Protocol Developers */ contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor( address owner, address initialImplementation, bytes memory data ) public { require(owner != address(0), "owner: zero address"); require( initialImplementation != address(0), "initialImplementation: zero address" ); setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); (bool success, ) = initialImplementation.delegatecall(data); require(success, "OwnableDelegateProxy failed implementation"); } } /* Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them. Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies. */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./OwnableDelegateProxy.sol"; import "./ProxyRegistryInterface.sol"; /** * @title ProxyRegistry * @author Wyvern Protocol Developers */ contract ProxyRegistry is OwnableUpgradeable, ProxyRegistryInterface { /* DelegateProxy implementation contract. Must be initialized. */ address public override delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public override proxies; /* Contracts pending access. */ mapping(address => uint256) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint256 public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication(address addr) public onlyOwner { require( !contracts[addr] && pending[addr] == 0, "Contract is already allowed in registry, or pending" ); pending[addr] = block.timestamp; } /** * End the process to enable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication(address addr) public onlyOwner { require( !contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp), "Contract is no longer pending or has already been approved by registry" ); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication(address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return proxy New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { return registerProxyFor(msg.sender); } /** * Register a proxy contract with this registry, overriding any existing proxy * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return proxy New AuthenticatedProxy contract */ function registerProxyOverride() public returns (OwnableDelegateProxy proxy) { proxy = new OwnableDelegateProxy( msg.sender, delegateProxyImplementation, abi.encodeWithSignature( "initialize(address,address)", msg.sender, address(this) ) ); proxies[msg.sender] = proxy; return proxy; } /** * Register a proxy contract with this registry * * @dev Can be called by any user * @return proxy New AuthenticatedProxy contract */ function registerProxyFor(address user) public returns (OwnableDelegateProxy proxy) { require( proxies[user] == OwnableDelegateProxy(0), "User already has a proxy" ); proxy = new OwnableDelegateProxy( user, delegateProxyImplementation, abi.encodeWithSignature( "initialize(address,address)", user, address(this) ) ); proxies[user] = proxy; return proxy; } /** * Transfer access */ function transferAccessTo(address from, address to) public { OwnableDelegateProxy proxy = proxies[from]; /* CHECKS */ require( OwnableDelegateProxy(msg.sender) == proxy, "Proxy transfer can only be called by the proxy" ); require( proxies[to] == OwnableDelegateProxy(0), "Proxy transfer has existing proxy as destination" ); /* EFFECTS */ delete proxies[from]; proxies[to] = proxy; } } /* Proxy registry interface. */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./OwnableDelegateProxy.sol"; /** * @title ProxyRegistryInterface * @author Wyvern Protocol Developers */ interface ProxyRegistryInterface { function delegateProxyImplementation() external returns (address); function proxies(address owner) external returns (OwnableDelegateProxy); } /* Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters). */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "../modules/ERC20.sol"; /** * @title TokenRecipient * @author Wyvern Protocol Developers */ contract TokenRecipient { event ReceivedEther(address indexed sender, uint256 amount); event ReceivedTokens( address indexed from, uint256 value, address indexed token, bytes extraData ); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval( address from, uint256 value, address token, bytes memory extraData ) public { ERC20 t = ERC20(token); require( t.transferFrom(from, address(this), value), "ERC20 token transfer failed" ); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ fallback() external payable { emit ReceivedEther(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./Proxy.sol"; import "./OwnedUpgradeabilityStorage.sol"; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view override returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return proxyTypeId Proxy type, 2 for forwarding proxy */ function proxyType() public pure override returns (uint256 proxyTypeId) { return 2; } /** * @dev Upgrades the implementation address * @param implementation_ representing the address of the new implementation to be set */ function _upgradeTo(address implementation_) internal { require( _implementation != implementation_, "Proxy already uses this implementation" ); _implementation = implementation_; emit Upgraded(implementation_); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require( msg.sender == proxyOwner(), "Only the proxy owner can call this method" ); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "New owner cannot be the null address"); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation_ representing the address of the new implementation to be set. */ function upgradeTo(address implementation_) public onlyProxyOwner { _upgradeTo(implementation_); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation_ representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation_, bytes memory data) public payable onlyProxyOwner { upgradeTo(implementation_); (bool success, ) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @title OwnedUpgradeabilityStorage * @dev This contract keeps track of the upgradeability owner */ contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return proxyTypeId Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure virtual returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { address _impl = implementation(); require(_impl != address(0), "Proxy implementation required"); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "../libraries/LibPart.sol"; interface RoyaltiesV2 { event RoyaltiesSet(uint256 tokenId, LibPart.Part royalties); function getVindergoodV2Royalties(uint256 id) external view returns (LibPart.Part memory); }
Unsafe write uint into a memory location index Memory location source uint to write return End memory index/
function unsafeWriteUint(uint256 index, uint256 source) internal pure returns (uint256) { assembly { mstore(index, source) index := add(index, 0x20) } return index; }
14,408,353
./full_match/11155111/0xE46FE78DBfCa5E835667Ba9dCd3F3315E7623F8a/sources/contracts/AllowanceModule.sol
Allows to add a delegate. delegate Delegate that should be added. We have a collision for the indices of delegates Delegate already exists, nothing to do
function addDelegate(address delegate) public { uint48 index = uint48(delegate); require(index != uint(0), "index != uint(0)"); address currentDelegate = delegates[msg.sender][index].delegate; if (currentDelegate != address(0)) { require(currentDelegate == delegate, "currentDelegate == delegate"); return; } uint48 startIndex = delegatesStart[msg.sender]; delegates[msg.sender][index] = Delegate(delegate, 0, startIndex); delegates[msg.sender][startIndex].prev = index; delegatesStart[msg.sender] = index; emit AddDelegate(msg.sender, delegate); }
3,835,139
//Address: 0x7268f9c2bc9c9e65b4a16888cb5672531ce8e945 //Contract name: DayToken //Balance: 0 Ether //Verification Date: 9/15/2017 //Transacion Count: 4246 // CODE STARTS HERE pragma solidity ^0.4.13; ////////////////// >>>>> Wallet Contract <<<<< /////////////////// /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { if (msg.sender != address(this)) throw; _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) throw; _; } modifier ownerExists(address owner) { if (!isOwner[owner]) throw; _; } modifier transactionExists(uint transactionId) { if (transactions[transactionId].destination == 0) throw; _; } modifier confirmed(uint transactionId, address owner) { if (!confirmations[transactionId][owner]) throw; _; } modifier notConfirmed(uint transactionId, address owner) { if (confirmations[transactionId][owner]) throw; _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) throw; _; } modifier notNull(address _address) { if (_address == 0) throw; _; } modifier validRequirement(uint ownerCount, uint _required) { if ( ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) throw; _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == 0) throw; isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction tx = transactions[transactionId]; tx.executed = true; if (tx.destination.call.value(tx.value)(tx.data)) Execution(transactionId); else { ExecutionFailure(transactionId); tx.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } ////////////////// >>>>> Library Contracts <<<<< /////////////////// contract SafeMathLib { function safeMul(uint a, uint b) constant returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) constant returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) constant returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } ////////////////// >>>>> Token Contracts <<<<< /////////////////// /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) constant returns (uint remaining); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to] ) { balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } else{ return false; } } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value // From a/c has balance && _allowance >= _value // Transfer approved && _value > 0 // Non-zero transfer && balances[_to] + _value > balances[_to] // Overflow check ){ balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(_allowance,_value); Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // 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; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. * If false we are are in transfer lock up period. */ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. * These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. */ modifier canTransfer(address _sender) { if (!released) { require(transferAgents[_sender]); } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. * It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. * This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of their tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)); // Validate input value. require(value!=0); balances[msg.sender] = safeSub(balances[msg.sender],value); // Take tokens out from circulation totalSupply = safeSub(totalSupply,value); totalUpgraded = safeAdd(totalUpgraded,value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); // Only a master can designate the next agent require(msg.sender == upgradeMaster); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } /** * A crowdsale token. * * An ERC-20 token designed specifically for crowdsales with investor protection and * further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through approve() mechanism * - The token can be capped (supply set in the constructor) * or uncapped (crowdsale contract can mint new tokens) */ contract DayToken is ReleasableToken, MintableToken, UpgradeableToken { enum sellingStatus {NOTONSALE, EXPIRED, ONSALE} /** Basic structure for a contributor with a minting Address * adr address of the contributor * initialContributionDay initial contribution of the contributor in wei * lastUpdatedOn day count from Minting Epoch when the account balance was last updated * mintingPower Initial Minting power of the address * expiryBlockNumber Variable to mark end of Minting address sale. Set by user * minPriceInDay minimum price of Minting address in Day tokens. Set by user * status Selling status Variable for transfer Minting address. * sellingPriceInDay Variable for transfer Minting address. Price at which the address is actually sold */ struct Contributor { address adr; uint256 initialContributionDay; uint256 lastUpdatedOn; //Day from Minting Epoch uint256 mintingPower; uint expiryBlockNumber; uint256 minPriceInDay; sellingStatus status; } /* Stores maximum days for which minting will happen since minting epoch */ uint256 public maxMintingDays = 1095; /* Mapping to store id of each minting address */ mapping (address => uint) public idOf; /* Mapping from id of each minting address to their respective structures */ mapping (uint256 => Contributor) public contributors; /* mapping to store unix timestamp of when the minting address is issued to each team member */ mapping (address => uint256) public teamIssuedTimestamp; mapping (address => bool) public soldAddresses; mapping (address => uint256) public sellingPriceInDayOf; /* Stores the id of the first contributor */ uint256 public firstContributorId; /* Stores total Pre + Post ICO TimeMints */ uint256 public totalNormalContributorIds; /* Stores total Normal TimeMints allocated */ uint256 public totalNormalContributorIdsAllocated = 0; /* Stores the id of the first team TimeMint */ uint256 public firstTeamContributorId; /* Stores the total team TimeMints */ uint256 public totalTeamContributorIds; /* Stores total team TimeMints allocated */ uint256 public totalTeamContributorIdsAllocated = 0; /* Stores the id of the first Post ICO contributor (for auctionable TimeMints) */ uint256 public firstPostIcoContributorId; /* Stores total Post ICO TimeMints (for auction) */ uint256 public totalPostIcoContributorIds; /* Stores total Auction TimeMints allocated */ uint256 public totalPostIcoContributorIdsAllocated = 0; /* Maximum number of address */ uint256 public maxAddresses; /* Min Minting power with 19 decimals: 0.5% : 5000000000000000000 */ uint256 public minMintingPower; /* Max Minting power with 19 decimals: 1% : 10000000000000000000 */ uint256 public maxMintingPower; /* Halving cycle in days (88) */ uint256 public halvingCycle; /* Unix timestamp when minting is to be started */ uint256 public initialBlockTimestamp; /* Flag to prevent setting initialBlockTimestamp more than once */ bool public isInitialBlockTimestampSet; /* number of decimals in minting power */ uint256 public mintingDec; /* Minimum Balance in Day tokens required to sell a minting address */ uint256 public minBalanceToSell; /* Team address lock down period from issued time, in seconds */ uint256 public teamLockPeriodInSec; //Initialize and set function /* Duration in secs that we consider as a day. (For test deployment purposes, if we want to decrease length of a day. default: 84600)*/ uint256 public DayInSecs; event UpdatedTokenInformation(string newName, string newSymbol); event MintingAdrTransferred(uint id, address from, address to); event ContributorAdded(address adr, uint id); event TimeMintOnSale(uint id, address seller, uint minPriceInDay, uint expiryBlockNumber); event TimeMintSold(uint id, address buyer, uint offerInDay); event PostInvested(address investor, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId); event TeamAddressAdded(address teamAddress, uint id); // Tell us invest was success event Invested(address receiver, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId); modifier onlyContributor(uint id){ require(isValidContributorId(id)); _; } string public name; string public symbol; uint8 public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? */ function DayToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals, bool _mintable, uint _maxAddresses, uint _firstTeamContributorId, uint _totalTeamContributorIds, uint _totalPostIcoContributorIds, uint256 _minMintingPower, uint256 _maxMintingPower, uint _halvingCycle, uint256 _minBalanceToSell, uint256 _dayInSecs, uint256 _teamLockPeriodInSec) UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply; maxAddresses = _maxAddresses; require(maxAddresses > 1); // else division by zero will occur in setInitialMintingPowerOf firstContributorId = 1; totalNormalContributorIds = maxAddresses - _totalTeamContributorIds - _totalPostIcoContributorIds; // check timeMint total is sane require(totalNormalContributorIds >= 1); firstTeamContributorId = _firstTeamContributorId; totalTeamContributorIds = _totalTeamContributorIds; totalPostIcoContributorIds = _totalPostIcoContributorIds; // calculate first contributor id to be auctioned post ICO firstPostIcoContributorId = maxAddresses - totalPostIcoContributorIds + 1; minMintingPower = _minMintingPower; maxMintingPower = _maxMintingPower; halvingCycle = _halvingCycle; // setting future date far far away, year 2020, // call setInitialBlockTimestamp to set proper timestamp initialBlockTimestamp = 1577836800; isInitialBlockTimestampSet = false; // use setMintingDec to change this mintingDec = 19; minBalanceToSell = _minBalanceToSell; DayInSecs = _dayInSecs; teamLockPeriodInSec = _teamLockPeriodInSec; if (totalSupply > 0) { Minted(owner, totalSupply); } if (!_mintable) { mintingFinished = true; require(totalSupply != 0); } } /** * Used to set timestamp at which minting power of TimeMints is activated * Can be called only by owner * @param _initialBlockTimestamp timestamp to be set. */ function setInitialBlockTimestamp(uint _initialBlockTimestamp) internal onlyOwner { require(!isInitialBlockTimestampSet); isInitialBlockTimestampSet = true; initialBlockTimestamp = _initialBlockTimestamp; } /** * check if mintining power is activated and Day token and Timemint transfer is enabled */ function isDayTokenActivated() constant returns (bool isActivated) { return (block.timestamp >= initialBlockTimestamp); } /** * to check if an id is a valid contributor * @param _id contributor id to check. */ function isValidContributorId(uint _id) constant returns (bool isValidContributor) { return (_id > 0 && _id <= maxAddresses && contributors[_id].adr != 0 && idOf[contributors[_id].adr] == _id); // cross checking } /** * to check if an address is a valid contributor * @param _address contributor address to check. */ function isValidContributorAddress(address _address) constant returns (bool isValidContributor) { return isValidContributorId(idOf[_address]); } /** * In case of Team address check if lock-in period is over (returns true for all non team addresses) * @param _address team address to check lock in period for. */ function isTeamLockInPeriodOverIfTeamAddress(address _address) constant returns (bool isLockInPeriodOver) { isLockInPeriodOver = true; if (teamIssuedTimestamp[_address] != 0) { if (block.timestamp - teamIssuedTimestamp[_address] < teamLockPeriodInSec) isLockInPeriodOver = false; } return isLockInPeriodOver; } /** * Used to set mintingDec * Can be called only by owner * @param _mintingDec bounty to be set. */ function setMintingDec(uint256 _mintingDec) onlyOwner { require(!isInitialBlockTimestampSet); mintingDec = _mintingDec; } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyOwner { require(isInitialBlockTimestampSet); mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here */ function setTokenInformation(string _name, string _symbol) onlyOwner { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } /** * Returns the current phase. * Note: Phase starts with 1 * @param _day Number of days since Minting Epoch */ function getPhaseCount(uint _day) public constant returns (uint phase) { phase = (_day/halvingCycle) + 1; return (phase); } /** * Returns current day number since minting epoch * or zero if initialBlockTimestamp is in future or its DayZero. */ function getDayCount() public constant returns (uint daySinceMintingEpoch) { daySinceMintingEpoch = 0; if (isDayTokenActivated()) daySinceMintingEpoch = (block.timestamp - initialBlockTimestamp)/DayInSecs; return daySinceMintingEpoch; } /** * Calculates and Sets the minting power of a particular id. * Called before Minting Epoch by constructor * @param _id id of the address whose minting power is to be set. */ function setInitialMintingPowerOf(uint256 _id) internal onlyContributor(_id) { contributors[_id].mintingPower = (maxMintingPower - ((_id-1) * (maxMintingPower - minMintingPower)/(maxAddresses-1))); } /** * Returns minting power of a particular id. * @param _id Contribution id whose minting power is to be returned */ function getMintingPowerById(uint _id) public constant returns (uint256 mintingPower) { return contributors[_id].mintingPower/(2**(getPhaseCount(getDayCount())-1)); } /** * Returns minting power of a particular address. * @param _adr Address whose minting power is to be returned */ function getMintingPowerByAddress(address _adr) public constant returns (uint256 mintingPower) { return getMintingPowerById(idOf[_adr]); } /** * Calculates and returns the balance based on the minting power, day and phase. * Can only be called internally * Can calculate balance based on last updated. * @param _id id whose balnce is to be calculated * @param _dayCount day count upto which balance is to be updated */ function availableBalanceOf(uint256 _id, uint _dayCount) internal returns (uint256) { uint256 balance = balances[contributors[_id].adr]; uint maxUpdateDays = _dayCount < maxMintingDays ? _dayCount : maxMintingDays; uint i = contributors[_id].lastUpdatedOn + 1; while(i <= maxUpdateDays) { uint phase = getPhaseCount(i); uint phaseEndDay = phase * halvingCycle - 1; // as first day is 0 uint constantFactor = contributors[_id].mintingPower / 2**(phase-1); for (uint j = i; j <= phaseEndDay && j <= maxUpdateDays; j++) { balance = safeAdd( balance, constantFactor * balance / 10**(mintingDec + 2) ); } i = j; } return balance; } /** * Updates the balance of the specified id in its structure and also in the balances[] mapping. * returns true if successful. * Only for internal calls. Not public. * @param _id id whose balance is to be updated. */ function updateBalanceOf(uint256 _id) internal returns (bool success) { // check if its contributor if (isValidContributorId(_id)) { uint dayCount = getDayCount(); // proceed only if not already updated today if (contributors[_id].lastUpdatedOn != dayCount && contributors[_id].lastUpdatedOn < maxMintingDays) { address adr = contributors[_id].adr; uint oldBalance = balances[adr]; totalSupply = safeSub(totalSupply, oldBalance); uint newBalance = availableBalanceOf(_id, dayCount); balances[adr] = newBalance; totalSupply = safeAdd(totalSupply, newBalance); contributors[_id].lastUpdatedOn = dayCount; Transfer(0, adr, newBalance - oldBalance); return true; } } return false; } /** * Standard ERC20 function overridden. * Returns the balance of the specified address. * Calculates the balance on fly only if it is a minting address else * simply returns balance from balances[] mapping. * For public calls. * @param _adr address whose balance is to be returned. */ function balanceOf(address _adr) constant returns (uint balance) { uint id = idOf[_adr]; if (id != 0) return balanceById(id); else return balances[_adr]; } /** * Standard ERC20 function overridden. * Returns the balance of the specified id. * Calculates the balance on fly only if it is a minting address else * simply returns balance from balances[] mapping. * For public calls. * @param _id address whose balance is to be returned. */ function balanceById(uint _id) public constant returns (uint256 balance) { address adr = contributors[_id].adr; if (isDayTokenActivated()) { if (isValidContributorId(_id)) { return ( availableBalanceOf(_id, getDayCount()) ); } } return balances[adr]; } /** * Returns totalSupply of DAY tokens. */ function getTotalSupply() public constant returns (uint) { return totalSupply; } /** Function to update balance of a Timemint * returns true if balance updated, false otherwise * @param _id TimeMint to update */ function updateTimeMintBalance(uint _id) public returns (bool) { require(isDayTokenActivated()); return updateBalanceOf(_id); } /** Function to update balance of sender's Timemint * returns true if balance updated, false otherwise */ function updateMyTimeMintBalance() public returns (bool) { require(isDayTokenActivated()); return updateBalanceOf(idOf[msg.sender]); } /** * Standard ERC20 function overidden. * Used to transfer day tokens from caller's address to another * @param _to address to which Day tokens are to be transferred * @param _value Number of Day tokens to be transferred */ function transfer(address _to, uint _value) public returns (bool success) { require(isDayTokenActivated()); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(msg.sender)); updateBalanceOf(idOf[msg.sender]); // Check sender account has enough balance and transfer amount is non zero require ( balanceOf(msg.sender) >= _value && _value != 0 ); updateBalanceOf(idOf[_to]); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } /** * Standard ERC20 Standard Token function overridden. Added Team address vesting period lock. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(isDayTokenActivated()); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(_from)); uint _allowance = allowed[_from][msg.sender]; updateBalanceOf(idOf[_from]); // Check from account has enough balance, transfer amount is non zero // and _value is allowed to be transferred require ( balanceOf(_from) >= _value && _value != 0 && _value <= _allowance); updateBalanceOf(idOf[_to]); allowed[_from][msg.sender] = safeSub(_allowance, _value); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } /** * Add any contributor structure (For every kind of contributors: Team/Pre-ICO/ICO/Test) * @param _adr Address of the contributor to be added * @param _initialContributionDay Initial Contribution of the contributor to be added */ function addContributor(uint contributorId, address _adr, uint _initialContributionDay) internal onlyOwner { require(contributorId <= maxAddresses); //address should not be an existing contributor require(!isValidContributorAddress(_adr)); //TimeMint should not be already allocated require(!isValidContributorId(contributorId)); contributors[contributorId].adr = _adr; idOf[_adr] = contributorId; setInitialMintingPowerOf(contributorId); contributors[contributorId].initialContributionDay = _initialContributionDay; contributors[contributorId].lastUpdatedOn = getDayCount(); ContributorAdded(_adr, contributorId); contributors[contributorId].status = sellingStatus.NOTONSALE; } /** Function to be called by minting addresses in order to sell their address * @param _minPriceInDay Minimum price in DAY tokens set by the seller * @param _expiryBlockNumber Expiry Block Number set by the seller */ function sellMintingAddress(uint256 _minPriceInDay, uint _expiryBlockNumber) public returns (bool) { require(isDayTokenActivated()); require(_expiryBlockNumber > block.number); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(msg.sender)); uint id = idOf[msg.sender]; require(contributors[id].status == sellingStatus.NOTONSALE); // update balance of sender address before checking for minimum required balance updateBalanceOf(id); require(balances[msg.sender] >= minBalanceToSell); contributors[id].minPriceInDay = _minPriceInDay; contributors[id].expiryBlockNumber = _expiryBlockNumber; contributors[id].status = sellingStatus.ONSALE; balances[msg.sender] = safeSub(balances[msg.sender], minBalanceToSell); balances[this] = safeAdd(balances[this], minBalanceToSell); Transfer(msg.sender, this, minBalanceToSell); TimeMintOnSale(id, msg.sender, contributors[id].minPriceInDay, contributors[id].expiryBlockNumber); return true; } /** Function to be called by minting address in order to cancel the sale of their TimeMint */ function cancelSaleOfMintingAddress() onlyContributor(idOf[msg.sender]) public { uint id = idOf[msg.sender]; // TimeMint should be on sale require(contributors[id].status == sellingStatus.ONSALE); contributors[id].status = sellingStatus.EXPIRED; } /** Function to be called by any user to get a list of all On Sale TimeMints */ function getOnSaleIds() constant public returns(uint[]) { uint[] memory idsOnSale = new uint[](maxAddresses); uint j = 0; for(uint i=1; i <= maxAddresses; i++) { if ( isValidContributorId(i) && block.number <= contributors[i].expiryBlockNumber && contributors[i].status == sellingStatus.ONSALE ) { idsOnSale[j] = i; j++; } } return idsOnSale; } /** Function to be called by any user to get status of a Time Mint. * returns status 0 - Not on sale, 1 - Expired, 2 - On sale, * @param _id ID number of the Time Mint */ function getSellingStatus(uint _id) constant public returns(sellingStatus status) { require(isValidContributorId(_id)); status = contributors[_id].status; if ( block.number > contributors[_id].expiryBlockNumber && status == sellingStatus.ONSALE ) status = sellingStatus.EXPIRED; return status; } /** Function to be called by any user to buy a onsale address by offering an amount * @param _offerId ID number of the address to be bought by the buyer * @param _offerInDay Offer given by the buyer in number of DAY tokens */ function buyMintingAddress(uint _offerId, uint256 _offerInDay) public returns(bool) { if (contributors[_offerId].status == sellingStatus.ONSALE && block.number > contributors[_offerId].expiryBlockNumber) { contributors[_offerId].status = sellingStatus.EXPIRED; } address soldAddress = contributors[_offerId].adr; require(contributors[_offerId].status == sellingStatus.ONSALE); require(_offerInDay >= contributors[_offerId].minPriceInDay); // prevent seller from cancelling sale in between contributors[_offerId].status = sellingStatus.NOTONSALE; // first get the offered DayToken in the token contract & // then transfer the total sum (minBalanceToSend+_offerInDay) to the seller balances[msg.sender] = safeSub(balances[msg.sender], _offerInDay); balances[this] = safeAdd(balances[this], _offerInDay); Transfer(msg.sender, this, _offerInDay); if(transferMintingAddress(contributors[_offerId].adr, msg.sender)) { //mark the offer as sold & let seller pull the proceed to their own account. sellingPriceInDayOf[soldAddress] = _offerInDay; soldAddresses[soldAddress] = true; TimeMintSold(_offerId, msg.sender, _offerInDay); } return true; } /** * Transfer minting address from one user to another * Gives the transfer-to address, the id of the original address * returns true if successful and false if not. * @param _to address of the user to which minting address is to be tranferred */ function transferMintingAddress(address _from, address _to) internal onlyContributor(idOf[_from]) returns (bool) { require(isDayTokenActivated()); // _to should be non minting address require(!isValidContributorAddress(_to)); uint id = idOf[_from]; // update balance of from address before transferring minting power updateBalanceOf(id); contributors[id].adr = _to; idOf[_to] = id; idOf[_from] = 0; contributors[id].initialContributionDay = 0; // needed as id is assigned to new address contributors[id].lastUpdatedOn = getDayCount(); contributors[id].expiryBlockNumber = 0; contributors[id].minPriceInDay = 0; MintingAdrTransferred(id, _from, _to); return true; } /** Function to allow seller to get back their deposited amount of day tokens(minBalanceToSell) and * offer made by buyer after successful sale. * Throws if sale is not successful */ function fetchSuccessfulSaleProceed() public returns(bool) { require(soldAddresses[msg.sender] == true); // to prevent re-entrancy attack soldAddresses[msg.sender] = false; uint saleProceed = safeAdd(minBalanceToSell, sellingPriceInDayOf[msg.sender]); balances[this] = safeSub(balances[this], saleProceed); balances[msg.sender] = safeAdd(balances[msg.sender], saleProceed); Transfer(this, msg.sender, saleProceed); return true; } /** Function that lets a seller get their deposited day tokens (minBalanceToSell) back, if no buyer turns up. * Allowed only after expiryBlockNumber * Throws if any other state other than EXPIRED */ function refundFailedAuctionAmount() onlyContributor(idOf[msg.sender]) public returns(bool){ uint id = idOf[msg.sender]; if(block.number > contributors[id].expiryBlockNumber && contributors[id].status == sellingStatus.ONSALE) { contributors[id].status = sellingStatus.EXPIRED; } require(contributors[id].status == sellingStatus.EXPIRED); // reset selling status contributors[id].status = sellingStatus.NOTONSALE; balances[this] = safeSub(balances[this], minBalanceToSell); // update balance of seller address before refunding updateBalanceOf(id); balances[msg.sender] = safeAdd(balances[msg.sender], minBalanceToSell); contributors[id].minPriceInDay = 0; contributors[id].expiryBlockNumber = 0; Transfer(this, msg.sender, minBalanceToSell); return true; } /** Function to add a team address as a contributor and store it's time issued to calculate vesting period * Called by owner */ function addTeamTimeMints(address _adr, uint _id, uint _tokens, bool _isTest) public onlyOwner { //check if Id is in range of team Ids require(_id >= firstTeamContributorId && _id < firstTeamContributorId + totalTeamContributorIds); require(totalTeamContributorIdsAllocated < totalTeamContributorIds); addContributor(_id, _adr, 0); totalTeamContributorIdsAllocated++; // enforce lockin period if not test address if(!_isTest) teamIssuedTimestamp[_adr] = block.timestamp; mint(_adr, _tokens); TeamAddressAdded(_adr, _id); } /** Function to add reserved aution TimeMints post-ICO. Only by owner * @param _receiver Address of the minting to be added * @param _customerId Server side id of the customer * @param _id contributorId */ function postAllocateAuctionTimeMints(address _receiver, uint _customerId, uint _id) public onlyOwner { //check if Id is in range of Auction Ids require(_id >= firstPostIcoContributorId && _id < firstPostIcoContributorId + totalPostIcoContributorIds); require(totalPostIcoContributorIdsAllocated < totalPostIcoContributorIds); require(released == true); addContributor(_id, _receiver, 0); totalPostIcoContributorIdsAllocated++; PostInvested(_receiver, 0, 0, _customerId, _id); } /** Function to add all contributors except team, test and Auctions TimeMints. Only by owner * @param _receiver Address of the minting to be added * @param _customerId Server side id of the customer * @param _id contributor id * @param _tokens day tokens to allocate * @param _weiAmount ether invested in wei */ function allocateNormalTimeMints(address _receiver, uint _customerId, uint _id, uint _tokens, uint _weiAmount) public onlyOwner { // check if Id is in range of Normal Ids require(_id >= firstContributorId && _id <= totalNormalContributorIds); require(totalNormalContributorIdsAllocated < totalNormalContributorIds); addContributor(_id, _receiver, _tokens); totalNormalContributorIdsAllocated++; mint(_receiver, _tokens); Invested(_receiver, _weiAmount, _tokens, _customerId, _id); } /** Function to release token * Called by owner */ function releaseToken(uint _initialBlockTimestamp) public onlyOwner { require(!released); // check not already released setInitialBlockTimestamp(_initialBlockTimestamp); // Make token transferable releaseTokenTransfer(); } }
Used to set mintingDec Can be called only by owner _mintingDec bounty to be set./
function setMintingDec(uint256 _mintingDec) onlyOwner { require(!isInitialBlockTimestampSet); mintingDec = _mintingDec; }
1,800,531
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeDecimalMath} from "./SafeDecimalMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./lib/FixedPoint.sol"; import "./Owned.sol"; import "./Pausable.sol"; import "./interfaces/IConjure.sol"; contract EtherCollateral is ReentrancyGuard, Owned, Pausable { using SafeMath for uint256; using SafeDecimalMath for uint256; // ========== CONSTANTS ========== uint256 internal constant ONE_THOUSAND = 1e18 * 1000; uint256 internal constant ONE_HUNDRED = 1e18 * 100; uint256 internal constant ACCOUNT_LOAN_LIMIT_CAP = 1000; // ========== SETTER STATE VARIABLES ========== // The ratio of Collateral to synths issued uint256 public collateralizationRatio = SafeDecimalMath.unit() * 120; // Minting fee for issuing the synths. Default 50 bips. uint256 public issueFeeRate; // Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 0.05 ETH uint256 public minLoanCollateralSize = SafeDecimalMath.unit() / 20; // Maximum number of loans an account can create uint256 public accountLoanLimit = 50; // Time when remaining loans can be liquidated uint256 public liquidationDeadline; // Liquidation ratio when loans can be liquidated uint256 public liquidationRatio = (120 * SafeDecimalMath.unit()) / 100; // 1.2 ratio // Liquidation penalty when loans are liquidated. default 10% uint256 public liquidationPenalty = SafeDecimalMath.unit() / 10; // ========== STATE VARIABLES ========== // The total number of synths issued by the collateral in this contract uint256 public totalIssuedSynths; // Total number of loans ever created uint256 public totalLoansCreated; // Total number of open loans uint256 public totalOpenLoanCount; // Synth loan storage struct struct SynthLoanStruct { // Acccount that created the loan address payable account; // Amount (in collateral token ) that they deposited uint256 collateralAmount; // Amount (in synths) that they issued to borrow uint256 loanAmount; // Minting Fee uint256 mintingFee; // When the loan was created uint256 timeCreated; // ID for the loan uint256 loanID; // When the loan was paidback (closed) uint256 timeClosed; } // Users Loans by address mapping(address => SynthLoanStruct[]) public accountsSynthLoans; // Account Open Loan Counter mapping(address => uint256) public accountOpenLoanCounter; address payable public arbasset; address public factoryaddress; // ========== CONSTRUCTOR ========== constructor(address payable _asset, address _owner, address _factoryaddress, uint256 _mintingfeerate ) Owned(_owner) public { arbasset = _asset; factoryaddress = _factoryaddress; issueFeeRate = _mintingfeerate; // max 2.5% fee for minting require(_mintingfeerate <= 250); } // ========== SETTERS ========== function setCollateralizationRatio(uint256 ratio) external onlyOwner { require(ratio <= ONE_THOUSAND, "Too high"); require(ratio >= ONE_HUNDRED, "Too low"); collateralizationRatio = ratio; emit CollateralizationRatioUpdated(ratio); } function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { // max 2.5% fee for minting require(_issueFeeRate <= 250); issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } function setMinLoanCollateralSize(uint256 _minLoanCollateralSize) external onlyOwner { minLoanCollateralSize = _minLoanCollateralSize; emit MinLoanCollateralSizeUpdated(minLoanCollateralSize); } function setAccountLoanLimit(uint256 _loanLimit) external onlyOwner { require(_loanLimit < ACCOUNT_LOAN_LIMIT_CAP, "Owner cannot set higher than ACCOUNT_LOAN_LIMIT_CAP"); accountLoanLimit = _loanLimit; emit AccountLoanLimitUpdated(accountLoanLimit); } function setLiquidationRatio(uint256 _liquidationRatio) external onlyOwner { require(_liquidationRatio > SafeDecimalMath.unit(), "Ratio less than 100%"); liquidationRatio = _liquidationRatio; emit LiquidationRatioUpdated(liquidationRatio); } function getContractInfo() external view returns ( uint256 _collateralizationRatio, uint256 _issuanceRatio, uint256 _issueFeeRate, uint256 _minLoanCollateralSize, uint256 _totalIssuedSynths, uint256 _totalLoansCreated, uint256 _totalOpenLoanCount, uint256 _ethBalance, uint256 _liquidationDeadline ) { _collateralizationRatio = collateralizationRatio; _issuanceRatio = issuanceRatio(); _issueFeeRate = issueFeeRate; _minLoanCollateralSize = minLoanCollateralSize; _totalIssuedSynths = totalIssuedSynths; _totalLoansCreated = totalLoansCreated; _totalOpenLoanCount = totalOpenLoanCount; _ethBalance = address(this).balance; _liquidationDeadline = liquidationDeadline; } // returns value of 100 / collateralizationRatio. // e.g. 100/150 = 0.6666666667 function issuanceRatio() public view returns (uint256) { // this rounds so you get slightly more rather than slightly less return ONE_HUNDRED.divideDecimalRound(collateralizationRatio); } function loanAmountFromCollateral(uint256 collateralAmount) public returns (uint256) { uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); return collateralAmount.multiplyDecimal(issuanceRatio()).multiplyDecimal(currentethusdprice).divideDecimal(currentprice); } function collateralAmountForLoan(uint256 loanAmount) public returns (uint256) { uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); return loanAmount .multiplyDecimal(collateralizationRatio.divideDecimalRound(currentethusdprice).multiplyDecimal(currentprice)) .divideDecimalRound(ONE_HUNDRED); } function getMintingFee(address _account, uint256 _loanID) external view returns (uint256) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); return synthLoan.mintingFee; } /** * r = target issuance ratio * D = debt balance * V = Collateral * P = liquidation penalty * Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r) */ function calculateAmountToLiquidate(uint debtBalance, uint collateral) public view returns (uint) { uint unit = SafeDecimalMath.unit(); uint ratio = liquidationRatio; uint dividend = debtBalance.sub(collateral.divideDecimal(ratio)); uint divisor = unit.sub(unit.add(liquidationPenalty).divideDecimal(ratio)); return dividend.divideDecimal(divisor); } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } // Create the fixed size array to return uint256[] memory _result = new uint256[](_counter); // Copy loanIDs from dynamic array to fixed array for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } // Return an array with list of open Loan IDs return _result; } function getLoan(address _account, uint256 _loanID) external view returns ( address account, uint256 collateralAmount, uint256 loanAmount, uint256 timeCreated, uint256 loanID, uint256 timeClosed, uint256 totalFees ) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); account = synthLoan.account; collateralAmount = synthLoan.collateralAmount; loanAmount = synthLoan.loanAmount; timeCreated = synthLoan.timeCreated; loanID = synthLoan.loanID; timeClosed = synthLoan.timeClosed; totalFees = synthLoan.mintingFee; } function getLoanCollateralRatio(address _account, uint256 _loanID) external view returns (uint256 loanCollateralRatio) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); (loanCollateralRatio, ) = _loanCollateralRatio(synthLoan); } function _loanCollateralRatio(SynthLoanStruct memory _loan) internal view returns ( uint256 loanCollateralRatio, uint256 collateralValue ) { uint256 loanAmountWithAccruedInterest = _loan.loanAmount.multiplyDecimal(IConjure(arbasset).getLatestPrice()); collateralValue = _loan.collateralAmount.multiplyDecimal(uint(IConjure(arbasset).getLatestETHUSDPrice())); loanCollateralRatio = collateralValue.divideDecimal(loanAmountWithAccruedInterest); } // ========== PUBLIC FUNCTIONS ========== function openLoan(uint256 _loanAmount) external payable notPaused nonReentrant returns (uint256 loanID) { // Require ETH sent to be greater than minLoanCollateralSize require( msg.value >= minLoanCollateralSize, "Not enough ETH to create this loan. Please see the minLoanCollateralSize" ); // Each account is limited to creating 50 (accountLoanLimit) loans require(accountsSynthLoans[msg.sender].length < accountLoanLimit, "Each account is limited to 50 loans"); // Calculate issuance amount based on issuance ratio uint256 maxLoanAmount = loanAmountFromCollateral(msg.value); // Require requested _loanAmount to be less than maxLoanAmount // Issuance ratio caps collateral to loan value at 120% require(_loanAmount <= maxLoanAmount, "Loan amount exceeds max borrowing power"); uint256 ethforloan = collateralAmountForLoan(_loanAmount); uint256 mintingFee = _calculateMintingFee(msg.value); require(msg.value >= ethforloan + mintingFee); // Get a Loan ID loanID = _incrementTotalLoansCounter(); // Create Loan storage object SynthLoanStruct memory synthLoan = SynthLoanStruct({ account: msg.sender, collateralAmount: msg.value - mintingFee, loanAmount: _loanAmount, mintingFee: mintingFee, timeCreated: block.timestamp, loanID: loanID, timeClosed: 0 }); // Record loan in mapping to account in an array of the accounts open loans accountsSynthLoans[msg.sender].push(synthLoan); // Increment totalIssuedSynths totalIssuedSynths = totalIssuedSynths.add(_loanAmount); // Issue the synth (less fee) syntharb().mint(msg.sender, _loanAmount); // Fee distribution. Mint the fees into the FeePool and record fees paid if (mintingFee > 0) { // calculate back factory owner fee is 0.25 on top of creator fee arbasset.transfer(mintingFee / 4 * 3); address payable factoryowner = IFactoryAddress(factoryaddress).getFactoryOwner(); factoryowner.transfer(mintingFee / 4); } // Tell the Dapps a loan was created emit LoanCreated(msg.sender, loanID, _loanAmount); } function closeLoan(uint256 loanID) external nonReentrant { _closeLoan(msg.sender, loanID, false); } // Add ETH collateral to an open loan function depositCollateral(address account, uint256 loanID) external payable notPaused { require(msg.value > 0, "Deposit amount must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 totalCollateral = synthLoan.collateralAmount.add(msg.value); _updateLoanCollateral(synthLoan, totalCollateral); // Tell the Dapps collateral was added to loan emit CollateralDeposited(account, loanID, msg.value, totalCollateral); } // Withdraw ETH collateral from an open loan function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external notPaused nonReentrant { require(withdrawAmount > 0, "Amount to withdraw must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(msg.sender, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 collateralAfter = synthLoan.collateralAmount.sub(withdrawAmount); SynthLoanStruct memory loanAfter = _updateLoanCollateral(synthLoan, collateralAfter); // require collateral ratio after to be above the liquidation ratio (uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter); require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw"); // transfer ETH to msg.sender msg.sender.transfer(withdrawAmount); // Tell the Dapps collateral was added to loan emit CollateralWithdrawn(msg.sender, loanID, withdrawAmount, loanAfter.collateralAmount); } function repayLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _repayAmount ) external { // check msg.sender has sufficient funds to pay require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _repayAmount, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); ( uint256 loanAmountPaid, uint256 loanAmountAfter ) = _splitInterestLoanPayment(_repayAmount, synthLoan.loanAmount); // burn funds from msg.sender for repaid amount syntharb().burn(msg.sender, _repayAmount); // Send interest paid to fee pool and record loan amount paid _processInterestAndLoanPayment(loanAmountPaid); // update loan with new total loan amount, record accrued interests _updateLoan(synthLoan, loanAmountAfter); emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter); } // Liquidate loans at or below issuance ratio function liquidateLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _debtToCover ) external nonReentrant { // check msg.sender (liquidator's wallet) has sufficient require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _debtToCover, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); (uint256 collateralRatio, uint256 collateralValue) = _loanCollateralRatio(synthLoan); require(collateralRatio < liquidationRatio, "Collateral ratio above liquidation ratio"); // calculate amount to liquidate to fix ratio including accrued interest uint256 liquidationAmount = calculateAmountToLiquidate( synthLoan.loanAmount, collateralValue ); // cap debt to liquidate uint256 amountToLiquidate = liquidationAmount < _debtToCover ? liquidationAmount : _debtToCover; // burn funds from msg.sender for amount to liquidate syntharb().burn(msg.sender, amountToLiquidate); (uint256 loanAmountPaid, ) = _splitInterestLoanPayment( amountToLiquidate, synthLoan.loanAmount ); // Send interests paid to fee pool and record loan amount paid _processInterestAndLoanPayment(loanAmountPaid); // Collateral value to redeem uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); uint256 collateralRedeemed = amountToLiquidate.multiplyDecimal(currentprice).divideDecimal(currentethusdprice); // Add penalty uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(liquidationPenalty) ); // update remaining loanAmount less amount paid and update accrued interests less interest paid _updateLoan(synthLoan, synthLoan.loanAmount.sub(loanAmountPaid)); // update remaining collateral on loan _updateLoanCollateral(synthLoan, synthLoan.collateralAmount.sub(totalCollateralLiquidated)); // Send liquidated ETH collateral to msg.sender msg.sender.transfer(totalCollateralLiquidated); // emit loan liquidation event emit LoanPartiallyLiquidated( _loanCreatorsAddress, _loanID, msg.sender, amountToLiquidate, totalCollateralLiquidated ); } function _splitInterestLoanPayment( uint256 _paymentAmount, uint256 _loanAmount ) internal pure returns ( uint256 loanAmountPaid, uint256 loanAmountAfter ) { uint256 remainingPayment = _paymentAmount; // Remaining amounts - pay down loan amount loanAmountAfter = _loanAmount; if (remainingPayment > 0) { loanAmountAfter = loanAmountAfter.sub(remainingPayment); loanAmountPaid = remainingPayment; } } function _processInterestAndLoanPayment(uint256 loanAmountPaid) internal { // Decrement totalIssuedSynths if (loanAmountPaid > 0) { totalIssuedSynths = totalIssuedSynths.sub(loanAmountPaid); } } // Liquidation of an open loan available for anyone function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant { // Close the creators loan and send collateral to the closer. _closeLoan(_loanCreatorsAddress, _loanID, true); // Tell the Dapps this loan was liquidated emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); } // ========== PRIVATE FUNCTIONS ========== function _closeLoan( address account, uint256 loanID, bool liquidation ) private { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 repayAmount = synthLoan.loanAmount; require( IERC20(address(syntharb())).balanceOf(msg.sender) >= repayAmount, "You do not have the required Synth balance to close this loan." ); // Record loan as closed _recordLoanClosure(synthLoan); // Decrement totalIssuedSynths // subtract the accrued interest from the loanAmount totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); // get prices uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); // Burn all Synths issued for the loan + the fees syntharb().burn(msg.sender, repayAmount); uint256 remainingCollateral = synthLoan.collateralAmount; if (liquidation) { // Send liquidator redeemed collateral + 10% penalty // Collateral value to redeem uint256 collateralRedeemed = repayAmount.multiplyDecimal(currentprice).divideDecimal(currentethusdprice); // add penalty uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(liquidationPenalty) ); // ensure remaining ETH collateral sufficient to cover collateral liquidated // will revert if the liquidated collateral + penalty is more than remaining collateral remainingCollateral = remainingCollateral.sub(totalCollateralLiquidated); // Send liquidator CollateralLiquidated msg.sender.transfer(totalCollateralLiquidated); } // Send remaining collateral to loan creator synthLoan.account.transfer(remainingCollateral); // Tell the Dapps emit LoanClosed(account, loanID); } function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _updateLoan( SynthLoanStruct memory _synthLoan, uint256 _newLoanAmount ) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].loanAmount = _newLoanAmount; } } } function _updateLoanCollateral(SynthLoanStruct memory _synthLoan, uint256 _newCollateralAmount) private returns (SynthLoanStruct memory) { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].collateralAmount = _newCollateralAmount; return synthLoans[i]; } } } function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { // Record the time the loan was closed synthLoans[i].timeClosed = block.timestamp; } } // Reduce Total Open Loans Count totalOpenLoanCount = totalOpenLoanCount.sub(1); } function _incrementTotalLoansCounter() private returns (uint256) { // Increase the total Open loan count totalOpenLoanCount = totalOpenLoanCount.add(1); // Increase the total Loans Created count totalLoansCreated = totalLoansCreated.add(1); // Return total count to be used as a unique ID. return totalLoansCreated; } function _calculateMintingFee(uint256 _ethAmount) private view returns (uint256 mintingFee) { if (issueFeeRate == 0) { mintingFee = 0; } else { mintingFee = _ethAmount.divideDecimalRound(10000 + issueFeeRate).multiplyDecimal(issueFeeRate); } } function _checkLoanIsOpen(SynthLoanStruct memory _synthLoan) internal pure { require(_synthLoan.loanID > 0, "Loan does not exist"); require(_synthLoan.timeClosed == 0, "Loan already closed"); } /* ========== INTERNAL VIEWS ========== */ function syntharb() internal view returns (IConjure) { return IConjure(arbasset); } // ========== EVENTS ========== event CollateralizationRatioUpdated(uint256 ratio); event LiquidationRatioUpdated(uint256 ratio); event InterestRateUpdated(uint256 interestRate); event IssueFeeRateUpdated(uint256 issueFeeRate); event MinLoanCollateralSizeUpdated(uint256 minLoanCollateralSize); event AccountLoanLimitUpdated(uint256 loanLimit); event LoanLiquidationOpenUpdated(bool loanLiquidationOpen); event LoanCreated(address indexed account, uint256 loanID, uint256 amount); event LoanClosed(address indexed account, uint256 loanID); event LoanLiquidated(address indexed account, uint256 loanID, address liquidator); event LoanPartiallyLiquidated( address indexed account, uint256 loanID, address liquidator, uint256 liquidatedAmount, uint256 liquidatedCollateral ); event CollateralDeposited(address indexed account, uint256 loanID, uint256 collateralAmount, uint256 collateralAfter); event CollateralWithdrawn(address indexed account, uint256 loanID, uint256 amountWithdrawn, uint256 collateralAfter); event LoanRepaid(address indexed account, uint256 loanID, uint256 repaidAmount, uint256 newLoanAmount); } contract EtherCollateralFactory { event NewEtherCollateralContract(address deployed); constructor() public { } /** * @dev lets anyone mint a new CONJURE contract */ function EtherCollateralMint( address payable asset_, address owner_, address factoryaddress_, uint256 mintingfeerate_ ) public returns (address) { EtherCollateral newContract = new EtherCollateral( asset_, owner_, factoryaddress_, mintingfeerate_ ); emit NewEtherCollateralContract(address(newContract)); return address(newContract); } } interface IFactoryAddress { function getFactoryOwner() external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; // Libraries import "@openzeppelin/contracts/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // 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; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; /************************************************************************************************ From https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/FixedPoint.sol Copied from the github repository at commit hash 9642a0705fdaf36b477354a4167a8cd765250860. Modifications: - Removed `sqrt` function Subject to the GPL-3.0 license *************************************************************************************************/ // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require( y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW" ); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, "FixedPoint: ZERO_RECIPROCAL"); return uq112x112(uint224(Q224 / self._x)); } } pragma solidity ^0.6.0; contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } pragma solidity ^0.6.0; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } pragma solidity ^0.6.0; interface IConjure { function burn(address account, uint amount) external; function mint(address account, uint amount) external; function getFee() external view returns (uint8); function getLatestETHUSDPrice() external view returns (int); function getPrice() external returns (uint); function getLatestPrice() external view returns (uint); }
Liquidate loans at or below issuance ratio check msg.sender (liquidator's wallet) has sufficient Check loan exists and is open calculate amount to liquidate to fix ratio including accrued interest cap debt to liquidate burn funds from msg.sender for amount to liquidate Send interests paid to fee pool and record loan amount paid Collateral value to redeem Add penalty update remaining loanAmount less amount paid and update accrued interests less interest paid update remaining collateral on loan Send liquidated ETH collateral to msg.sender emit loan liquidation event
function liquidateLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _debtToCover ) external nonReentrant { require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _debtToCover, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); _checkLoanIsOpen(synthLoan); (uint256 collateralRatio, uint256 collateralValue) = _loanCollateralRatio(synthLoan); require(collateralRatio < liquidationRatio, "Collateral ratio above liquidation ratio"); uint256 liquidationAmount = calculateAmountToLiquidate( synthLoan.loanAmount, collateralValue ); uint256 amountToLiquidate = liquidationAmount < _debtToCover ? liquidationAmount : _debtToCover; syntharb().burn(msg.sender, amountToLiquidate); (uint256 loanAmountPaid, ) = _splitInterestLoanPayment( amountToLiquidate, synthLoan.loanAmount ); _processInterestAndLoanPayment(loanAmountPaid); uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); uint256 collateralRedeemed = amountToLiquidate.multiplyDecimal(currentprice).divideDecimal(currentethusdprice); uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(liquidationPenalty) ); _updateLoan(synthLoan, synthLoan.loanAmount.sub(loanAmountPaid)); _updateLoanCollateral(synthLoan, synthLoan.collateralAmount.sub(totalCollateralLiquidated)); msg.sender.transfer(totalCollateralLiquidated); emit LoanPartiallyLiquidated( _loanCreatorsAddress, _loanID, msg.sender, amountToLiquidate, totalCollateralLiquidated ); }
6,308,976
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) {
1,784,301
pragma solidity 0.5.11; /** * @dev Interface for Aaves A Token * Documentation: https://developers.aave.com/#atokens */ interface IAaveAToken { /** * @notice Non-standard ERC20 function to redeem an _amount of aTokens for the underlying * asset, burning the aTokens during the process. * @param _amount Amount of aTokens */ function redeem(uint256 _amount) external; /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns (uint256); } /** * @dev Interface for Aaves Lending Pool * Documentation: https://developers.aave.com/#lendingpool */ interface IAaveLendingPool { /** * @notice Deposits a certain _amount of an asset specified by the _reserve parameter. * @dev The caller receives a certain amount of corresponding aTokens in exchange. * The amount of aTokens received depends on the corresponding aToken exchange rate. * LendingPoolCore must be approved to spend this reserve */ function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external; } /** * @dev Interface for Aaves Lending Pool * Documentation: https://developers.aave.com/#lendingpooladdressesprovider */ interface ILendingPoolAddressesProvider { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); /** * @notice Get the address for lendingPoolCore * @dev IMPORTANT - this is where _reserve must be approved before deposit */ function getLendingPoolCore() external view returns (address payable); }
Interface for Aaves A Token/
interface IAaveAToken { function redeem(uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); }
6,460,625
// SPDX-License-Identifier: MIT // Welcome to the Golden Gumball Machine pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IGoldenGumballMachine.sol"; contract GoldenGumballMachine is IGoldenGumballMachine, ERC721, ERC721Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; constructor (address _owner, address _payToken) ERC721("Golden Gumball Tokens", "GUM") { GUM = IERC721(address(this)); payToken = IERC20(_payToken); transferOwnership(_owner); } // STRUCTS, MAPPINGS, AND ARRAYS // // Parameters of Gumballers (shot callers, 20" blades, on the Impala) struct Gumballers { uint256 gumballerBlocknum; uint256 myGoldenToken; bool gumballerBool; bool myHonorBool; } // Parameters of Gumballs struct Gumballs { address nftAddress; uint256 nftId; address owner; } mapping(address => Gumballers) public gumballers; Gumballs[] public gumballs; // Parameters of Whitelisted Tokens struct Whitelist { bool status; } mapping(address => Whitelist) public whitelist; // Parameters of Tickets struct Tickets { address owner; } Tickets[] public tickets; // CONSTANTS AND GLOBAL VARIABLES // // ERC20 interfaces IERC721 public GUM; IERC20 public payToken; // Bool to ensure the machine has sufficient Gumballs inserted before allowing tokens to be inserted bool public isMachineInitialized; // Golden Gumball Machine global variables uint256 public totalGumballs; uint256 public lastGumball; uint256 public drawingEndTimestamp; uint256 public lastDrawingTimestamp; uint256 private goldenBlock; bool private goldenBool; bool private honorBool; uint256 public totalTickets; uint256 public lastWinningTicket; uint256 public totalGoldenTokens; uint256 public blockNum; // Golden Gumball Machine admin-set variables uint256 public ENTRY_PRICE; uint256 public MACHINE_ACTIVATE_REQUIREMENT; uint256 public MACHINE_DEACTIVATE_REQUIREMENT; bool public drawingRepeatStatus; bool public drawingActive; uint256 public drawingDuration; // Constants for the Gumball machine uint256 public constant MAX_BLOCKS = 250; uint256 public constant BLOCK_BUFFER = 1; // FUNCTION MODIFIERS // modifier onlyNotContract() { require( _msgSender() == tx.origin, "Only contracts can call this function" ); _; } modifier gumballMachineActive() { require( isMachineInitialized == true, "Machine stock is too low to use, come back later when more Gumballs are added!" ); _; } // ADMIN-ONLY FUNCTIONS // function setPayToken(address _payToken) public onlyOwner { payToken = IERC20(_payToken); } function setEntryPrice(uint256 _price) public onlyOwner { ENTRY_PRICE = _price; } function setActiveRequirements(uint256 _deactivate, uint256 _activate) public onlyOwner { MACHINE_DEACTIVATE_REQUIREMENT = _deactivate; MACHINE_ACTIVATE_REQUIREMENT = _activate; } function setWhitelistStatus(address _nftAddress, bool _status) public onlyOwner { Whitelist storage _whitelisted = whitelist[_nftAddress]; _whitelisted.status = _status; } function setDrawingRepeatStatus(bool _status) public onlyOwner { drawingRepeatStatus = _status; } function setBlockNum(uint256 _blockNum) public { blockNum = _blockNum; } function initializeDrawing(uint256 _duration, bool _repeatDrawing) public gumballMachineActive onlyOwner { require( _duration >= 0, "Duration must be longer" ); require( block.number > drawingEndTimestamp, "Cannot initialize in the middle of a drawing" ); drawingDuration = _duration; drawingRepeatStatus = _repeatDrawing; drawingActive = true; drawingEndTimestamp = (block.timestamp + _duration); } // EXTERNAL FUNCTIONS // /** @notice External function to enter into the Golden Gumball drawing */ function enterDrawing() external override gumballMachineActive nonReentrant { // HARD CHECK: Requires the drawing be active before proceeding require( block.timestamp < drawingEndTimestamp && block.timestamp > lastDrawingTimestamp && drawingActive == true, "Drawing isn't currently active" ); // HARD CHECK: Requires the _msgSender() to have enough ERC20 tokens to transfer require( payToken.transferFrom(_msgSender(), address(this), ENTRY_PRICE), "Insufficient balance or not approved" ); _enterDrawing(); } /** @notice Fixes stale drawing (drawing that was started and never finished before the MAX_BLOCKS buffer) */ function fixStaleDrawing() public override { // HARD CHECK: Require the drawing to be started before fixing require( goldenBool == true, "No drawing found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the drawing began require( block.number > (goldenBlock + MAX_BLOCKS), "Drawing isn't stale" ); goldenBool = false; honorBool = false; } /** @notice Fixes stuck tokens (Tokens that were inserted and left before resulting) */ function returnToken() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require the token be inserted before returning require( gumballer.gumballerBool == true && gumballer.myHonorBool == false, "No token found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the token was inserted require( block.number > (gumballer.gumballerBlocknum + MAX_BLOCKS), "Token isn't stale" ); // Returns Golden Gumball Token GUM.safeTransferFrom( address(this), _msgSender(), gumballer.myGoldenToken ); gumballer.gumballerBool = false; } /** @notice Fixes account status in the event that a user inserted a token, cranked the lever, then waited longer than the allowed time, this will not return the token for security reasons */ function fixStatus() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require a token be inserted before fixing require( gumballer.gumballerBool == true && gumballer.myHonorBool == true, "No token found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the lever was cranked require( block.number > (gumballer.gumballerBlocknum + MAX_BLOCKS), "Token hasn't expired yet" ); gumballer.gumballerBool = false; gumballer.myHonorBool = false; } /** @notice External function to begin the drawing */ function beginDrawing() external override gumballMachineActive nonReentrant { // HARD CHECK: Requires the drawing be completed before proceeding require( block.timestamp > drawingEndTimestamp && drawingActive == true, "Drawing isn't currently active or entry period hasn't ended" ); // HARD CHECK: Require no current Gumball purchase in queue require( goldenBool == false, "Drawing has already started" ); goldenBlock = block.number; goldenBool = true; } /** @notice Shuffles around all the tickets (fully commits to the drawing, winner must be picked within MAX_BLOCKS or drawing is null) */ function shuffleTickets() public override { // HARD CHECK: Require the drawing to be started before shuffling require( goldenBool == true, "Drawing hasn't started" ); // HARD CHECK: Require block.number to be greater than when the drawing began require( block.number > (goldenBlock + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the drawing began require( block.number <= (goldenBlock + MAX_BLOCKS), "Stale drawing, fixStaleDrawing and restart the drawing" ); goldenBlock = (block.number + BLOCK_BUFFER); honorBool = true; } /** @notice Implements commit/reveal logic to randomly select the winner */ function pickTheWinner() public override { // HARD CHECK: Require the tickets be shuffled before picking a winner require( goldenBool == true && honorBool == true, "No active drawing found" ); // HARD CHECK: Require block.number to be greater than when the drawing began require( block.number > (goldenBlock + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the drawing began require( block.number <= (goldenBlock + MAX_BLOCKS), "Stale drawing, fixStaleDrawing and restart the drawing" ); // Get the blockhash of the locked in goldenBlock from the shuffleTickets() function bytes32 _goldenBlockhash = blockhash(goldenBlock); // Packs the blockhash and keccacks it, then takes the remainder (totalTickets) and that's the random number uint256 _goldenRand = uint256(keccak256(abi.encodePacked(_goldenBlockhash))) % totalTickets - 1; // Set the Golden Gumball info back to default goldenBlock = 0; goldenBool = false; honorBool = false; // Get the owner of the winning ticket address _winner = tickets[_goldenRand].owner; // Swap the data of the last ticket purchased with the winning ticket tickets[_goldenRand].owner = tickets[totalTickets-1].owner; lastWinningTicket = _goldenRand; // Deletes the last Ticket in line (essentially the Ticket that was won, in the form of the last-in-lines' data) tickets.pop(); totalTickets--; // Mints a Golden Gumball Token for the winner super._mint(_winner, totalGoldenTokens); totalGoldenTokens++; lastDrawingTimestamp = drawingEndTimestamp; // Restarts the drawing if the drawingRepeatStatus is true, else it sets the drawing to inactive if (drawingRepeatStatus == true) { drawingEndTimestamp = (block.timestamp + drawingDuration); } else { drawingActive = false; } } /** @notice External function to add Gumballs to the machine @param _nftAddress ERC 721 Address @param _nftId NFT ID */ function addGumball(address _nftAddress, uint256 _nftId) external override nonReentrant { // HARD CHECK: Requires sender to own the NFT require( IERC721(_nftAddress).ownerOf(_nftId) == _msgSender(), "You don't own this NFT" ); // HARD CHECK: Requires Gumball contract to be approved require( IERC721(_nftAddress).isApprovedForAll( _msgSender(), address(this) ), "Gumball hasn't been approved" ); // HARD CHECK: Requires the NFT address be whitelisted to add to the machine Whitelist memory _whitelisted = whitelist[_nftAddress]; require( _whitelisted.status = true, "NFT address isn't current whitelisted" ); // Call internal function _addGumball to complete the addGumBall process _addGumball( _nftAddress, _nftId ); } /** @notice Inserts Golden Gumball Token into the machine */ function insertGumballToken(uint256 _nftId) public override nonReentrant onlyNotContract gumballMachineActive { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require the sender be the owner of the Golden Gumball Token require( IERC721(address(this)).ownerOf(_nftId) == _msgSender(), "You don't own this Golden Gumball Token" ); // HARD CHECK: Require no current Gumball purchase in queue require( gumballer.gumballerBool == false, "Golden Gumball already purchased" ); // HARD CHECK: Requires Gumball contract to be approved require( IERC721(address(this)).isApprovedForAll( _msgSender(), address(this) ), "Golden Gumball hasn't been approved" ); // Inserts Golden Gumball Token into the machine GUM.safeTransferFrom( _msgSender(), address(this), _nftId ); gumballer.gumballerBlocknum = block.number; gumballer.gumballerBool = true; } /** @notice Cranks lever on the Golden Gumball Machine */ function crankTheLever() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require current Golden Gumball purchase in queue require( gumballer.gumballerBool == true, "No active Golden Gumball found" ); // HARD CHECK: Require block.number to be greater than when the token was inserted require( block.number >= (gumballer.gumballerBlocknum + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the token was inserted require( block.number <= (gumballer.gumballerBlocknum + MAX_BLOCKS), "Gumball token expired, press the return token button to try again" ); gumballer.gumballerBlocknum = (block.number + BLOCK_BUFFER); gumballer.myHonorBool = true; } /** @notice Implements commit/reveal logic to randomly select your Gumball */ function revealYourGumball() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require current Golden Gumball purchase in queue require( gumballer.gumballerBool == true && gumballer.myHonorBool == true, "No active Gumball found" ); // HARD CHECK: Require block.number to be greater than when the lever was cranked require( block.number >= (gumballer.gumballerBlocknum + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the lever was cranked require( block.number <= (gumballer.gumballerBlocknum + MAX_BLOCKS), "Gumball token expired, press the return token button to try again" ); // Get the blockhash of the locked in gumballer.gumballerBlocknum from the crankTheLever() function bytes32 _gumBlockhash = blockhash(gumballer.gumballerBlocknum); // Packs the blockhash and keccacks it, then takes the remainder (totalGumballs) and that's the random number uint256 _gumRand = uint256(keccak256(abi.encodePacked(_gumBlockhash))) % totalGumballs - 1; // Set the Gumballer purchase info back to default gumballer.gumballerBlocknum = 0; gumballer.gumballerBool = false; gumballer.myHonorBool = false; // Get the NFT address and ID for the Gumball won address _nftAddress = gumballs[_gumRand].nftAddress; uint256 _nftId = gumballs[_gumRand].nftId; // Swap the data of the last Gumball added to the machine with the Gumball that was won gumballs[_gumRand].nftAddress = gumballs[totalGumballs-1].nftAddress; gumballs[_gumRand].nftId = gumballs[totalGumballs-1].nftId; gumballs[_gumRand].owner = gumballs[totalGumballs-1].owner; lastGumball = _gumRand; // Deletes the last Gumball in line (essentially the Gumball that was won, in the form of the last-in-lines' data) gumballs.pop(); totalGumballs--; if (totalGumballs <= MACHINE_DEACTIVATE_REQUIREMENT) { isMachineInitialized = false; } // Transfers the randomly selected Gumball to the buyer IERC721(_nftAddress).safeTransferFrom( IERC721(_nftAddress).ownerOf(_nftId), _msgSender(), _nftId ); // emit GumballClaimed(_nftAddress, _nftId); } // INTERNAL FUNCTIONS // /** @notice Internal function to complete the addGumBall process @param _nftAddress ERC 721 Address @param _nftId NFT ID */ function _addGumball(address _nftAddress, uint256 _nftId) internal { // Transfers NFT ownership to the GumBall machine IERC721(_nftAddress).safeTransferFrom( IERC721(_nftAddress).ownerOf(_nftId), address(this), _nftId ); // Catalogues the NFT Address/ID and logs the owner gumballs.push(); gumballs[gumballs.length-1].nftAddress = _nftAddress; gumballs[gumballs.length-1].nftId = _nftId; gumballs[gumballs.length-1].owner = _msgSender(); totalGumballs++; if (totalGumballs >= MACHINE_ACTIVATE_REQUIREMENT) { isMachineInitialized = true; } emit GumballAdded(_msgSender(), _nftAddress, _nftId); } /** @notice Internal function to enter the Golden Gumball Token drawing */ function _enterDrawing() internal { // Catalogues the Ticket owner tickets.push(); tickets[tickets.length-1].owner = _msgSender(); totalTickets++; } }
/ HARD CHECK: Require the sender be the owner of the Golden Gumball Token HARD CHECK: Require no current Gumball purchase in queue HARD CHECK: Requires Gumball contract to be approved Inserts Golden Gumball Token into the machine
function insertGumballToken(uint256 _nftId) public override nonReentrant onlyNotContract gumballMachineActive { Gumballers storage gumballer = gumballers[_msgSender()]; require( IERC721(address(this)).ownerOf(_nftId) == _msgSender(), "You don't own this Golden Gumball Token" ); require( gumballer.gumballerBool == false, "Golden Gumball already purchased" ); require( IERC721(address(this)).isApprovedForAll( _msgSender(), address(this) ), "Golden Gumball hasn't been approved" ); GUM.safeTransferFrom( _msgSender(), address(this), _nftId ); gumballer.gumballerBlocknum = block.number; gumballer.gumballerBool = true; }
13,006,602
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _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 Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != 0); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(account != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { require(amount <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( amount); _burn(account, amount); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require(token.approve(spender, value)); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) public { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the mount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param beneficiary Address performing the token purchase */ function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol&#39;s _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: contracts/TieredPriceCrowdsale.sol /** * @title CappedWhitelistedCrowdsale * @dev Crowdsale with a limit for total contributions and per-beneficiary caps. * Combination of CappedCrowdsale and IndividuallyCappedCrowdsale */ contract TieredPriceCrowdsale is Crowdsale { uint256 private _baseRate; uint256 private _tier2Start; uint256 private _tier3Start; uint256 private _tier4Start; constructor( uint256 baseRate, uint256 openingTimeTier2, uint256 openingTimeTier3, uint256 openingTimeTier4 ) public { require(baseRate > 0); require(openingTimeTier2 > block.timestamp); require(openingTimeTier3 >= openingTimeTier2); require(openingTimeTier4 >= openingTimeTier3); _baseRate = baseRate; _tier4Start = openingTimeTier4; _tier3Start = openingTimeTier3; _tier2Start = openingTimeTier2; } function _getbonusRate() internal view returns (uint256) { // Calculate current rate with bonus if(_tier2Start > block.timestamp){ return(_baseRate * 6 / 5); } else if(_tier3Start > block.timestamp){ return(_baseRate * 11 / 10); } else if(_tier4Start > block.timestamp){ return(_baseRate * 21 / 20); } else { return(_baseRate); } } /** * @return the current bonus level. */ function bonusRate() public view returns(uint256) { return _getbonusRate(); } /** * @param tier Value that represents the tier * @return Timestamp when the tier starts */ function tierStartTime( uint256 tier ) external view returns(uint256) { if(tier == 2){ return _tier2Start; } else if(tier == 3){ return _tier3Start; } else if(tier == 4){ return _tier4Start; } return 0; } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount( uint256 weiAmount ) internal view returns (uint256) { return weiAmount.mul(_getbonusRate()); } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = true; } /** * @dev remove an account&#39;s access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/CapperRole.sol contract CapperRole { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private cappers; constructor() public { cappers.add(msg.sender); } modifier onlyCapper() { require(isCapper(msg.sender)); _; } function isCapper(address account) public view returns (bool) { return cappers.has(account); } function addCapper(address account) public onlyCapper { cappers.add(account); emit CapperAdded(account); } function renounceCapper() public { cappers.remove(msg.sender); } function _removeCapper(address account) internal { cappers.remove(account); emit CapperRemoved(account); } } // File: contracts/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale with whitelist required for purchases, based on IndividuallyCappedCrowdsale. */ contract WhitelistedCrowdsale is Crowdsale, CapperRole { using SafeMath for uint256; uint256 private _invCap; mapping(address => uint256) private _contributions; mapping(address => uint256) private _caps; constructor(uint256 invCap) public { require(invCap > 0); _invCap = invCap; } /** * @dev Checks whether the beneficiary is in the whitelist. * @param beneficiary Address to be checked * @return Whether the beneficiary is whitelisted */ function isWhitelisted(address beneficiary) public view returns (bool) { return _caps[beneficiary] != 0; } /** * @dev add an address to the whitelist * @param beneficiary address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address beneficiary) public onlyCapper returns (bool) { require(beneficiary != address(0)); _caps[beneficiary] = _invCap; return isWhitelisted(beneficiary); } /** * @dev add addresses to the whitelist * @param _beneficiaries addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _beneficiaries) external onlyCapper { for (uint256 i = 0; i < _beneficiaries.length; i++) { addAddressToWhitelist(_beneficiaries[i]); } } /** * @dev remove an address from the whitelist * @param beneficiary address * @return true if the address was removed from the whitelist, false if the address wasn&#39;t already in the whitelist */ function removeAddressFromWhitelist(address beneficiary) public onlyCapper returns (bool) { require(beneficiary != address(0)); _caps[beneficiary] = 0; return isWhitelisted(beneficiary); } /** * @dev remove addresses from the whitelist * @param _beneficiaries addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren&#39;t already in the whitelist */ function removeAddressesFromWhitelist(address[] _beneficiaries) external onlyCapper { for (uint256 i = 0; i < _beneficiaries.length; i++) { removeAddressFromWhitelist(_beneficiaries[i]); } } /** * @dev Returns the amount contributed so far by a specific beneficiary. * @param beneficiary Address of contributor * @return Beneficiary contribution so far */ function getContribution(address beneficiary) public view returns (uint256) { return _contributions[beneficiary]; } /** * @dev Extend parent behavior requiring purchase to respect the beneficiary&#39;s funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { super._preValidatePurchase(beneficiary, weiAmount); require( _contributions[beneficiary].add(weiAmount) <= _caps[beneficiary]); } /** * @dev Extend parent behavior to update beneficiary contributions * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor(uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns(uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) public { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime >= openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized = false; event CrowdsaleFinalized(); /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() public { require(!_finalized); require(hasClosed()); _finalization(); emit CrowdsaleFinalized(); _finalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() public { minters.add(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { minters.add(account); emit MinterAdded(account); } function renounceMinter() public { minters.remove(msg.sender); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { event MintingFinished(); bool private _mintingFinished = false; modifier onlyBeforeMintingFinished() { require(!_mintingFinished); _; } /** * @return true if the minting is finished. */ function mintingFinished() public view returns(bool) { return _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 ) public onlyMinter onlyBeforeMintingFinished returns (bool) { _mint(to, amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyMinter onlyBeforeMintingFinished returns (bool) { _mintingFinished = true; emit MintingFinished(); return true; } } // File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount)); } } // File: contracts/PlazaCrowdsale.sol contract PlazaCrowdsale is CappedCrowdsale, FinalizableCrowdsale, MintedCrowdsale, WhitelistedCrowdsale, TieredPriceCrowdsale { constructor( uint256 openingTime, uint256 closingTime, uint256 rate, address wallet, uint256 cap, ERC20Mintable token, uint256 openingTimeTier4, uint256 openingTimeTier3, uint256 openingTimeTier2, uint256 invCap ) public Crowdsale(rate, wallet, token) CappedCrowdsale(cap) WhitelistedCrowdsale(invCap) TimedCrowdsale(openingTime, closingTime) TieredPriceCrowdsale(rate, openingTimeTier2, openingTimeTier3, openingTimeTier4) {} }
Extend parent behavior requiring purchase to respect the beneficiary&39;s funding cap. beneficiary Token purchaser weiAmount Amount of wei contributed/
function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { super._preValidatePurchase(beneficiary, weiAmount); require( _contributions[beneficiary].add(weiAmount) <= _caps[beneficiary]); }
6,710,117
./full_match/100/0x62D007D4c4Db781C24FF6ac19279B9A9Ec32b344/sources/contracts/recover/recover.sol
Pay the arbitration fee to raise a dispute. To be called by the finder. UNTRUSTED. Note that this function mirrors payArbitrationFeeByFinder. _claimID The index of the claim./ Require that the total pay at least the arbitration cost. The owner still has to pay. This can also happen if he has paid, but arbitrationCost has increased.
function payArbitrationFeeByFinder(uint _claimID) public payable { Claim storage itemClaim = claims[_claimID]; Item storage item = items[itemClaim.itemID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require( itemClaim.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); require(itemClaim.finder == _msgSender(), "The caller must be the sender."); require(true == itemClaim.isAccepted, "The claim of the item must be accepted."); itemClaim.finderFee += msg.value; require(itemClaim.finderFee >= arbitrationCost, "The finder fee must cover arbitration costs."); itemClaim.lastInteraction = block.timestamp; if (item.ownerFee < arbitrationCost) { itemClaim.status = Status.WaitingOwner; emit HasToPayFee(_claimID, Party.Owner); raiseDispute(_claimID, arbitrationCost); } }
14,273,936