file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.4.24; import "contracts/Storage.sol"; contract MultiSignAdmin is Pausable, Administratable, UserContract { /* * Constants */ uint256 constant public maxBankCount = 50; /* * events */ event BankAddition(address indexed bank); event BankRemoval(address indexed bank); event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event RequirementChange(uint256 required); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // This notifies clients about the amount mint event Mint(address indexed to, uint256 value); /* * Storage */ Balance internal _balances; address[] public alliance; mapping (address => bool) public inAlliance; mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bool isMint; bool executed; } /* * modifiers */ modifier validRequirement(uint256 bankCount, uint256 _required) { require(bankCount <= maxBankCount && _required <= bankCount && _required != 0 && bankCount != 0); _; } modifier bankNotExist(address bank) { require(!inAlliance[bank]); _; } modifier bankExists(address bank) { require(inAlliance[bank]); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } constructor( Balance _balanceContract, Blacklist _blacklistContract, Verified _verifiedListContract, address[] _banks, uint256 _required ) UserContract(_blacklistContract, _verifiedListContract) validRequirement(_banks.length, _required) public { _balances = _balanceContract; for (uint256 i=0; i<_banks.length; i++) { require(!inAlliance[_banks[i]] && _banks[i] != 0); inAlliance[_banks[i]] = true; } alliance = _banks; required = _required; } /// @dev Allows to add a new bank. Transaction has to be sent by owner. /// @param bank Address of new bank. function addBank(address bank) onlyOwner bankNotExist(bank) notNull(bank) validRequirement(alliance.length + 1, required) public { inAlliance[bank] = true; alliance.push(bank); emit BankAddition(owner); } /// @dev Allows to remove a bank. Transaction has to be sent by owner. /// @param bank Address of bank. function removeBank(address bank) onlyOwner bankExists(bank) public { inAlliance[bank] = false; for (uint256 i=0; i<alliance.length - 1; i++) if (alliance[i] == bank) { alliance[i] = alliance[alliance.length - 1]; break; } alliance.length -= 1; if (required > alliance.length) changeRequirement(alliance.length); emit BankRemoval(owner); } /// @dev Allows to replace an bank with a new bank. Transaction has to be sent by owner. /// @param bank Address of bank to be replaced. /// @param newBank Address of new bank. function replaceBank(address bank, address newBank) onlyOwner bankExists(bank) bankNotExist(newBank) public { for (uint256 i=0; i<alliance.length; i++) if (alliance[i] == bank) { alliance[i] = newBank; break; } inAlliance[bank] = false; inAlliance[newBank] = true; emit BankRemoval(bank); emit BankAddition(newBank); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint256 _required) onlyOwner validRequirement(alliance.length, _required) public { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a mint transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function proposeMint(address destination, uint256 value) bankExists(msg.sender) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, true); confirmTransaction(transactionId); } /// @dev Allows an owner to submit and confirm a burnFrom transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function proposeBurn(address destination, uint256 value) bankExists(msg.sender) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, false); confirmTransaction(transactionId); } /// @dev Allows a bank to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) bankExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) public { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows a bank to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint256 transactionId) bankExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) public { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) bankExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) public { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; bool success = true; if (txn.isMint) { success = _mint(txn.destination, txn.value); } else { success = _burnFrom(txn.destination, txn.value); } if (success) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i=0; i<alliance.length; i++) { if (confirmations[transactionId][alliance[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 isMint true if calling Mint, false if calling BurnFrom. /// @return Returns transaction ID. function addTransaction(address destination, uint256 value, bool isMint) notNull(destination) internal returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, isMint: isMint, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i=0; i<alliance.length; i++) if (confirmations[transactionId][alliance[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 view returns (uint256 count) { for (uint256 i=0; i<transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of banks. /// @return List of bank addresses. function getAlliance() public view returns (address[]) { return alliance; } /// @dev Returns array with bank addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of bank addresses. function getConfirmations(uint256 transactionId) public view returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](alliance.length); uint256 count = 0; uint256 i; for (i=0; i<alliance.length; i++) if (confirmations[transactionId][alliance[i]]) { confirmationsTemp[count] = alliance[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(uint256 from, uint256 to, bool pending, bool executed) public view returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint256 count = 0; uint256 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]; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function _burnFrom(address _from, uint256 _value) whenNotPaused internal returns (bool success) { require(_balances.balanceOf(_from) >= _value); // Check if the targeted balance is enough _balances.subBalance(_from, _value); // Subtract from the targeted balance _balances.subTotalSupply(_value); emit Burn(_from, _value); return true; } /** * Add `_amount` tokens to the pool and to the `_to` address' balance * * @param _to the address that will receive the given amount of tokens * @param _amount the amount of tokens it will receive */ function _mint(address _to, uint256 _amount) whenNotPaused internal returns (bool success) { _balances.addBalance(_to, _amount); _balances.addTotalSupply(_amount); emit Mint(_to, _amount); return true; } }
@dev Allows anyone to execute a confirmed transaction. @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId) bankExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) public { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; bool success = true; if (txn.isMint) { success = _mint(txn.destination, txn.value); success = _burnFrom(txn.destination, txn.value); } if (success) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } }
5,414,979
[ 1, 19132, 1281, 476, 358, 1836, 279, 19979, 2492, 18, 225, 24112, 5947, 1599, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1836, 3342, 12, 11890, 5034, 24112, 13, 203, 565, 11218, 4002, 12, 3576, 18, 15330, 13, 203, 565, 19979, 12, 7958, 548, 16, 1234, 18, 15330, 13, 203, 565, 486, 23839, 12, 7958, 548, 13, 203, 565, 1071, 203, 225, 288, 203, 565, 309, 261, 291, 3976, 11222, 12, 7958, 548, 3719, 288, 203, 1377, 5947, 2502, 7827, 273, 8938, 63, 7958, 548, 15533, 203, 1377, 7827, 18, 4177, 4817, 273, 638, 31, 203, 1377, 1426, 2216, 273, 638, 31, 203, 1377, 309, 261, 24790, 18, 291, 49, 474, 13, 288, 203, 3639, 2216, 273, 389, 81, 474, 12, 24790, 18, 10590, 16, 7827, 18, 1132, 1769, 203, 3639, 2216, 273, 389, 70, 321, 1265, 12, 24790, 18, 10590, 16, 7827, 18, 1132, 1769, 203, 1377, 289, 203, 1377, 309, 261, 4768, 13, 203, 3639, 3626, 8687, 12, 7958, 548, 1769, 203, 1377, 469, 288, 203, 3639, 3626, 8687, 5247, 12, 7958, 548, 1769, 203, 3639, 7827, 18, 4177, 4817, 273, 629, 31, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract SEcoinAbstract {function unlock() public;} contract SECrowdsale { using SafeMath for uint256; // The token being sold address constant public SEcoin = 0xe45b7cd82ac0f3f6cfc9ecd165b79d6f87ed2875;//"SEcoin address" // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public SEcoinWallet = 0x5C737AdC09a0cFA1C9b83E199971a677163ddd07;//"SEcoin all token inside & ICO ether"; address public SEcoinsetWallet = 0x52873e9191f21a26ddc8b65e5dddbac6b73b69e8;//"control SEcoin SmartContract address" // how many token units a buyer gets per wei uint256 public rate = 6000;//"ICO start rate" // amount of raised money in wei uint256 public weiRaised; uint256 public weiSold; //storage address and amount address public SEcoinbuyer; address[] public SEcoinbuyerevent; uint256[] public SEcoinAmountsevent; uint256[] public SEcoinmonth; uint public firstbuy; uint SEcoinAmounts ; uint SEcoinAmountssend; mapping(address => uint) public icobuyer; mapping(address => uint) public icobuyer2; event TokenPurchase(address indexed purchaser, address indexed SEcoinbuyer, uint256 value, uint256 amount,uint SEcoinAmountssend); // fallback function can be used to buy tokens function () external payable {buyTokens(msg.sender);} //check buyer function buyer(address SEcoinbuyer) internal{ if(icobuyer[msg.sender]==0){ icobuyer[msg.sender] = firstbuy; icobuyer2[msg.sender] = firstbuy; firstbuy++; //event buyer SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); }else if(icobuyer[msg.sender]!=0){ uint i = icobuyer2[msg.sender]; SEcoinAmountsevent[i]=SEcoinAmountsevent[i]+SEcoinAmounts; icobuyer2[msg.sender]=icobuyer[msg.sender];} } // low level token purchase function function buyTokens(address SEcoinbuyer) public payable { require(SEcoinbuyer != address(0x0)); require(selltime()); require(msg.value>=1*1e16 && msg.value<=200*1e18); // calculate token amount to be created SEcoinAmounts = calculateObtainedSEcoin(msg.value); SEcoinAmountssend= calculateObtainedSEcoinsend(SEcoinAmounts); // update state weiRaised = weiRaised.add(msg.value); weiSold = weiSold.add(SEcoinAmounts); //sendtoken require(ERC20Basic(SEcoin).transfer(SEcoinbuyer, SEcoinAmountssend)); //call function buyer(msg.sender); checkRate(); forwardFunds(); //write event emit TokenPurchase(msg.sender, SEcoinbuyer, msg.value, SEcoinAmounts,SEcoinAmountssend); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { SEcoinWallet.transfer(msg.value); } //calculate Amount function calculateObtainedSEcoin(uint256 amountEtherInWei) public view returns (uint256) { checkRate(); return amountEtherInWei.mul(rate); } function calculateObtainedSEcoinsend (uint SEcoinAmounts)public view returns (uint){ return SEcoinAmounts.div(10); } // return true if the transaction can buy tokens function selltime() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; return withinPeriod; } // return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool isEnd = now > endTime || weiRaised >= 299600000*1e18;//ico max token return isEnd; } //releaseSEcoin only admin function releaseSEcoin() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); SEcoinAbstract(SEcoin).unlock(); } //getunselltoken only admin function getunselltoken()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this)-weiSold; ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } //backup function getunselltokenB()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this); ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } // be sure to get the token ownerships function start() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (firstbuy==0); startTime = 1541001600;//startTime endTime = 1543593599;//endTime SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); firstbuy=1; } //Change setting Wallet function changeSEcoinWallet(address _SEcoinsetWallet) public returns (bool) { require (msg.sender == SEcoinsetWallet); SEcoinsetWallet = _SEcoinsetWallet; } //ckeckRate function checkRate() public returns (bool) { if (now>=startTime && now< 1541433599){ rate = 6000;//section one }else if (now >= 1541433599 && now < 1542297599) { rate = 5000;//section two }else if (now >= 1542297599 && now < 1543161599) { rate = 4000;//section three }else if (now >= 1543161599) { rate = 3500;//section four } } //get ICOtoken in everyMonth function getICOtoken(uint number)public returns(string){ require(SEcoinbuyerevent[number] == msg.sender); require(now>=1543593600&&now<=1567267199); uint _month; //December 2018 two if(now>=1543593600 && now<=1546271999 && SEcoinmonth[number]==0){ require(SEcoinmonth[number]==0); ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=1; } //February January 2019 three else if(now>=1546272000 && now<=1548950399 && SEcoinmonth[number]<=1){ if(SEcoinmonth[number]==1){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=2; }else if(SEcoinmonth[number]<1){ _month = 2-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=2;} } //February 2019 four else if(now>=1548950400 && now<=1551369599 && SEcoinmonth[number]<=2){ if(SEcoinmonth[number]==2){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=3; }else if(SEcoinmonth[number]<2){ _month = 3-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=3;} } //March 2019 five else if(now>=1551369600 && now<=1554047999 && SEcoinmonth[number]<=3){ if(SEcoinmonth[number]==3){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=4; }else if(SEcoinmonth[number]<3){ _month = 4-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=4;} } //April 2019 six else if(now>=1554048000 && now<=1556639999 && SEcoinmonth[number]<=4){ if(SEcoinmonth[number]==4){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=5; }else if(SEcoinmonth[number]<4){ _month = 5-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=5;} } //May 2019 seven else if(now>=1556640000 && now<=1559318399 && SEcoinmonth[number]<=5){ if(SEcoinmonth[number]==5){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=6; }else if(SEcoinmonth[number]<5){ _month = 6-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=6;} } //June 2019 eight else if(now>=1559318400 && now<=1561910399 && SEcoinmonth[number]<=6){ if(SEcoinmonth[number]==6){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=7; }else if(SEcoinmonth[number]<6){ _month = 7-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=7;} } //July 2019 nine August else if(now>=1561910400 && now<=1564588799 && SEcoinmonth[number]<=7){ if(SEcoinmonth[number]==7){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=8; }else if(SEcoinmonth[number]<7){ _month = 8-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=8;} } //August 2019 ten else if(now>=1564588800 && now<=1567267199 && SEcoinmonth[number]<=8){ if(SEcoinmonth[number]==8){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=9; }else if(SEcoinmonth[number]<8){ _month = 9-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=9;} } //get all token else if(now<1543593600 || now>1567267199 || SEcoinmonth[number]>=9){ revert("Get all tokens or endtime"); } } }
getunselltoken only admin
function getunselltoken()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this)-weiSold; ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); }
14,081,321
[ 1, 588, 27595, 1165, 2316, 1338, 3981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 27595, 1165, 2316, 1435, 482, 1135, 12, 6430, 15329, 203, 3639, 2583, 261, 3576, 18, 15330, 422, 3174, 12645, 542, 16936, 1769, 203, 3639, 2583, 261, 5332, 28362, 1435, 597, 8657, 480, 374, 1769, 203, 3639, 2254, 5034, 7232, 329, 1090, 12645, 273, 4232, 39, 3462, 8252, 12, 1090, 12645, 2934, 12296, 951, 12, 2211, 24950, 1814, 77, 55, 1673, 31, 203, 3639, 4232, 39, 3462, 8252, 12, 1090, 12645, 2934, 13866, 12, 1090, 12645, 16936, 16, 7232, 329, 1090, 12645, 1769, 377, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6F3F365DbFC800fC0DdCA2Ce12ee665a01Be6bfD/sources/HexDex.sol
* Function for the frontend to dynamically retrieve the price scaling of sell orders./
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } ==========================================*/
2,887,632
[ 1, 2083, 364, 326, 15442, 358, 18373, 4614, 326, 6205, 10612, 434, 357, 80, 11077, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 41, 18664, 379, 8872, 12, 11890, 5034, 389, 7860, 774, 55, 1165, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 24899, 7860, 774, 55, 1165, 1648, 1147, 3088, 1283, 67, 1769, 203, 3639, 2254, 5034, 389, 546, 822, 379, 273, 2430, 774, 41, 18664, 379, 67, 24899, 7860, 774, 55, 1165, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 2892, 24899, 546, 822, 379, 16, 31945, 14667, 67, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 14060, 10477, 18, 1717, 24899, 546, 822, 379, 16, 389, 2892, 350, 5839, 1769, 203, 3639, 327, 389, 8066, 329, 41, 18664, 379, 31, 203, 565, 289, 203, 203, 225, 422, 4428, 1432, 5549, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../contracts/testContracts/TellorMaster.sol"; import "../contracts/testContracts/Tellor.sol"; import "./OracleIDDescriptions.sol"; import "../contracts/interfaces/ADOInterface.sol"; /** * @title UserContract * This contracts creates for easy integration to the Tellor Tellor System * This contract holds the Ether and Tributes for interacting with the system * Note it is centralized (we can set the price of Tellor Tributes) * Once the tellor system is running, this can be set properly. * Note deploy through centralized 'Tellor Master contract' */ contract UserContract is ADOInterface{ //in Loyas per ETH. so at 200$ ETH price and 3$ Trib price -- (3/200 * 1e18) uint256 public tributePrice; address payable public owner; address payable public tellorStorageAddress; address public oracleIDDescriptionsAddress; Tellor _tellor; TellorMaster _tellorm; OracleIDDescriptions descriptions; event OwnershipTransferred(address _previousOwner, address _newOwner); event NewPriceSet(uint256 _newPrice); event NewDescriptorSet(address _descriptorSet); /*Constructor*/ /** * @dev the constructor sets the storage address and owner * @param _storage is the TellorMaster address ??? */ constructor(address payable _storage) public { tellorStorageAddress = _storage; _tellor = Tellor(tellorStorageAddress); //we should delcall here _tellorm = TellorMaster(tellorStorageAddress); owner = msg.sender; } /*Functions*/ /* * @dev Allows the owner to set the address for the oracleID descriptors * used by the ADO members for price key value pairs standarization * _oracleDescriptos is the address for the OracleIDDescptions contract */ function setOracleIDDescriptors(address _oracleDescriptors) external { require(msg.sender == owner, "Sender is not owner"); oracleIDDescriptionsAddress = _oracleDescriptors; descriptions = OracleIDDescriptions(_oracleDescriptors); emit NewDescriptorSet(_oracleDescriptors); } /** * @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 payable newOwner) external { require(msg.sender == owner, "Sender is not owner"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev This function allows the owner to withdraw the ETH paid for requests */ function withdrawEther() external { require(msg.sender == owner, "Sender is not owner"); owner.transfer(address(this).balance); } /** * @dev Allows the contract owner(Tellor) to withdraw any Tributes left on this contract */ function withdrawTokens() external { require(msg.sender == owner, "Sender is not owner"); _tellor.transfer(owner, _tellorm.balanceOf(address(this))); } /** * @dev Allows the user to submit a request for data to the oracle using ETH * @param c_sapi string API being requested to be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value */ function requestDataWithEther(string calldata c_sapi, string calldata _c_symbol, uint256 _granularity) external payable { uint _amount = (msg.value / tributePrice)*1e18; require(_tellorm.balanceOf(address(this)) >= _amount, "Balance is lower than tip amount"); _tellor.requestData(c_sapi, _c_symbol, _granularity, _amount); } /** * @dev Allows the user to tip miners using ether * @param _apiId to tip */ function addTipWithEther(uint256 _apiId) external payable { uint _amount = (msg.value / tributePrice)*1e18; require(_tellorm.balanceOf(address(this)) >= _amount, "Balance is lower than tip amount"); _tellor.addTip(_apiId, _amount); } /** * @dev Allows the owner to set the Tribute token price. * @param _price to set for Tellor Tribute token */ function setPrice(uint256 _price) public { require(msg.sender == owner, "Sender is not owner"); tributePrice = _price; emit NewPriceSet(_price); } /** * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return bool true if it is able to retreive a value, the value, and the value's timestamp */ function getCurrentValue(uint256 _requestId) public view returns (bool ifRetrieve, uint256 value, uint256 _timestampRetrieved) { uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId); if (_count > 0) { _timestampRetrieved = _tellorm.getTimestampbyRequestIDandIndex(_requestId, _count - 1); //will this work with a zero index? (or insta hit?) return (true, _tellorm.retrieveData(_requestId, _timestampRetrieved), _timestampRetrieved); } return (false, 0, 0); } /** * @dev Allows the user to get the latest value for the requestId specified using the * ADO specification for the standard inteface for price oracles * @param _bytesId is the ADO standarized bytes32 price/key value pair identifier * @return the timestamp, outcome or value/ and the status code (for retreived, null, etc...) */ function resultFor(bytes32 _bytesId) view external returns (uint256 timestamp, int outcome, int status) { uint _id = descriptions.getTellorIdFromBytes(_bytesId); if (_id > 0){ bool _didGet; uint256 _returnedValue; uint256 _timestampRetrieved; (_didGet,_returnedValue,_timestampRetrieved) = getCurrentValue(_id); if(_didGet){ return (_timestampRetrieved, int(_returnedValue),descriptions.getStatusFromTellorStatus(1)); } else{ return (0,0,descriptions.getStatusFromTellorStatus(2)); } } return (0, 0, descriptions.getStatusFromTellorStatus(0)); } /** * @dev Allows the user to get the first verified value for the requestId after the specified timestamp * @param _requestId is the requestId to look up the value for * @param _timestamp after which to search for first verified value * @return bool true if it is able to retreive a value, the value, and the value's timestamp, the timestamp after * which it searched for the first verified value */ function getFirstVerifiedDataAfter(uint256 _requestId, uint256 _timestamp) public view returns (bool, uint256, uint256 _timestampRetrieved) { uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId); if (_count > 0) { for (uint256 i = _count; i > 0; i--) { if ( _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1) > _timestamp && _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1) < block.timestamp - 86400 ) { _timestampRetrieved = _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1); //will this work with a zero index? (or insta hit?) } } if (_timestampRetrieved > 0) { return (true, _tellorm.retrieveData(_requestId, _timestampRetrieved), _timestampRetrieved); } } return (false, 0, 0); } /** * @dev Allows the user to get the first value for the requestId after the specified timestamp * @param _requestId is the requestId to look up the value for * @param _timestamp after which to search for first verified value * @return bool true if it is able to retreive a value, the value, and the value's timestamp */ function getAnyDataAfter(uint256 _requestId, uint256 _timestamp) public view returns (bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved) { uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId); if (_count > 0) { for (uint256 i = _count; i > 0; i--) { if (_tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1) >= _timestamp) { _timestampRetrieved = _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1); //will this work with a zero index? (or insta hit?) } } if (_timestampRetrieved > 0) { return (true, _tellorm.retrieveData(_requestId, _timestampRetrieved), _timestampRetrieved); } } return (false, 0, 0); } }
* @dev Allows the user to tip miners using ether @param _apiId to tip/
function addTipWithEther(uint256 _apiId) external payable { uint _amount = (msg.value / tributePrice)*1e18; require(_tellorm.balanceOf(address(this)) >= _amount, "Balance is lower than tip amount"); _tellor.addTip(_apiId, _amount); }
12,578,533
[ 1, 19132, 326, 729, 358, 9529, 1131, 414, 1450, 225, 2437, 225, 389, 2425, 548, 358, 9529, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 14189, 1190, 41, 1136, 12, 11890, 5034, 389, 2425, 548, 13, 3903, 8843, 429, 288, 203, 3639, 2254, 389, 8949, 273, 261, 3576, 18, 1132, 342, 433, 495, 624, 5147, 17653, 21, 73, 2643, 31, 203, 3639, 2583, 24899, 88, 1165, 535, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 389, 8949, 16, 315, 13937, 353, 2612, 2353, 9529, 3844, 8863, 203, 3639, 389, 88, 1165, 280, 18, 1289, 14189, 24899, 2425, 548, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title It holds the storage variables related to ERC20DividendCheckpoint module */ contract ERC20DividendCheckpointStorage { // Mapping to token address for each dividend mapping (uint256 => address) public dividendTokens; } /** * @title Holds the storage variable for the DividendCheckpoint modules (i.e ERC20, Ether) * @dev abstract contract */ contract DividendCheckpointStorage { // Address to which reclaimed dividends and withholding tax is sent address public wallet; uint256 public EXCLUDED_ADDRESS_LIMIT = 150; bytes32 public constant DISTRIBUTE = "DISTRIBUTE"; bytes32 public constant MANAGE = "MANAGE"; bytes32 public constant CHECKPOINT = "CHECKPOINT"; struct Dividend { uint256 checkpointId; uint256 created; // Time at which the dividend was created uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer - // set to very high value to bypass uint256 amount; // Dividend amount in WEI uint256 claimedAmount; // Amount of dividend claimed so far uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this) bool reclaimed; // True if expiry has passed and issuer has reclaimed remaining dividend uint256 totalWithheld; uint256 totalWithheldWithdrawn; mapping (address => bool) claimed; // List of addresses which have claimed dividend mapping (address => bool) dividendExcluded; // List of addresses which cannot claim dividends mapping (address => uint256) withheld; // Amount of tax withheld from claim bytes32 name; // Name/title - used for identification } // List of all dividends Dividend[] public dividends; // List of addresses which cannot claim dividends address[] public excluded; // Mapping from address to withholding tax as a percentage * 10**16 mapping (address => uint256) public withholdingTax; } /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ 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() internal view returns (address); /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function _fallback() internal { _delegate(_implementation()); } /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function _delegate(address implementation) internal { /*solium-disable-next-line security/no-inline-assembly*/ assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } function () public payable { _fallback(); } } /** * @title OwnedProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedProxy is Proxy { // Owner of the contract address private __owner; // Address of the current implementation address internal __implementation; /** * @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 Throws if called by any account other than the owner. */ modifier ifOwner() { if (msg.sender == _owner()) { _; } else { _fallback(); } } /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor() public { _setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function _owner() internal view returns (address) { return __owner; } /** * @dev Sets the address of the owner */ function _setOwner(address _newOwner) internal { require(_newOwner != address(0), "Address should not be 0x"); __owner = _newOwner; } /** * @notice Internal function to provide the address of the implementation contract */ function _implementation() internal view returns (address) { return __implementation; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() external ifOwner returns (address) { return _owner(); } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() external ifOwner returns (address) { return _implementation(); } /** * @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) external ifOwner { require(_newOwner != address(0), "Address should not be 0x"); emit ProxyOwnershipTransferred(_owner(), _newOwner); _setOwner(_newOwner); } } /** * @title Utility contract to allow pausing and unpausing of certain functions */ contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Contract is paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Contract is not paused"); _; } /** * @notice Called by the owner to pause, triggers stopped state */ function _pause() internal whenNotPaused { paused = true; /*solium-disable-next-line security/no-block-members*/ emit Pause(now); } /** * @notice Called by the owner to unpause, returns to normal state */ function _unpause() internal whenPaused { paused = false; /*solium-disable-next-line security/no-block-members*/ emit Unpause(now); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function decimals() external view 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 transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool); function increaseApproval(address _spender, uint _addedValue) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Storage for Module contract * @notice Contract is abstract */ contract ModuleStorage { /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = IERC20(_polyAddress); } address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; IERC20 public polyToken; } /** * @title Transfer Manager module for core transfer validation functionality */ contract ERC20DividendCheckpointProxy is ERC20DividendCheckpointStorage, DividendCheckpointStorage, ModuleStorage, Pausable, OwnedProxy { /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken * @param _implementation representing the address of the new implementation to be set */ constructor (address _securityToken, address _polyAddress, address _implementation) public ModuleStorage(_securityToken, _polyAddress) { require( _implementation != address(0), "Implementation address should not be 0x" ); __implementation = _implementation; } } /** * @title Utility contract for reusable code */ library Util { /** * @notice Changes a string to upper case * @param _base String to change */ function upper(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1)-32); } _baseBytes[i] = b1; } return string(_baseBytes); } /** * @notice Changes the string into bytes32 * @param _source String that need to convert into bytes32 */ /// Notice - Maximum Length for _source will be 32 chars otherwise returned bytes32 value will have lossy value. function stringToBytes32(string memory _source) internal pure returns (bytes32) { return bytesToBytes32(bytes(_source), 0); } /** * @notice Changes bytes into bytes32 * @param _b Bytes that need to convert into bytes32 * @param _offset Offset from which to begin conversion */ /// Notice - Maximum length for _source will be 32 chars otherwise returned bytes32 value will have lossy value. function bytesToBytes32(bytes _b, uint _offset) internal pure returns (bytes32) { bytes32 result; for (uint i = 0; i < _b.length; i++) { result |= bytes32(_b[_offset + i] & 0xFF) >> (i * 8); } return result; } /** * @notice Changes the bytes32 into string * @param _source that need to convert into string */ function bytes32ToString(bytes32 _source) internal pure returns (string result) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(_source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } /** * @notice Gets function signature from _data * @param _data Passed data * @return bytes4 sig */ function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } } interface IBoot { /** * @notice This function returns the signature of configure function * @return bytes4 Configure function signature */ function getInitFunction() external pure returns(bytes4); } /** * @title Interface that every module factory contract should implement */ interface IModuleFactory { event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory); event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event GenerateModuleFromFactory( address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _setupCost, uint256 _timestamp ); event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch); //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]); /** * @notice Get the name of the Module */ function getName() external view returns(bytes32); /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() external view returns (bytes32[]); /** * @notice Used to change the setup fee * @param _newSetupCost New setup fee */ function changeFactorySetupFee(uint256 _newSetupCost) external; /** * @notice Used to change the usage fee * @param _newUsageCost New usage fee */ function changeFactoryUsageFee(uint256 _newUsageCost) external; /** * @notice Used to change the subscription fee * @param _newSubscriptionCost New subscription fee */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) external; /** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion New version array */ function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external; /** * @notice Get the setup cost of the module */ function getSetupCost() external view returns (uint256); /** * @notice Used to get the lower bound * @return Lower bound */ function getLowerSTVersionBounds() external view returns(uint8[]); /** * @notice Used to get the upper bound * @return Upper bound */ function getUpperSTVersionBounds() external view returns(uint8[]); } /** * @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; } } /** * @title Helper library use to compare or validate the semantic versions */ library VersionUtils { /** * @notice This function is used to validate the version submitted * @param _current Array holds the present version of ST * @param _new Array holds the latest version of the ST * @return bool */ function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) { bool[] memory _temp = new bool[](_current.length); uint8 counter = 0; for (uint8 i = 0; i < _current.length; i++) { if (_current[i] < _new[i]) _temp[i] = true; else _temp[i] = false; } for (i = 0; i < _current.length; i++) { if (i == 0) { if (_current[i] <= _new[i]) if(_temp[0]) { counter = counter + 3; break; } else counter++; else return false; } else { if (_temp[i-1]) counter++; else if (_current[i] <= _new[i]) counter++; else return false; } } if (counter == _current.length) return true; } /** * @notice Used to compare the lower bound with the latest version * @param _version1 Array holds the lower bound of the version * @param _version2 Array holds the latest version of the ST * @return bool */ function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) { require(_version1.length == _version2.length, "Input length mismatch"); uint counter = 0; for (uint8 j = 0; j < _version1.length; j++) { if (_version1[j] == 0) counter ++; } if (counter != _version1.length) { counter = 0; for (uint8 i = 0; i < _version1.length; i++) { if (_version2[i] > _version1[i]) return true; else if (_version2[i] < _version1[i]) return false; else counter++; } if (counter == _version1.length - 1) return true; else return false; } else return true; } /** * @notice Used to compare the upper bound with the latest version * @param _version1 Array holds the upper bound of the version * @param _version2 Array holds the latest version of the ST * @return bool */ function compareUpperBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) { require(_version1.length == _version2.length, "Input length mismatch"); uint counter = 0; for (uint8 j = 0; j < _version1.length; j++) { if (_version1[j] == 0) counter ++; } if (counter != _version1.length) { counter = 0; for (uint8 i = 0; i < _version1.length; i++) { if (_version1[i] > _version2[i]) return true; else if (_version1[i] < _version2[i]) return false; else counter++; } if (counter == _version1.length - 1) return true; else return false; } else return true; } /** * @notice Used to pack the uint8[] array data into uint24 value * @param _major Major version * @param _minor Minor version * @param _patch Patch version */ function pack(uint8 _major, uint8 _minor, uint8 _patch) internal pure returns(uint24) { return (uint24(_major) << 16) | (uint24(_minor) << 8) | uint24(_patch); } /** * @notice Used to convert packed data into uint8 array * @param _packedVersion Packed data */ function unpack(uint24 _packedVersion) internal pure returns (uint8[]) { uint8[] memory _unpackVersion = new uint8[](3); _unpackVersion[0] = uint8(_packedVersion >> 16); _unpackVersion[1] = uint8(_packedVersion >> 8); _unpackVersion[2] = uint8(_packedVersion); return _unpackVersion; } } /** * @title Interface that any module factory contract should implement * @notice Contract is abstract */ contract ModuleFactory is IModuleFactory, Ownable { IERC20 public polyToken; uint256 public usageCost; uint256 public monthlySubscriptionCost; uint256 public setupCost; string public description; string public version; bytes32 public name; string public title; // @notice Allow only two variables to be stored // 1. lowerBound // 2. upperBound // @dev (0.0.0 will act as the wildcard) // @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch mapping(string => uint24) compatibleSTVersionRange; /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = IERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } /** * @notice Used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { emit ChangeFactorySetupFee(setupCost, _newSetupCost, address(this)); setupCost = _newSetupCost; } /** * @notice Used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { emit ChangeFactoryUsageFee(usageCost, _newUsageCost, address(this)); usageCost = _newUsageCost; } /** * @notice Used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this)); monthlySubscriptionCost = _newSubscriptionCost; } /** * @notice Updates the title of the ModuleFactory * @param _newTitle New Title that will replace the old one. */ function changeTitle(string _newTitle) public onlyOwner { require(bytes(_newTitle).length > 0, "Invalid title"); title = _newTitle; } /** * @notice Updates the description of the ModuleFactory * @param _newDesc New description that will replace the old one. */ function changeDescription(string _newDesc) public onlyOwner { require(bytes(_newDesc).length > 0, "Invalid description"); description = _newDesc; } /** * @notice Updates the name of the ModuleFactory * @param _newName New name that will replace the old one. */ function changeName(bytes32 _newName) public onlyOwner { require(_newName != bytes32(0),"Invalid name"); name = _newName; } /** * @notice Updates the version of the ModuleFactory * @param _newVersion New name that will replace the old one. */ function changeVersion(string _newVersion) public onlyOwner { require(bytes(_newVersion).length > 0, "Invalid version"); version = _newVersion; } /** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion new version array */ function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")), "Must be a valid bound type" ); require(_newVersion.length == 3); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version"); } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } /** * @notice Used to get the lower bound * @return lower bound */ function getLowerSTVersionBounds() external view returns(uint8[]) { return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]); } /** * @notice Used to get the upper bound * @return upper bound */ function getUpperSTVersionBounds() external view returns(uint8[]) { return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]); } /** * @notice Get the setup cost of the module */ function getSetupCost() external view returns (uint256) { return setupCost; } /** * @notice Get the name of the Module */ function getName() public view returns(bytes32) { return name; } } /** * @title Factory for deploying ERC20DividendCheckpoint module */ contract ERC20DividendCheckpointFactory is ModuleFactory { address public logicContract; /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module * @param _logicContract Contract address that contains the logic related to `description` */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost, address _logicContract) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { require(_logicContract != address(0), "Invalid logic contract"); version = "2.1.1"; name = "ERC20DividendCheckpoint"; title = "ERC20 Dividend Checkpoint"; description = "Create ERC20 dividends for token holders at a specific checkpoint"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); logicContract = _logicContract; } /** * @notice Used to launch the Module with the help of factory * @return Address Contract address of the Module */ function deploy(bytes _data) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "insufficent allowance"); address erc20DividendCheckpoint = new ERC20DividendCheckpointProxy(msg.sender, address(polyToken), logicContract); //Checks that _data is valid (not calling anything it shouldn't) require(Util.getSig(_data) == IBoot(erc20DividendCheckpoint).getInitFunction(), "Invalid data"); /*solium-disable-next-line security/no-low-level-calls*/ require(erc20DividendCheckpoint.call(_data), "Unsuccessfull call"); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(erc20DividendCheckpoint, getName(), address(this), msg.sender, setupCost, now); return erc20DividendCheckpoint; } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 4; return res; } /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns(string) { return "Create ERC20 dividend to be paid out to token holders based on their balances at dividend creation time"; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](3); availableTags[0] = "ERC20"; availableTags[1] = "Dividend"; availableTags[2] = "Checkpoint"; return availableTags; } }
* @dev Fallback function allowing to perform a delegatecall to the given implementation. This function will return whatever the implementation call returns/solium-disable-next-line security/no-inline-assembly*/ Copy msg.data. We take full control of memory in this inline assembly block because it will not return to Solidity code. We overwrite the Solidity scratch pad at memory position 0. Call the implementation. out and outsize are 0 because we don't know the size yet. Copy the returned data. delegatecall returns 0 on error.
function _delegate(address implementation) internal { assembly { calldatacopy(0, 0, calldatasize) let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch result } }
926,180
[ 1, 12355, 445, 15632, 358, 3073, 279, 7152, 1991, 358, 326, 864, 4471, 18, 1220, 445, 903, 327, 15098, 326, 4471, 745, 1135, 19, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 19, 5631, 1234, 18, 892, 18, 1660, 4862, 1983, 3325, 434, 3778, 316, 333, 6370, 19931, 1203, 2724, 518, 903, 486, 327, 358, 348, 7953, 560, 981, 18, 1660, 6156, 326, 348, 7953, 560, 15289, 4627, 622, 3778, 1754, 374, 18, 3049, 326, 4471, 18, 596, 471, 596, 1467, 854, 374, 2724, 732, 2727, 1404, 5055, 326, 963, 4671, 18, 5631, 326, 2106, 501, 18, 7152, 1991, 1135, 374, 603, 555, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 22216, 12, 2867, 4471, 13, 2713, 288, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 13, 203, 203, 5411, 2231, 563, 519, 7152, 1991, 12, 31604, 16, 4471, 16, 374, 16, 745, 13178, 554, 16, 374, 16, 374, 13, 203, 203, 5411, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 13, 203, 203, 5411, 1620, 563, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; /** OpenZeppelin Dependencies */ // import "@openzeppelin/contracts-upgradeable/contracts/proxy/Initializable.sol"; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; /** Uniswap */ import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; /** Local Interfaces */ import './interfaces/IToken.sol'; import './interfaces/IAuction.sol'; import './interfaces/IStaking.sol'; import './interfaces/IAuctionV1.sol'; contract Auction is IAuction, Initializable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; /** Events */ event Bid( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time ); event VentureBid( address indexed account, uint256 ethBid, uint256 indexed auctionId, uint256 time, address[] coins, uint256[] amountBought ); event Withdraval( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time, uint256 stakeDays ); event AuctionIsOver(uint256 eth, uint256 token, uint256 indexed auctionId); /** Structs */ struct AuctionReserves { uint256 eth; // Amount of Eth in the auction uint256 token; // Amount of Axn in auction for day uint256 uniswapLastPrice; // Last known uniswap price from last bid uint256 uniswapMiddlePrice; // Using middle price days to calculate avg price } struct UserBid { uint256 eth; // Amount of ethereum address ref; // Referrer address for bid bool withdrawn; // Determine withdrawn } struct Addresses { address mainToken; // Axion token address address staking; // Staking platform address payable uniswap; // Uniswap Main Router address payable recipient; // Origin address for excess ethereum in auction } struct Options { uint256 autoStakeDays; // # of days bidder must stake once axion is won from auction uint256 referrerPercent; // Referral Bonus % uint256 referredPercent; // Referral Bonus % bool referralsOn; // If on referrals are used on auction uint256 discountPercent; // Discount in comparison to uniswap price in auction uint256 premiumPercent; // Premium in comparions to unsiwap price in auction } /** Roles */ bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE'); bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE'); bytes32 public constant CALLER_ROLE = keccak256('CALLER_ROLE'); /** Mapping */ mapping(uint256 => AuctionReserves) public reservesOf; // [day], mapping(address => uint256[]) public auctionsOf; mapping(uint256 => mapping(address => UserBid)) public auctionBidOf; mapping(uint256 => mapping(address => bool)) public existAuctionsOf; /** Simple types */ uint256 public lastAuctionEventId; // Index for Auction uint256 public lastAuctionEventIdV1; // Last index for layer 1 auction uint256 public start; // Beginning of contract uint256 public stepTimestamp; // # of seconds per "axion day" (86400) Options public options; // Auction options (see struct above) Addresses public addresses; // (See Address struct above) IAuctionV1 public auctionV1; // V1 Auction contract for backwards compatibility bool public init_; // Unneeded legacy variable to ensure init is only called once. mapping(uint256 => mapping(address => uint256)) public autoStakeDaysOf; // NOT USED uint256 public middlePriceDays; // When calculating auction price this is used to determine average struct VentureToken { address coin; // address of token to buy from swap uint96 percentage; // % of token to buy NOTE: (On a VCA day all Venture tokens % should add up to 100%) } struct AuctionData { uint8 mode; // 1 = VCA, 0 = Normal Auction VentureToken[] tokens; // Tokens to buy in VCA } AuctionData[7] internal auctions; // 7 values for 7 days of the week uint8 internal ventureAutoStakeDays; // # of auto stake days for VCA Auction /* UGPADEABILITY: New variables must go below here. */ /** modifiers */ modifier onlyCaller() { require( hasRole(CALLER_ROLE, _msgSender()), 'Caller is not a caller role' ); _; } modifier onlyManager() { require( hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager role' ); _; } modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, _msgSender()), 'Caller is not a migrator' ); _; } /** Update Price of current auction Get current axion day Get uniswapLastPrice Set middlePrice */ function _updatePrice() internal { uint256 currentAuctionId = getCurrentAuctionId(); /** Set reserves of */ reservesOf[currentAuctionId].uniswapLastPrice = getUniswapLastPrice(); reservesOf[currentAuctionId] .uniswapMiddlePrice = getUniswapMiddlePriceForDays(); } /** Get token paths Use uniswap to buy tokens back and send to staking platform using (addresses.staking) @param tokenAddress {address} - Token to buy from uniswap @param amountOutMin {uint256} - Slippage tolerance for router @param amount {uint256} - Min amount expected @param deadline {uint256} - Deadline for trade (used for uniswap router) */ function _swapEthForToken( address tokenAddress, uint256 amountOutMin, uint256 amount, uint256 deadline ) private returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = tokenAddress; return IUniswapV2Router02(addresses.uniswap).swapExactETHForTokens{ value: amount }(amountOutMin, path, addresses.staking, deadline)[1]; } /** Bid function which routes to either venture bid or bid internal @param amountOutMin {uint256[]} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param ref {address} - Referrer Address to get % axion from bid */ function bid( uint256[] calldata amountOutMin, uint256 deadline, address ref ) external payable { uint256 currentDay = getCurrentDay(); uint8 auctionMode = auctions[currentDay].mode; if (auctionMode == 0) { bidInternal(amountOutMin[0], deadline, ref); } else if (auctionMode == 1) { ventureBid(amountOutMin, deadline, currentDay); } } /** BidInternal - Buys back axion from uniswap router and sends to staking platform @param amountOutMin {uint256} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param ref {address} - Referrer Address to get % axion from bid */ function bidInternal( uint256 amountOutMin, uint256 deadline, address ref ) internal { _saveAuctionData(); _updatePrice(); /** Can not refer self */ require(_msgSender() != ref, 'msg.sender == ref'); /** Get percentage for recipient and uniswap (Extra function really unnecessary) */ (uint256 toRecipient, uint256 toUniswap) = _calculateRecipientAndUniswapAmountsToSend(); /** Buy back tokens from uniswap and send to staking contract */ _swapEthForToken( addresses.mainToken, amountOutMin, toUniswap, deadline ); /** Get Auction ID */ uint256 auctionId = getCurrentAuctionId(); /** If referralsOn is true allow to set ref */ if (options.referralsOn == true) { auctionBidOf[auctionId][_msgSender()].ref = ref; } /** Run common shared functionality between VCA and Normal */ bidCommon(auctionId); /** Transfer any eithereum in contract to recipient address */ addresses.recipient.transfer(toRecipient); /** Send event to blockchain */ emit Bid(msg.sender, msg.value, auctionId, now); } /** BidInternal - Buys back axion from uniswap router and sends to staking platform @param amountOutMin {uint256[]} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param currentDay {uint256} - currentAuctionId */ function ventureBid( uint256[] memory amountOutMin, uint256 deadline, uint256 currentDay ) internal { _saveAuctionData(); _updatePrice(); /** Get the token(s) of the day */ VentureToken[] storage tokens = auctions[currentDay].tokens; /** Create array to determine amount bought for each token */ address[] memory coinsBought = new address[](tokens.length); uint256[] memory amountsBought = new uint256[](tokens.length); /** Loop over tokens to purchase */ for (uint8 i = 0; i < tokens.length; i++) { /** Determine amount to purchase based on ethereum bid */ uint256 amountBought; uint256 amountToBuy = msg.value.mul(tokens[i].percentage).div(100); /** If token is 0xFFfFfF... we buy no token and just distribute the bidded ethereum */ if ( tokens[i].coin != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { amountBought = _swapEthForToken( tokens[i].coin, amountOutMin[i], amountToBuy, deadline ); IStaking(addresses.staking).updateTokenPricePerShare( msg.sender, addresses.recipient, tokens[i].coin, amountBought ); } else { amountBought = amountToBuy; IStaking(addresses.staking).updateTokenPricePerShare{ value: amountToBuy }(msg.sender, addresses.recipient, tokens[i].coin, amountToBuy); // Payable amount } coinsBought[i] = tokens[i].coin; amountsBought[i] = amountBought; } uint256 currentAuctionId = getCurrentAuctionId(); bidCommon(currentAuctionId); emit VentureBid( msg.sender, msg.value, currentAuctionId, now, coinsBought, amountsBought ); } /** Bid Common - Set common values for bid @param auctionId (uint256) - ID of auction */ function bidCommon(uint256 auctionId) internal { /** Set auctionBid for bidder */ auctionBidOf[auctionId][_msgSender()].eth = auctionBidOf[auctionId][ _msgSender() ] .eth .add(msg.value); /** Set existsOf in order to include all auction bids for current user into one */ if (!existAuctionsOf[auctionId][_msgSender()]) { auctionsOf[_msgSender()].push(auctionId); existAuctionsOf[auctionId][_msgSender()] = true; } reservesOf[auctionId].eth = reservesOf[auctionId].eth.add(msg.value); } /** getUniswapLastPrice - Use uniswap router to determine current price based on ethereum */ function getUniswapLastPrice() internal view returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = addresses.mainToken; uint256 price = IUniswapV2Router02(addresses.uniswap).getAmountsOut(1e18, path)[1]; return price; } /** getUniswapMiddlePriceForDays Use the "last known price" for the last {middlePriceDays} days to determine middle price by taking an average */ function getUniswapMiddlePriceForDays() internal view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); uint256 index = currentAuctionId; uint256 sum; uint256 points; while (points != middlePriceDays) { if (reservesOf[index].uniswapLastPrice != 0) { sum = sum.add(reservesOf[index].uniswapLastPrice); points = points.add(1); } if (index == 0) break; index = index.sub(1); } if (sum == 0) return getUniswapLastPrice(); else return sum.div(points); } /** withdraw - Withdraws an auction bid and stakes axion in staking contract @param auctionId {uint256} - Auction to withdraw from @param stakeDays {uint256} - # of days to stake in portal */ function withdraw(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); /** Require the # of days staking > options */ uint8 auctionMode = auctions[auctionId.mod(7)].mode; if (auctionMode == 0) { require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); } else if (auctionMode == 1) { require( stakeDays >= ventureAutoStakeDays, 'Auction: stakeDays < minimum days' ); } /** Require # of staking days < 5556 */ require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 currentAuctionId = getCurrentAuctionId(); UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; /** Ensure auctionId of withdraw is not todays auction, and user bid has not been withdrawn and eth > 0 */ require(currentAuctionId > auctionId, 'Auction: Auction is active'); require( userBid.eth > 0 && userBid.withdrawn == false, 'Auction: Zero bid or withdrawn' ); /** Set Withdrawn to true */ userBid.withdrawn = true; /** Call common withdraw functions */ withdrawInternal( userBid.ref, userBid.eth, auctionId, currentAuctionId, stakeDays ); } /** withdraw - Withdraws an auction bid and stakes axion in staking contract @param auctionId {uint256} - Auction to withdraw from @param stakeDays {uint256} - # of days to stake in portal NOTE: No longer needed, as there is most likely not more bids from v1 that have not been withdraw */ function withdrawV1(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); // Backward compatability with v1 auction require( auctionId <= lastAuctionEventIdV1, 'Auction: Invalid auction id' ); /** Ensure stake days > options */ require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 currentAuctionId = getCurrentAuctionId(); require(currentAuctionId > auctionId, 'Auction: Auction is active'); /** This stops a user from using WithdrawV1 twice, since the bid is put into memory at the end */ UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require( userBid.eth == 0 && userBid.withdrawn == false, 'Auction: Invalid auction ID' ); (uint256 eth, address ref) = auctionV1.auctionBetOf(auctionId, _msgSender()); require(eth > 0, 'Auction: Zero balance in auction/invalid auction ID'); /** Common withdraw functionality */ withdrawInternal(ref, eth, auctionId, currentAuctionId, stakeDays); /** Bring v1 auction bid to v2 */ auctionBidOf[auctionId][_msgSender()] = UserBid({ eth: eth, ref: ref, withdrawn: true }); auctionsOf[_msgSender()].push(auctionId); } function withdrawInternal( address ref, uint256 eth, uint256 auctionId, uint256 currentAuctionId, uint256 stakeDays ) internal { /** Calculate payout for bidder */ uint256 payout = _calculatePayout(auctionId, eth); uint256 uniswapPayoutWithPercent = _calculatePayoutWithUniswap(auctionId, eth, payout); /** If auction is undersold, send overage to weekly auction */ if (payout > uniswapPayoutWithPercent) { uint256 nextWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nextWeeklyAuction].token = reservesOf[nextWeeklyAuction] .token .add(payout.sub(uniswapPayoutWithPercent)); payout = uniswapPayoutWithPercent; } /** If referrer is empty simple task */ if (address(ref) == address(0)) { /** Burn tokens and then call external stake on staking contract */ IToken(addresses.mainToken).burn(address(this), payout); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval( msg.sender, payout, currentAuctionId, now, stakeDays ); } else { /** Burn tokens and determine referral amount */ IToken(addresses.mainToken).burn(address(this), payout); (uint256 toRefMintAmount, uint256 toUserMintAmount) = _calculateRefAndUserAmountsToMint(payout); /** Add referral % to payout */ payout = payout.add(toUserMintAmount); /** Call external stake for referrer and bidder */ IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); /** We do not want to mint if the referral address is the dEaD address */ if(address(ref) != address(0x000000000000000000000000000000000000dEaD)) { IStaking(addresses.staking).externalStake(toRefMintAmount, 14, ref); } emit Withdraval( msg.sender, payout, currentAuctionId, now, stakeDays ); } } /** External Contract Caller functions @param amount {uint256} - amount to add to next dailyAuction */ function callIncomeDailyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to tomorrows auction uint256 currentAuctionId = getCurrentAuctionId(); uint256 nextAuctionId = currentAuctionId + 1; reservesOf[nextAuctionId].token = reservesOf[nextAuctionId].token.add( amount ); } /** Add Reserves to specified Auction @param daysInFuture {uint256} - CurrentAuctionId + daysInFuture to send Axion to @param amount {uint256} - Amount of axion to add to auction */ function addReservesToAuction(uint256 daysInFuture, uint256 amount) external override onlyCaller returns (uint256) { // Adds a specified amount of axion to a future auction require( daysInFuture <= 365, 'AUCTION: Days in future can not be greater then 365' ); uint256 currentAuctionId = getCurrentAuctionId(); uint256 auctionId = currentAuctionId + daysInFuture; reservesOf[auctionId].token = reservesOf[auctionId].token.add(amount); return auctionId; } /** Add reserves to next weekly auction @param amount {uint256} - Amount of axion to add to auction */ function callIncomeWeeklyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to the next nearest weekly auction uint256 nearestWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nearestWeeklyAuction].token = reservesOf[ nearestWeeklyAuction ] .token .add(amount); } /** Calculate functions */ function calculateNearestWeeklyAuction() public view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); return currentAuctionId.add(uint256(7).sub(currentAuctionId.mod(7))); } /** Get current day of week * EX: friday = 0, saturday = 1, sunday = 2 etc... */ function getCurrentDay() internal view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); return currentAuctionId.mod(7); } function getCurrentAuctionId() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } function calculateStepsFromStart() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } /** Determine payout and overage @param auctionId {uint256} - Auction id to calculate price from @param amount {uint256} - Amount to use to determine overage @param payout {uint256} - payout */ function _calculatePayoutWithUniswap( uint256 auctionId, uint256 amount, uint256 payout ) internal view returns (uint256) { // Get payout for user uint256 uniswapPayout = reservesOf[auctionId].uniswapMiddlePrice.mul(amount).div(1e18); // Get payout with percentage based on discount, premium uint256 uniswapPayoutWithPercent = uniswapPayout .add(uniswapPayout.mul(options.discountPercent).div(100)) .sub(uniswapPayout.mul(options.premiumPercent).div(100)); if (payout > uniswapPayoutWithPercent) { return uniswapPayoutWithPercent; } else { return payout; } } /** Determine payout based on amount of token and ethereum @param auctionId {uint256} - auction to determine payout of @param amount {uint256} - amount of axion */ function _calculatePayout(uint256 auctionId, uint256 amount) internal view returns (uint256) { return amount.mul(reservesOf[auctionId].token).div( reservesOf[auctionId].eth ); } /** Get Percentages for recipient and uniswap for ethereum bid Unnecessary function */ function _calculateRecipientAndUniswapAmountsToSend() private returns (uint256, uint256) { uint256 toRecipient = msg.value.mul(20).div(100); uint256 toUniswap = msg.value.sub(toRecipient); return (toRecipient, toUniswap); } /** Determine amount of axion to mint for referrer based on amount @param amount {uint256} - amount of axion @return (uint256, uint256) */ function _calculateRefAndUserAmountsToMint(uint256 amount) private view returns (uint256, uint256) { uint256 toRefMintAmount = amount.mul(options.referrerPercent).div(100); uint256 toUserMintAmount = amount.mul(options.referredPercent).div(100); return (toRefMintAmount, toUserMintAmount); } /** Save auction data Determines if auction is over. If auction is over set lastAuctionId to currentAuctionId */ function _saveAuctionData() internal { uint256 currentAuctionId = getCurrentAuctionId(); AuctionReserves memory reserves = reservesOf[lastAuctionEventId]; if (lastAuctionEventId < currentAuctionId) { emit AuctionIsOver( reserves.eth, reserves.token, lastAuctionEventId ); lastAuctionEventId = currentAuctionId; } } function initialize(address _manager, address _migrator) public initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); init_ = false; } /** Public Setter Functions */ function setReferrerPercentage(uint256 percent) external onlyManager { options.referrerPercent = percent; } function setReferredPercentage(uint256 percent) external onlyManager { options.referredPercent = percent; } function setReferralsOn(bool _referralsOn) external onlyManager { options.referralsOn = _referralsOn; } function setAutoStakeDays(uint256 _autoStakeDays) external onlyManager { options.autoStakeDays = _autoStakeDays; } function setVentureAutoStakeDays(uint8 _autoStakeDays) external onlyManager { ventureAutoStakeDays = _autoStakeDays; } function setDiscountPercent(uint256 percent) external onlyManager { options.discountPercent = percent; } function setPremiumPercent(uint256 percent) external onlyManager { options.premiumPercent = percent; } function setMiddlePriceDays(uint256 _middleDays) external onlyManager { middlePriceDays = _middleDays; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } /** VCA Setters */ /** @param _day {uint8} 0 - 6 value. 0 represents Saturday, 6 Represents Friday @param _mode {uint8} 0 or 1. 1 VCA, 0 Normal */ function setAuctionMode(uint8 _day, uint8 _mode) external onlyManager { auctions[_day].mode = _mode; } /** @param day {uint8} 0 - 6 value. 0 represents Saturday, 6 Represents Friday @param coins {address[]} - Addresses to buy from uniswap @param percentages {uint8[]} - % of coin to buy, must add up to 100% */ function setTokensOfDay( uint8 day, address[] calldata coins, uint8[] calldata percentages ) external onlyManager { AuctionData storage auction = auctions[day]; auction.mode = 1; delete auction.tokens; uint8 percent = 0; for (uint8 i; i < coins.length; i++) { auction.tokens.push(VentureToken(coins[i], percentages[i])); percent = percentages[i] + percent; IStaking(addresses.staking).addDivToken(coins[i]); } require( percent == 100, 'AUCTION: Percentage for venture day must equal 100' ); } /** Getter functions */ function auctionsOf_(address account) external view returns (uint256[] memory) { return auctionsOf[account]; } function getAuctionModes() external view returns (uint8[7] memory) { uint8[7] memory auctionModes; for (uint8 i; i < auctions.length; i++) { auctionModes[i] = auctions[i].mode; } return auctionModes; } function getTokensOfDay(uint8 _day) external view returns (address[] memory, uint256[] memory) { VentureToken[] memory ventureTokens = auctions[_day].tokens; address[] memory tokens = new address[](ventureTokens.length); uint256[] memory percentages = new uint256[](ventureTokens.length); for (uint8 i; i < ventureTokens.length; i++) { tokens[i] = ventureTokens[i].coin; percentages[i] = ventureTokens[i].percentage; } return (tokens, percentages); } function getVentureAutoStakeDays() external view returns (uint8) { return ventureAutoStakeDays; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/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, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } 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.6.0; interface IToken { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IAuction { function callIncomeDailyTokensTrigger(uint256 amount) external; function callIncomeWeeklyTokensTrigger(uint256 amount) external; function addReservesToAuction(uint256 daysInFuture, uint256 amount) external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IStaking { function externalStake( uint256 amount, uint256 stakingDays, address staker ) external; function updateTokenPricePerShare( address payable bidderAddress, address payable originAddress, address tokenAddress, uint256 amountBought ) external payable; function addDivToken(address tokenAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IAuctionV1 { function auctionBetOf(uint256, address) external returns (uint256, address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 // 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)); } } 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); }
* @dev Contract module that allows children to implement role-based access control mechanisms. Roles are referred to by their `bytes32` identifier. These should be exposed in the external API and be unique. The best way to achieve this is by using `public constant` hash digests: ``` bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); ``` Roles can be used to represent a set of permissions. To restrict access to a function call, use {hasRole}: ``` function foo() public { require(hasRole(MY_ROLE, msg.sender)); ... } ``` Roles can be granted and revoked dynamically via the {grantRole} and {revokeRole} functions. Each role has an associated admin role, and only accounts that have a role's admin role can call {grantRole} and {revokeRole}. By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means that only accounts with this role will be able to grant or revoke other roles. More complex role relationships can be created by using {_setRoleAdmin}. WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to grant and revoke this role. Extra precautions should be taken to secure accounts that have been granted it./* @dev Returns `true` if `account` has been granted `role`./* @dev Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role./* @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 for more information./* @dev Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}./* @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./* @dev Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role./* @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`./* @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}. ====/* @dev Sets `adminRole` as ``role``'s admin role. Emits a {RoleAdminChanged} event./
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } 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); } 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); } function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity >=0.6.0 <0.8.0;
9,927,060
[ 1, 8924, 1605, 716, 5360, 2325, 358, 2348, 2478, 17, 12261, 2006, 3325, 1791, 28757, 18, 19576, 854, 29230, 358, 635, 3675, 1375, 3890, 1578, 68, 2756, 18, 8646, 1410, 506, 16265, 316, 326, 3903, 1491, 471, 506, 3089, 18, 1021, 3796, 4031, 358, 20186, 537, 333, 353, 635, 1450, 1375, 482, 5381, 68, 1651, 5403, 87, 30, 31621, 1731, 1578, 1071, 5381, 22069, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 22114, 67, 16256, 8863, 31621, 19576, 848, 506, 1399, 358, 2406, 279, 444, 434, 4371, 18, 2974, 13108, 2006, 358, 279, 445, 745, 16, 999, 288, 5332, 2996, 6713, 31621, 445, 8431, 1435, 1071, 288, 377, 2583, 12, 5332, 2996, 12, 22114, 67, 16256, 16, 1234, 18, 15330, 10019, 377, 1372, 289, 31621, 19576, 848, 506, 17578, 471, 22919, 18373, 3970, 326, 288, 16243, 2996, 97, 471, 288, 9083, 3056, 2996, 97, 4186, 18, 8315, 2478, 711, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 24349, 10784, 429, 353, 10188, 6934, 16, 1772, 10784, 429, 288, 203, 565, 445, 1001, 16541, 67, 2738, 1435, 2713, 12562, 288, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 16541, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 565, 445, 1001, 16541, 67, 2738, 67, 4384, 8707, 1435, 2713, 12562, 288, 203, 565, 289, 203, 565, 1450, 6057, 25121, 694, 10784, 429, 364, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 31, 203, 565, 1450, 5267, 10784, 429, 364, 1758, 31, 203, 203, 565, 1958, 6204, 751, 288, 203, 3639, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 4833, 31, 203, 3639, 1731, 1578, 3981, 2996, 31, 203, 565, 289, 203, 203, 565, 2874, 261, 3890, 1578, 516, 6204, 751, 13, 3238, 389, 7774, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 3331, 67, 15468, 67, 16256, 273, 374, 92, 713, 31, 203, 203, 203, 203, 203, 565, 445, 28335, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 7774, 63, 4615, 8009, 7640, 18, 12298, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 15673, 4419, 1380, 12, 3890, 1578, 2478, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 7774, 63, 4615, 8009, 7640, 18, 2469, 5621, 203, 565, 289, 203, 203, 565, 445, 15673, 4419, 12, 3890, 1578, 2478, 16, 2254, 5034, 770, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 2 ]
./partial_match/1/0x99cB2dC9F66b2D6ABb0017254e25a836829a952c/sources/REFLECT.sol
计算(rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); }
3,614,196
[ 1, 169, 111, 99, 168, 111, 250, 12, 86, 6275, 16, 436, 5912, 6275, 16, 436, 14667, 16, 268, 5912, 6275, 16, 268, 14667, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 1972, 12, 11890, 5034, 268, 6275, 13, 3238, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 261, 11890, 5034, 268, 5912, 6275, 16, 2254, 5034, 268, 14667, 13, 273, 389, 588, 56, 1972, 12, 88, 6275, 1769, 203, 3639, 2254, 5034, 783, 4727, 273, 225, 389, 588, 4727, 5621, 203, 3639, 261, 11890, 5034, 436, 6275, 16, 2254, 5034, 436, 5912, 6275, 16, 2254, 5034, 436, 14667, 13, 273, 389, 588, 54, 1972, 12, 88, 6275, 16, 268, 14667, 16, 783, 4727, 1769, 203, 3639, 327, 261, 86, 6275, 16, 436, 5912, 6275, 16, 436, 14667, 16, 268, 5912, 6275, 16, 268, 14667, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-17 */ /** *Submitted for verification at BscScan.com on 2021-07-28 */ /** *Submitted for verification at Etherscan.io on 2021-07-28 */ pragma solidity 0.5.16; interface IBEP2E { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint256); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 { } 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; } } /** * @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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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; } } contract BEP2EToken is Context, IBEP2E, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 public _decimals; string public _symbol; string public _name; constructor() public { _name = "National Technological Breakthrough"; _symbol = "TIKETS"; _decimals = 6; _totalSupply = 8999999999000000; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint256) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP2E-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP2E-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP2E-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP2E-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP2E-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP2E-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP2E}; * * 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP2E: 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 {BEP2E-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 {BEP2E-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, "BEP2E: 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), "BEP2E: transfer from the zero address"); require(recipient != address(0), "BEP2E: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP2E: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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), "BEP2E: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP2E: 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), "BEP2E: approve from the zero address"); require(spender != address(0), "BEP2E: 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, "BEP2E: burn amount exceeds allowance")); } }
* @dev See {BEP2E-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {BEP2E}; 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP2E: transfer amount exceeds allowance")); return true; }
2,051,019
[ 1, 9704, 288, 5948, 52, 22, 41, 17, 13866, 1265, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 1220, 353, 486, 1931, 635, 326, 512, 2579, 18, 2164, 326, 4721, 622, 326, 8435, 434, 288, 5948, 52, 22, 41, 20451, 29076, 30, 300, 1375, 15330, 68, 471, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 300, 326, 4894, 1297, 1240, 1699, 1359, 364, 1375, 15330, 11294, 87, 2430, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 13, 288, 203, 565, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 565, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 8009, 1717, 12, 8949, 16, 315, 5948, 52, 22, 41, 30, 7412, 3844, 14399, 1699, 1359, 7923, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4F8126bD0a57C4B865ab1C7A04F0ae2519206DDf/sources/FlokiSanta.sol
SPDX-License-Identifier: Unlicensed
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 ); Floki Santa ($FlokiSanta) pragma solidity 0.8.9; }
4,023,914
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 1351, 80, 335, 28003, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 42, 383, 15299, 348, 27677, 9253, 42, 383, 15299, 55, 27677, 13, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 29, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../base/Multicall.sol"; import "../bancor/BancorFormula.sol"; import "../upgrades/GraphUpgradeable.sol"; import "../utils/TokenUtils.sol"; import "./IGNS.sol"; import "./GNSStorage.sol"; /** * @title GNS * @dev The Graph Name System contract provides a decentralized naming system for subgraphs * used in the scope of the Graph Network. It translates subgraph names into subgraph versions. * Each version is associated with a Subgraph Deployment. The contract has no knowledge of * human-readable names. All human readable names emitted in events. * The contract implements a multicall behaviour to support batching multiple calls in a single * transaction. */ contract GNS is GNSV1Storage, GraphUpgradeable, IGNS, Multicall { using SafeMath for uint256; // -- Constants -- uint256 private constant MAX_UINT256 = 2**256 - 1; // 100% in parts per million uint32 private constant MAX_PPM = 1000000; // Equates to Connector weight on bancor formula to be CW = 1 uint32 private constant defaultReserveRatio = 1000000; // -- Events -- /** * @dev Emitted when graph account sets its default name */ event SetDefaultName( address indexed graphAccount, uint256 nameSystem, // only ENS for now bytes32 nameIdentifier, string name ); /** * @dev Emitted when graph account sets a subgraphs metadata on IPFS */ event SubgraphMetadataUpdated( address indexed graphAccount, uint256 indexed subgraphNumber, bytes32 subgraphMetadata ); /** * @dev Emitted when a `graph account` publishes a `subgraph` with a `version`. * Every time this event is emitted, indicates a new version has been created. * The event also emits a `metadataHash` with subgraph details and version details. */ event SubgraphPublished( address indexed graphAccount, uint256 indexed subgraphNumber, bytes32 indexed subgraphDeploymentID, bytes32 versionMetadata ); /** * @dev Emitted when a graph account deprecated one of its subgraphs */ event SubgraphDeprecated(address indexed graphAccount, uint256 indexed subgraphNumber); /** * @dev Emitted when a graphAccount creates an nSignal bonding curve that * points to a subgraph deployment */ event NameSignalEnabled( address indexed graphAccount, uint256 indexed subgraphNumber, bytes32 indexed subgraphDeploymentID, uint32 reserveRatio ); /** * @dev Emitted when a name curator deposits its vSignal into an nSignal curve to mint nSignal */ event NSignalMinted( address indexed graphAccount, uint256 indexed subgraphNumber, address indexed nameCurator, uint256 nSignalCreated, uint256 vSignalCreated, uint256 tokensDeposited ); /** * @dev Emitted when a name curator burns its nSignal, which in turn burns * the vSignal, and receives GRT */ event NSignalBurned( address indexed graphAccount, uint256 indexed subgraphNumber, address indexed nameCurator, uint256 nSignalBurnt, uint256 vSignalBurnt, uint256 tokensReceived ); /** * @dev Emitted when a graph account upgrades its nSignal curve to point to a new * subgraph deployment, burning all the old vSignal and depositing the GRT into the * new vSignal curve, creating new nSignal */ event NameSignalUpgrade( address indexed graphAccount, uint256 indexed subgraphNumber, uint256 newVSignalCreated, uint256 tokensSignalled, bytes32 indexed subgraphDeploymentID ); /** * @dev Emitted when an nSignal curve has been permanently disabled */ event NameSignalDisabled( address indexed graphAccount, uint256 indexed subgraphNumber, uint256 withdrawableGRT ); /** * @dev Emitted when a nameCurator withdraws its GRT from a deprecated name signal pool */ event GRTWithdrawn( address indexed graphAccount, uint256 indexed subgraphNumber, address indexed nameCurator, uint256 nSignalBurnt, uint256 withdrawnGRT ); // -- Modifiers -- /** * @dev Check if the owner is the graph account * @param _graphAccount Address of the graph account */ function _isGraphAccountOwner(address _graphAccount) private view { address graphAccountOwner = erc1056Registry.identityOwner(_graphAccount); require(graphAccountOwner == msg.sender, "GNS: Only graph account owner can call"); } /** * @dev Modifier that allows a function to be called by owner of a graph account * @param _graphAccount Address of the graph account */ modifier onlyGraphAccountOwner(address _graphAccount) { _isGraphAccountOwner(_graphAccount); _; } // -- Functions -- /** * @dev Initialize this contract. */ function initialize( address _controller, address _bondingCurve, address _didRegistry ) external onlyImpl { Managed._initialize(_controller); bondingCurve = _bondingCurve; erc1056Registry = IEthereumDIDRegistry(_didRegistry); // Settings _setOwnerTaxPercentage(500000); } /** * @dev Approve curation contract to pull funds. */ function approveAll() external override { graphToken().approve(address(curation()), MAX_UINT256); } /** * @dev Set the owner fee percentage. This is used to prevent a subgraph owner to drain all * the name curators tokens while upgrading or deprecating and is configurable in parts per hundred. * @param _ownerTaxPercentage Owner tax percentage */ function setOwnerTaxPercentage(uint32 _ownerTaxPercentage) external override onlyGovernor { _setOwnerTaxPercentage(_ownerTaxPercentage); } /** * @dev Internal: Set the owner tax percentage. This is used to prevent a subgraph owner to drain all * the name curators tokens while upgrading or deprecating and is configurable in parts per hundred. * @param _ownerTaxPercentage Owner tax percentage */ function _setOwnerTaxPercentage(uint32 _ownerTaxPercentage) private { require(_ownerTaxPercentage <= MAX_PPM, "Owner tax must be MAX_PPM or less"); ownerTaxPercentage = _ownerTaxPercentage; emit ParameterUpdated("ownerTaxPercentage"); } /** * @dev Allows a graph account to set a default name * @param _graphAccount Account that is setting its name * @param _nameSystem Name system account already has ownership of a name in * @param _nameIdentifier The unique identifier that is used to identify the name in the system * @param _name The name being set as default */ function setDefaultName( address _graphAccount, uint8 _nameSystem, bytes32 _nameIdentifier, string calldata _name ) external override onlyGraphAccountOwner(_graphAccount) { emit SetDefaultName(_graphAccount, _nameSystem, _nameIdentifier, _name); } /** * @dev Allows a graph account update the metadata of a subgraph they have published * @param _graphAccount Account that owns the subgraph * @param _subgraphNumber Subgraph number * @param _subgraphMetadata IPFS hash for the subgraph metadata */ function updateSubgraphMetadata( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphMetadata ) public override onlyGraphAccountOwner(_graphAccount) { emit SubgraphMetadataUpdated(_graphAccount, _subgraphNumber, _subgraphMetadata); } /** * @dev Allows a graph account to publish a new subgraph, which means a new subgraph number * will be used. * @param _graphAccount Account that is publishing the subgraph * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata * @param _subgraphMetadata IPFS hash for the subgraph metadata */ function publishNewSubgraph( address _graphAccount, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata, bytes32 _subgraphMetadata ) external override notPaused onlyGraphAccountOwner(_graphAccount) { uint256 subgraphNumber = graphAccountSubgraphNumbers[_graphAccount]; _publishVersion(_graphAccount, subgraphNumber, _subgraphDeploymentID, _versionMetadata); graphAccountSubgraphNumbers[_graphAccount] = graphAccountSubgraphNumbers[_graphAccount].add( 1 ); updateSubgraphMetadata(_graphAccount, subgraphNumber, _subgraphMetadata); _enableNameSignal(_graphAccount, subgraphNumber); } /** * @dev Allows a graph account to publish a new version of its subgraph. * Version is derived from the occurrence of SubgraphPublished being emitted. * The first time SubgraphPublished is called would be Version 0 * @param _graphAccount Account that is publishing the subgraph * @param _subgraphNumber Subgraph number for the account * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata */ function publishNewVersion( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata ) external override notPaused onlyGraphAccountOwner(_graphAccount) { require( isPublished(_graphAccount, _subgraphNumber), "GNS: Cannot update version if not published, or has been deprecated" ); bytes32 oldSubgraphDeploymentID = subgraphs[_graphAccount][_subgraphNumber]; require( _subgraphDeploymentID != oldSubgraphDeploymentID, "GNS: Cannot publish a new version with the same subgraph deployment ID" ); _publishVersion(_graphAccount, _subgraphNumber, _subgraphDeploymentID, _versionMetadata); _upgradeNameSignal(_graphAccount, _subgraphNumber, _subgraphDeploymentID); } /** * @dev Private function used by both external publishing functions * @param _graphAccount Account that is publishing the subgraph * @param _subgraphNumber Subgraph number for the account * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata */ function _publishVersion( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata ) private { require(_subgraphDeploymentID != 0, "GNS: Cannot set deploymentID to 0 in publish"); // Stores a subgraph deployment ID, which indicates a version has been created subgraphs[_graphAccount][_subgraphNumber] = _subgraphDeploymentID; // Emit version and name data emit SubgraphPublished( _graphAccount, _subgraphNumber, _subgraphDeploymentID, _versionMetadata ); } /** * @dev Deprecate a subgraph. Can only be done by the graph account owner. * @param _graphAccount Account that is deprecating the subgraph * @param _subgraphNumber Subgraph number for the account */ function deprecateSubgraph(address _graphAccount, uint256 _subgraphNumber) external override notPaused onlyGraphAccountOwner(_graphAccount) { require( isPublished(_graphAccount, _subgraphNumber), "GNS: Cannot deprecate a subgraph which does not exist" ); delete subgraphs[_graphAccount][_subgraphNumber]; emit SubgraphDeprecated(_graphAccount, _subgraphNumber); _disableNameSignal(_graphAccount, _subgraphNumber); } /** * @dev Enable name signal on a graph accounts numbered subgraph, which points to a subgraph * deployment * @param _graphAccount Graph account enabling name signal * @param _subgraphNumber Subgraph number being used */ function _enableNameSignal(address _graphAccount, uint256 _subgraphNumber) private { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; namePool.subgraphDeploymentID = subgraphs[_graphAccount][_subgraphNumber]; namePool.reserveRatio = defaultReserveRatio; emit NameSignalEnabled( _graphAccount, _subgraphNumber, namePool.subgraphDeploymentID, namePool.reserveRatio ); } /** * @dev Update a name signal on a graph accounts numbered subgraph * @param _graphAccount Graph account updating name signal * @param _subgraphNumber Subgraph number being used * @param _newSubgraphDeploymentID Deployment ID being upgraded to */ function _upgradeNameSignal( address _graphAccount, uint256 _subgraphNumber, bytes32 _newSubgraphDeploymentID ) private { // This is to prevent the owner from front running its name curators signal by posting // its own signal ahead, bringing the name curators in, and dumping on them ICuration curation = curation(); require( !curation.isCurated(_newSubgraphDeploymentID), "GNS: Owner cannot point to a subgraphID that has been pre-curated" ); NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require( namePool.nSignal > 0, "GNS: There must be nSignal on this subgraph for curve math to work" ); require(namePool.disabled == false, "GNS: Cannot be disabled"); // Burn all version signal in the name pool for tokens uint256 tokens = curation.burn(namePool.subgraphDeploymentID, namePool.vSignal, 0); // Take the owner cut of the curation tax, add it to the total uint32 curationTaxPercentage = curation.curationTaxPercentage(); uint256 tokensWithTax = _chargeOwnerTax(tokens, _graphAccount, curationTaxPercentage); // Update pool: constant nSignal, vSignal can change namePool.subgraphDeploymentID = _newSubgraphDeploymentID; (namePool.vSignal, ) = curation.mint(namePool.subgraphDeploymentID, tokensWithTax, 0); emit NameSignalUpgrade( _graphAccount, _subgraphNumber, namePool.vSignal, tokensWithTax, _newSubgraphDeploymentID ); } /** * @dev Allow a name curator to mint some nSignal by depositing GRT * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number * @param _tokensIn The amount of tokens the nameCurator wants to deposit * @param _nSignalOutMin Expected minimum amount of name signal to receive */ function mintNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokensIn, uint256 _nSignalOutMin ) external override notPartialPaused { // Pool checks NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require(namePool.disabled == false, "GNS: Cannot be disabled"); require( namePool.subgraphDeploymentID != 0, "GNS: Must deposit on a name signal that exists" ); // Pull tokens from sender TokenUtils.pullTokens(graphToken(), msg.sender, _tokensIn); // Get name signal to mint for tokens deposited (uint256 vSignal, ) = curation().mint(namePool.subgraphDeploymentID, _tokensIn, 0); uint256 nSignal = vSignalToNSignal(_graphAccount, _subgraphNumber, vSignal); // Slippage protection require(nSignal >= _nSignalOutMin, "GNS: Slippage protection"); // Update pools namePool.vSignal = namePool.vSignal.add(vSignal); namePool.nSignal = namePool.nSignal.add(nSignal); namePool.curatorNSignal[msg.sender] = namePool.curatorNSignal[msg.sender].add(nSignal); emit NSignalMinted(_graphAccount, _subgraphNumber, msg.sender, nSignal, vSignal, _tokensIn); } /** * @dev Allow a nameCurator to burn some of its nSignal and get GRT in return * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignal The amount of nSignal the nameCurator wants to burn * @param _tokensOutMin Expected minimum amount of tokens to receive */ function burnNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal, uint256 _tokensOutMin ) external override notPartialPaused { // Pool checks NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require(namePool.disabled == false, "GNS: Cannot be disabled"); // Curator balance checks uint256 curatorNSignal = namePool.curatorNSignal[msg.sender]; require( _nSignal <= curatorNSignal, "GNS: Curator cannot withdraw more nSignal than they have" ); // Get tokens for name signal amount to burn uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignal); uint256 tokens = curation().burn(namePool.subgraphDeploymentID, vSignal, _tokensOutMin); // Update pools namePool.vSignal = namePool.vSignal.sub(vSignal); namePool.nSignal = namePool.nSignal.sub(_nSignal); namePool.curatorNSignal[msg.sender] = namePool.curatorNSignal[msg.sender].sub(_nSignal); // Return the tokens to the curator TokenUtils.pushTokens(graphToken(), msg.sender, tokens); emit NSignalBurned(_graphAccount, _subgraphNumber, msg.sender, _nSignal, vSignal, tokens); } /** * @dev Owner disables the subgraph. This means the subgraph-number combination can no longer * be used for name signal. The nSignal curve is destroyed, the vSignal is burned, and the GNS * contract holds the GRT from burning the vSignal, which all curators can withdraw manually. * @param _graphAccount Account that is deprecating its name curation * @param _subgraphNumber Subgraph number */ function _disableNameSignal(address _graphAccount, uint256 _subgraphNumber) private { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; // If no nSignal, then no need to burn vSignal if (namePool.nSignal != 0) { // Note: No slippage, burn at any cost namePool.withdrawableGRT = curation().burn( namePool.subgraphDeploymentID, namePool.vSignal, 0 ); namePool.vSignal = 0; } // Set the NameCurationPool fields to make it disabled namePool.disabled = true; emit NameSignalDisabled(_graphAccount, _subgraphNumber, namePool.withdrawableGRT); } /** * @dev When the subgraph curve is disabled, all nameCurators can call this function and * withdraw the GRT they are entitled for its original deposit of vSignal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators */ function withdraw(address _graphAccount, uint256 _subgraphNumber) external override notPartialPaused { // Pool checks NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require(namePool.disabled == true, "GNS: Name bonding curve must be disabled first"); require(namePool.withdrawableGRT > 0, "GNS: No more GRT to withdraw"); // Curator balance checks uint256 curatorNSignal = namePool.curatorNSignal[msg.sender]; require(curatorNSignal > 0, "GNS: Curator must have some nSignal to withdraw GRT"); // Get curator share of tokens to be withdrawn uint256 tokensOut = curatorNSignal.mul(namePool.withdrawableGRT).div(namePool.nSignal); namePool.curatorNSignal[msg.sender] = 0; namePool.nSignal = namePool.nSignal.sub(curatorNSignal); namePool.withdrawableGRT = namePool.withdrawableGRT.sub(tokensOut); // Return tokens to the curator TokenUtils.pushTokens(graphToken(), msg.sender, tokensOut); emit GRTWithdrawn(_graphAccount, _subgraphNumber, msg.sender, curatorNSignal, tokensOut); } /** * @dev Calculate tax that owner will have to cover for upgrading or deprecating. * @param _tokens Tokens that were received from deprecating the old subgraph * @param _owner Subgraph owner * @param _curationTaxPercentage Tax percentage on curation deposits from Curation contract * @return Total tokens that will be sent to curation, _tokens + ownerTax */ function _chargeOwnerTax( uint256 _tokens, address _owner, uint32 _curationTaxPercentage ) private returns (uint256) { if (_curationTaxPercentage == 0 || ownerTaxPercentage == 0) { return 0; } // Tax on the total bonding curve funds uint256 taxOnOriginal = _tokens.mul(_curationTaxPercentage).div(MAX_PPM); // Total after the tax uint256 totalWithoutOwnerTax = _tokens.sub(taxOnOriginal); // The portion of tax that the owner will pay uint256 ownerTax = taxOnOriginal.mul(ownerTaxPercentage).div(MAX_PPM); uint256 totalWithOwnerTax = totalWithoutOwnerTax.add(ownerTax); // The total after tax, plus owner partial repay, divided by // the tax, to adjust it slightly upwards. ex: // 100 GRT, 5 GRT Tax, owner pays 100% --> 5 GRT // To get 100 in the protocol after tax, Owner deposits // ~5.26, as ~105.26 * .95 = 100 uint256 totalAdjustedUp = totalWithOwnerTax.mul(MAX_PPM).div( uint256(MAX_PPM).sub(uint256(_curationTaxPercentage)) ); uint256 ownerTaxAdjustedUp = totalAdjustedUp.sub(_tokens); // Get the owner of the subgraph to reimburse the curation tax TokenUtils.pullTokens(graphToken(), _owner, ownerTaxAdjustedUp); return totalAdjustedUp; } /** * @dev Calculate name signal to be returned for an amount of tokens. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _tokensIn Tokens being exchanged for name signal * @return Amount of name signal and curation tax */ function tokensToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokensIn ) public view override returns ( uint256, uint256, uint256 ) { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; (uint256 vSignal, uint256 curationTax) = curation().tokensToSignal( namePool.subgraphDeploymentID, _tokensIn ); uint256 nSignal = vSignalToNSignal(_graphAccount, _subgraphNumber, vSignal); return (vSignal, nSignal, curationTax); } /** * @dev Calculate tokens returned for an amount of name signal. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignalIn Name signal being exchanged for tokens * @return Amount of tokens returned for an amount of nSignal */ function nSignalToTokens( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignalIn ) public view override returns (uint256, uint256) { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignalIn); uint256 tokensOut = curation().signalToTokens(namePool.subgraphDeploymentID, vSignal); return (vSignal, tokensOut); } /** * @dev Calculate nSignal to be returned for an amount of vSignal. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _vSignalIn Amount of vSignal to exchange for name signal * @return Amount of nSignal that can be bought */ function vSignalToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _vSignalIn ) public view override returns (uint256) { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; // Handle initialization by using 1:1 version to name signal if (namePool.vSignal == 0) { return _vSignalIn; } return BancorFormula(bondingCurve).calculatePurchaseReturn( namePool.nSignal, namePool.vSignal, namePool.reserveRatio, _vSignalIn ); } /** * @dev Calculate vSignal to be returned for an amount of name signal. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignalIn Name signal being exchanged for vSignal * @return Amount of vSignal that can be returned */ function nSignalToVSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignalIn ) public view override returns (uint256) { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; return BancorFormula(bondingCurve).calculateSaleReturn( namePool.nSignal, namePool.vSignal, namePool.reserveRatio, _nSignalIn ); } /** * @dev Get the amount of name signal a curator has on a name pool. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _curator Curator to look up to see n signal balance * @return Amount of name signal owned by a curator for the name pool */ function getCuratorNSignal( address _graphAccount, uint256 _subgraphNumber, address _curator ) public view override returns (uint256) { return nameSignals[_graphAccount][_subgraphNumber].curatorNSignal[_curator]; } /** * @dev Return whether a subgraph name is published. * @param _graphAccount Account being checked * @param _subgraphNumber Subgraph number being checked for publishing * @return Return true if subgraph is currently published */ function isPublished(address _graphAccount, uint256 _subgraphNumber) public view override returns (bool) { return subgraphs[_graphAccount][_subgraphNumber] != 0; } } // 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: GPL-2.0-or-later pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./IMulticall.sol"; // Inspired by https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/base/Multicall.sol // Note: Removed payable from the multicall /** * @title Multicall * @notice Enables calling multiple methods in a single call to the contract */ abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; import "@openzeppelin/contracts/math/SafeMath.sol"; contract BancorFormula { using SafeMath for uint256; uint16 public constant version = 6; uint256 private constant ONE = 1; uint32 private constant MAX_RATIO = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** * @dev Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** * @dev Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** * @dev Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** * @dev Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** * @dev given a token supply, reserve balance, ratio and a deposit amount (in the reserve token), * calculates the return for a given conversion (in the main token) * * Formula: * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 1000000) - 1) * * @param _supply token total supply * @param _reserveBalance total reserve balance * @param _reserveRatio reserve ratio, represented in ppm, 1-1000000 * @param _depositAmount deposit amount, in reserve token * * @return purchase return amount */ function calculatePurchaseReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount ) public view returns (uint256) { // validate input require( _supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO, "invalid parameters" ); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the ratio = 100% if (_reserveRatio == MAX_RATIO) return _supply.mul(_depositAmount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_RATIO); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a token supply, reserve balance, ratio and a sell amount (in the main token), * calculates the return for a given conversion (in the reserve token) * * Formula: * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1000000 / _reserveRatio)) * * @param _supply token total supply * @param _reserveBalance total reserve * @param _reserveRatio constant reserve Ratio, represented in ppm, 1-1000000 * @param _sellAmount sell amount, in the token itself * * @return sale return amount */ function calculateSaleReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount ) public view returns (uint256) { // validate input require( _supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO && _sellAmount <= _supply, "invalid parameters" ); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _reserveBalance; // special case if the ratio = 100% if (_reserveRatio == MAX_RATIO) return _reserveBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_RATIO, _reserveRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given two reserve balances/ratios and a sell amount (in the first reserve token), * calculates the return for a conversion from the first reserve token to the second reserve token (in the second reserve token) * note that prior to version 4, you should use 'calculateCrossConnectorReturn' instead * * Formula: * Return = _toReserveBalance * (1 - (_fromReserveBalance / (_fromReserveBalance + _amount)) ^ (_fromReserveRatio / _toReserveRatio)) * * @param _fromReserveBalance input reserve balance * @param _fromReserveRatio input reserve ratio, represented in ppm, 1-1000000 * @param _toReserveBalance output reserve balance * @param _toReserveRatio output reserve ratio, represented in ppm, 1-1000000 * @param _amount input reserve amount * * @return second reserve amount */ function calculateCrossReserveReturn( uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require( _fromReserveBalance > 0 && _fromReserveRatio > 0 && _fromReserveRatio <= MAX_RATIO && _toReserveBalance > 0 && _toReserveRatio > 0 && _toReserveRatio <= MAX_RATIO ); // special case for equal ratios if (_fromReserveRatio == _toReserveRatio) return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromReserveBalance.add(_amount); (result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio); uint256 temp1 = _toReserveBalance.mul(result); uint256 temp2 = _toReserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given a smart token supply, reserve balance, total ratio and an amount of requested smart tokens, * calculates the amount of reserve tokens required for purchasing the given amount of smart tokens * * Formula: * Return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_RATIO / _totalRatio) - 1) * * @param _supply smart token supply * @param _reserveBalance reserve token balance * @param _totalRatio total ratio, represented in ppm, 2-2000000 * @param _amount requested amount of smart tokens * * @return amount of reserve tokens */ function calculateFundCost( uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount ) public view returns (uint256) { // validate input require( _supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2 ); // special case for 0 amount if (_amount == 0) return 0; // special case if the total ratio = 100% if (_totalRatio == MAX_RATIO) return (_amount.mul(_reserveBalance) - 1) / _supply + 1; uint256 result; uint8 precision; uint256 baseN = _supply.add(_amount); (result, precision) = power(baseN, _supply, MAX_RATIO, _totalRatio); uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1; return temp - _reserveBalance; } /** * @dev given a smart token supply, reserve balance, total ratio and an amount of smart tokens to liquidate, * calculates the amount of reserve tokens received for selling the given amount of smart tokens * * Formula: * Return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_RATIO / _totalRatio)) * * @param _supply smart token supply * @param _reserveBalance reserve token balance * @param _totalRatio total ratio, represented in ppm, 2-2000000 * @param _amount amount of smart tokens to liquidate * * @return amount of reserve tokens */ function calculateLiquidateReturn( uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount ) public view returns (uint256) { // validate input require( _supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2 && _amount <= _supply ); // special case for 0 amount if (_amount == 0) return 0; // special case for liquidating the entire supply if (_amount == _supply) return _reserveBalance; // special case if the total ratio = 100% if (_totalRatio == MAX_RATIO) return _amount.mul(_reserveBalance) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_RATIO, _totalRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev General Description: * Determine a value of precision. * Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. * Return the result along with the precision used. * * Detailed Description: * Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". * The larger "precision" is, the more accurately this value represents the real value. * However, the larger "precision" is, the more bits are required in order to store this value. * And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). * This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". * Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. * This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = (_baseN * FIXED_1) / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = (baseLog * _expN) / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return ( generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision ); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return (res * LN2_NUMERATOR) / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) { res += 0x40000000000000000000000000000000; x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8; } // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) { res += 0x20000000000000000000000000000000; x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7; } // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) { res += 0x10000000000000000000000000000000; x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1; } // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) { res += 0x08000000000000000000000000000000; x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8; } // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) { res += 0x04000000000000000000000000000000; x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3; } // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) { res += 0x02000000000000000000000000000000; x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2; } // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) { res += 0x01000000000000000000000000000000; x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99; } // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) { res += 0x00800000000000000000000000000000; x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733; } // add 1 / 2^8 z = y = x - FIXED_1; w = (y * y) / FIXED_1; res += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 res += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 res += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 res += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 res += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 res += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 res += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 res += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } /** * @dev deprecated, backward compatibility */ function calculateCrossConnectorReturn( uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount ) public view returns (uint256) { return calculateCrossReserveReturn( _fromConnectorBalance, _fromConnectorWeight, _toConnectorBalance, _toConnectorWeight, _amount ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; import "./IGraphProxy.sol"; /** * @title Graph Upgradeable * @dev This contract is intended to be inherited from upgradeable contracts. */ contract GraphUpgradeable { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Check if the caller is the proxy admin. */ modifier onlyProxyAdmin(IGraphProxy _proxy) { require(msg.sender == _proxy.admin(), "Caller must be the proxy admin"); _; } /** * @dev Check if the caller is the implementation. */ modifier onlyImpl { require(msg.sender == _implementation(), "Caller must be the implementation"); _; } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Accept to be an implementation of proxy. */ function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgrade(); } /** * @dev Accept to be an implementation of proxy and then call a function from the new * implementation as specified by `_data`, which should be an encoded function call. This is * useful to initialize new storage variables in the proxied contract. */ function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgradeAndCall(_data); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; import "../token/IGraphToken.sol"; library TokenUtils { /** * @dev Pull tokens from an address to this contract. * @param _graphToken Token to transfer * @param _from Address sending the tokens * @param _amount Amount of tokens to transfer */ function pullTokens( IGraphToken _graphToken, address _from, uint256 _amount ) internal { if (_amount > 0) { require(_graphToken.transferFrom(_from, address(this), _amount), "!transfer"); } } /** * @dev Push tokens from this contract to a receiving address. * @param _graphToken Token to transfer * @param _to Address receiving the tokens * @param _amount Amount of tokens to transfer */ function pushTokens( IGraphToken _graphToken, address _to, uint256 _amount ) internal { if (_amount > 0) { require(_graphToken.transfer(_to, _amount), "!transfer"); } } /** * @dev Burn tokens held by this contract. * @param _graphToken Token to burn * @param _amount Amount of tokens to burn */ function burnTokens(IGraphToken _graphToken, uint256 _amount) internal { if (_amount > 0) { _graphToken.burn(_amount); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; interface IGNS { // -- Pool -- struct NameCurationPool { uint256 vSignal; // The token of the subgraph deployment bonding curve uint256 nSignal; // The token of the name curation bonding curve mapping(address => uint256) curatorNSignal; bytes32 subgraphDeploymentID; uint32 reserveRatio; bool disabled; uint256 withdrawableGRT; } // -- Configuration -- function approveAll() external; function setOwnerTaxPercentage(uint32 _ownerTaxPercentage) external; // -- Publishing -- function setDefaultName( address _graphAccount, uint8 _nameSystem, bytes32 _nameIdentifier, string calldata _name ) external; function updateSubgraphMetadata( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphMetadata ) external; function publishNewSubgraph( address _graphAccount, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata, bytes32 _subgraphMetadata ) external; function publishNewVersion( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata ) external; function deprecateSubgraph(address _graphAccount, uint256 _subgraphNumber) external; // -- Curation -- function mintNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokensIn, uint256 _nSignalOutMin ) external; function burnNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal, uint256 _tokensOutMin ) external; function withdraw(address _graphAccount, uint256 _subgraphNumber) external; // -- Getters -- function tokensToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokensIn ) external view returns ( uint256, uint256, uint256 ); function nSignalToTokens( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignalIn ) external view returns (uint256, uint256); function vSignalToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _vSignalIn ) external view returns (uint256); function nSignalToVSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignalIn ) external view returns (uint256); function getCuratorNSignal( address _graphAccount, uint256 _subgraphNumber, address _curator ) external view returns (uint256); function isPublished(address _graphAccount, uint256 _subgraphNumber) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "../governance/Managed.sol"; import "./erc1056/IEthereumDIDRegistry.sol"; import "./IGNS.sol"; contract GNSV1Storage is Managed { // -- State -- // In parts per hundred uint32 public ownerTaxPercentage; // Bonding curve formula address public bondingCurve; // graphAccountID => subgraphNumber => subgraphDeploymentID // subgraphNumber = A number associated to a graph accounts deployed subgraph. This // is used to point to a subgraphID (graphAccountID + subgraphNumber) mapping(address => mapping(uint256 => bytes32)) public subgraphs; // graphAccountID => subgraph deployment counter mapping(address => uint256) public graphAccountSubgraphNumbers; // graphAccountID => subgraphNumber => NameCurationPool mapping(address => mapping(uint256 => IGNS.NameCurationPool)) public nameSignals; // ERC-1056 contract reference IEthereumDIDRegistry public erc1056Registry; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; /** * @title Multicall interface * @notice Enables calling multiple methods in a single call to the contract */ interface IMulticall { /** * @notice Call multiple functions in the current contract and return the data from all of them if they all succeed * @param data The encoded function data for each of the calls to make to this contract * @return results The results from each of the calls passed in via data */ function multicall(bytes[] calldata data) external returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; interface IGraphProxy { function admin() external returns (address); function setAdmin(address _newAdmin) external; function implementation() external returns (address); function pendingImplementation() external returns (address); function upgradeTo(address _newImplementation) external; function acceptUpgrade() external; function acceptUpgradeAndCall(bytes calldata data) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphToken is IERC20 { // -- Mint and Burn -- function burn(uint256 amount) external; function mint(address _to, uint256 _amount) external; // -- Mint Admin -- function addMinter(address _account) external; function removeMinter(address _account) external; function renounceMinter() external; function isMinter(address _account) external view returns (bool); // -- Permit -- function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external; } // 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: GPL-2.0-or-later pragma solidity ^0.7.3; import "./IController.sol"; import "../curation/ICuration.sol"; import "../epochs/IEpochManager.sol"; import "../rewards/IRewardsManager.sol"; import "../staking/IStaking.sol"; import "../token/IGraphToken.sol"; /** * @title Graph Managed contract * @dev The Managed contract provides an interface to interact with the Controller. * It also provides local caching for contract addresses. This mechanism relies on calling the * public `syncAllContracts()` function whenever a contract changes in the controller. * * Inspired by Livepeer: * https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol */ contract Managed { // -- State -- // Controller that contract is registered with IController public controller; mapping(bytes32 => address) private addressCache; uint256[10] private __gap; // -- Events -- event ParameterUpdated(string param); event SetController(address controller); /** * @dev Emitted when contract with `nameHash` is synced to `contractAddress`. */ event ContractSynced(bytes32 indexed nameHash, address contractAddress); // -- Modifiers -- function _notPartialPaused() internal view { require(!controller.paused(), "Paused"); require(!controller.partialPaused(), "Partial-paused"); } function _notPaused() internal view { require(!controller.paused(), "Paused"); } function _onlyGovernor() internal view { require(msg.sender == controller.getGovernor(), "Caller must be Controller governor"); } function _onlyController() internal view { require(msg.sender == address(controller), "Caller must be Controller"); } modifier notPartialPaused { _notPartialPaused(); _; } modifier notPaused { _notPaused(); _; } // Check if sender is controller. modifier onlyController() { _onlyController(); _; } // Check if sender is the governor. modifier onlyGovernor() { _onlyGovernor(); _; } // -- Functions -- /** * @dev Initialize the controller. */ function _initialize(address _controller) internal { _setController(_controller); } /** * @notice Set Controller. Only callable by current controller. * @param _controller Controller contract address */ function setController(address _controller) external onlyController { _setController(_controller); } /** * @dev Set controller. * @param _controller Controller contract address */ function _setController(address _controller) internal { require(_controller != address(0), "Controller must be set"); controller = IController(_controller); emit SetController(_controller); } /** * @dev Return Curation interface. * @return Curation contract registered with Controller */ function curation() internal view returns (ICuration) { return ICuration(_resolveContract(keccak256("Curation"))); } /** * @dev Return EpochManager interface. * @return Epoch manager contract registered with Controller */ function epochManager() internal view returns (IEpochManager) { return IEpochManager(_resolveContract(keccak256("EpochManager"))); } /** * @dev Return RewardsManager interface. * @return Rewards manager contract registered with Controller */ function rewardsManager() internal view returns (IRewardsManager) { return IRewardsManager(_resolveContract(keccak256("RewardsManager"))); } /** * @dev Return Staking interface. * @return Staking contract registered with Controller */ function staking() internal view returns (IStaking) { return IStaking(_resolveContract(keccak256("Staking"))); } /** * @dev Return GraphToken interface. * @return Graph token contract registered with Controller */ function graphToken() internal view returns (IGraphToken) { return IGraphToken(_resolveContract(keccak256("GraphToken"))); } /** * @dev Resolve a contract address from the cache or the Controller if not found. * @return Address of the contract */ function _resolveContract(bytes32 _nameHash) internal view returns (address) { address contractAddress = addressCache[_nameHash]; if (contractAddress == address(0)) { contractAddress = controller.getContractProxy(_nameHash); } return contractAddress; } /** * @dev Cache a contract address from the Controller registry. * @param _name Name of the contract to sync into the cache */ function _syncContract(string memory _name) internal { bytes32 nameHash = keccak256(abi.encodePacked(_name)); address contractAddress = controller.getContractProxy(nameHash); if (addressCache[nameHash] != contractAddress) { addressCache[nameHash] = contractAddress; emit ContractSynced(nameHash, contractAddress); } } /** * @dev Sync protocol contract addresses from the Controller registry. * This function will cache all the contracts using the latest addresses * Anyone can call the function whenever a Proxy contract change in the * controller to ensure the protocol is using the latest version */ function syncAllContracts() external { _syncContract("Curation"); _syncContract("EpochManager"); _syncContract("RewardsManager"); _syncContract("Staking"); _syncContract("GraphToken"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; interface IEthereumDIDRegistry { function identityOwner(address identity) external view returns (address); function setAttribute( address identity, bytes32 name, bytes calldata value, uint256 validity ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.12 <0.8.0; interface IController { function getGovernor() external view returns (address); // -- Registry -- function setContractProxy(bytes32 _id, address _contractAddress) external; function unsetContractProxy(bytes32 _id) external; function updateController(bytes32 _id, address _controller) external; function getContractProxy(bytes32 _id) external view returns (address); // -- Pausing -- function setPartialPaused(bool _partialPaused) external; function setPaused(bool _paused) external; function setPauseGuardian(address _newPauseGuardian) external; function paused() external view returns (bool); function partialPaused() external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; import "./IGraphCurationToken.sol"; interface ICuration { // -- Pool -- struct CurationPool { uint256 tokens; // GRT Tokens stored as reserves for the subgraph deployment uint32 reserveRatio; // Ratio for the bonding curve IGraphCurationToken gcs; // Curation token contract for this curation pool } // -- Configuration -- function setDefaultReserveRatio(uint32 _defaultReserveRatio) external; function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external; function setCurationTaxPercentage(uint32 _percentage) external; // -- Curation -- function mint( bytes32 _subgraphDeploymentID, uint256 _tokensIn, uint256 _signalOutMin ) external returns (uint256, uint256); function burn( bytes32 _subgraphDeploymentID, uint256 _signalIn, uint256 _tokensOutMin ) external returns (uint256); function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external; // -- Getters -- function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool); function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn) external view returns (uint256, uint256); function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn) external view returns (uint256); function curationTaxPercentage() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; interface IEpochManager { // -- Configuration -- function setEpochLength(uint256 _epochLength) external; // -- Epochs function runEpoch() external; // -- Getters -- function isCurrentEpochRun() external view returns (bool); function blockNum() external view returns (uint256); function blockHash(uint256 _block) external view returns (bytes32); function currentEpoch() external view returns (uint256); function currentEpochBlock() external view returns (uint256); function currentEpochBlockSinceStart() external view returns (uint256); function epochsSince(uint256 _epoch) external view returns (uint256); function epochsSinceUpdate() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; interface IRewardsManager { /** * @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment. */ struct Subgraph { uint256 accRewardsForSubgraph; uint256 accRewardsForSubgraphSnapshot; uint256 accRewardsPerSignalSnapshot; uint256 accRewardsPerAllocatedToken; } // -- Params -- function setIssuanceRate(uint256 _issuanceRate) external; // -- Denylist -- function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external; function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external; function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny) external; function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool); // -- Getters -- function getNewRewardsPerSignal() external view returns (uint256); function getAccRewardsPerSignal() external view returns (uint256); function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID) external view returns (uint256); function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID) external view returns (uint256, uint256); function getRewards(address _allocationID) external view returns (uint256); // -- Updates -- function updateAccRewardsPerSignal() external returns (uint256); function takeRewards(address _allocationID) external returns (uint256); // -- Hooks -- function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import "./IStakingData.sol"; interface IStaking is IStakingData { // -- Allocation Data -- /** * @dev Possible states an allocation can be * States: * - Null = indexer == address(0) * - Active = not Null && tokens > 0 * - Closed = Active && closedAtEpoch != 0 * - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now() * - Claimed = not Null && tokens == 0 */ enum AllocationState { Null, Active, Closed, Finalized, Claimed } // -- Configuration -- function setMinimumIndexerStake(uint256 _minimumIndexerStake) external; function setThawingPeriod(uint32 _thawingPeriod) external; function setCurationPercentage(uint32 _percentage) external; function setProtocolPercentage(uint32 _percentage) external; function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external; function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external; function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external; function setDelegationRatio(uint32 _delegationRatio) external; function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) external; function setDelegationParametersCooldown(uint32 _blocks) external; function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external; function setDelegationTaxPercentage(uint32 _percentage) external; function setSlasher(address _slasher, bool _allowed) external; function setAssetHolder(address _assetHolder, bool _allowed) external; // -- Operation -- function setOperator(address _operator, bool _allowed) external; function isOperator(address _operator, address _indexer) external view returns (bool); // -- Staking -- function stake(uint256 _tokens) external; function stakeTo(address _indexer, uint256 _tokens) external; function unstake(uint256 _tokens) external; function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external; function withdraw() external; function setRewardsDestination(address _destination) external; // -- Delegation -- function delegate(address _indexer, uint256 _tokens) external returns (uint256); function undelegate(address _indexer, uint256 _shares) external returns (uint256); function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256); // -- Channel management and allocations -- function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function closeAllocation(address _allocationID, bytes32 _poi) external; function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external; function closeAndAllocate( address _oldAllocationID, bytes32 _poi, address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function collect(uint256 _tokens, address _allocationID) external; function claim(address _allocationID, bool _restake) external; function claimMany(address[] calldata _allocationID, bool _restake) external; // -- Getters and calculations -- function hasStake(address _indexer) external view returns (bool); function getIndexerStakedTokens(address _indexer) external view returns (uint256); function getIndexerCapacity(address _indexer) external view returns (uint256); function getAllocation(address _allocationID) external view returns (Allocation memory); function getAllocationState(address _allocationID) external view returns (AllocationState); function isAllocation(address _allocationID) external view returns (bool); function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function getDelegation(address _indexer, address _delegator) external view returns (Delegation memory); function isDelegator(address _indexer, address _delegator) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphCurationToken is IERC20 { function burnFrom(address _account, uint256 _amount) external; function mint(address _to, uint256 _amount) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.12 <0.8.0; interface IStakingData { /** * @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment * An allocation is created in the allocate() function and consumed in claim() */ struct Allocation { address indexer; bytes32 subgraphDeploymentID; uint256 tokens; // Tokens allocated to a SubgraphDeployment uint256 createdAtEpoch; // Epoch when it was created uint256 closedAtEpoch; // Epoch when it was closed uint256 collectedFees; // Collected fees for the allocation uint256 effectiveAllocation; // Effective allocation when closed uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc } /** * @dev Represents a request to close an allocation with a specific proof of indexing. * This is passed when calling closeAllocationMany to define the closing parameters for * each allocation. */ struct CloseAllocationRequest { address allocationID; bytes32 poi; } // -- Delegation Data -- /** * @dev Delegation pool information. One per indexer. */ struct DelegationPool { uint32 cooldownBlocks; // Blocks to wait before updating parameters uint32 indexingRewardCut; // in PPM uint32 queryFeeCut; // in PPM uint256 updatedAtBlock; // Block when the pool was last updated uint256 tokens; // Total tokens as pool reserves uint256 shares; // Total shares minted in the pool mapping(address => Delegation) delegators; // Mapping of delegator => Delegation } /** * @dev Individual delegation data of a delegator in a pool. */ struct Delegation { uint256 shares; // Shares owned by a delegator in the pool uint256 tokensLocked; // Tokens locked for undelegation uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn } }
* @dev Check if the owner is the graph account @param _graphAccount Address of the graph account/
function _isGraphAccountOwner(address _graphAccount) private view { address graphAccountOwner = erc1056Registry.identityOwner(_graphAccount); require(graphAccountOwner == msg.sender, "GNS: Only graph account owner can call"); }
13,682,926
[ 1, 1564, 309, 326, 3410, 353, 326, 2667, 2236, 225, 389, 4660, 3032, 5267, 434, 326, 2667, 2236, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 4137, 3032, 5541, 12, 2867, 389, 4660, 3032, 13, 3238, 1476, 288, 203, 3639, 1758, 2667, 3032, 5541, 273, 6445, 71, 2163, 4313, 4243, 18, 10781, 5541, 24899, 4660, 3032, 1769, 203, 3639, 2583, 12, 4660, 3032, 5541, 422, 1234, 18, 15330, 16, 315, 43, 3156, 30, 5098, 2667, 2236, 3410, 848, 745, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xAf5d2BC0A47f0aE99b7E7225349e3d5C48F46Fd5/sources/STERegistryV1.sol
* @title Interface for checkpoint module configuration/
interface IConfigurableModule { function configure( address _securityToken ) external; }
3,412,104
[ 1, 1358, 364, 9776, 1605, 1664, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 31660, 3120, 288, 203, 203, 565, 445, 5068, 12, 203, 3639, 1758, 389, 7462, 1345, 203, 565, 262, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x0e227b07FB1e8B9E1690e489c0267271D5Ffc781/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRigelPerShare: 0 })); updateStakingPool(); }
5,184,334
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 54, 360, 292, 2173, 9535, 30, 374, 203, 3639, 289, 10019, 203, 3639, 1089, 510, 6159, 2864, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xb2A9c9cB4796dFc137a3EbBF312d73A7837CF708/sources/PobTokenPresale.sol
Number of tokens at start of the sale. This exact amount must be sent to the contract to call initialize() !
uint256 public constant initialTokens = 1000000 * 10**9;
3,460,830
[ 1, 1854, 434, 2430, 622, 787, 434, 326, 272, 5349, 18, 1220, 5565, 3844, 1297, 506, 3271, 358, 326, 6835, 358, 745, 4046, 1435, 401, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 5381, 2172, 5157, 273, 15088, 380, 1728, 636, 29, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./ERCStaking.sol"; import "./Checkpointing.sol"; import "./res/Autopetrified.sol"; import "./res/IsContract.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract Staking is Autopetrified, ERCStaking, ERCStakingHistory, IsContract { using SafeMath for uint256; using Checkpointing for Checkpointing.History; using SafeERC20 for ERC20; // todo: switch back to safetransfer? // This changes all 'transfer' calls to safeTransfer string private constant ERROR_TOKEN_NOT_CONTRACT = "STAKING_TOKEN_NOT_CONTRACT"; string private constant ERROR_AMOUNT_ZERO = "STAKING_AMOUNT_ZERO"; string private constant ERROR_TOKEN_TRANSFER = "STAKING_TOKEN_TRANSFER"; string private constant ERROR_NOT_ENOUGH_BALANCE = "STAKING_NOT_ENOUGH_BALANCE"; // standard - imitates relationship between Ether and Wei uint8 private constant DECIMALS = 18; // Default minimum stake uint256 internal minStakeAmount = 0; // Default maximum stake uint256 internal maxStakeAmount = 0; // Reward tracking info uint256 internal currentClaimBlock; uint256 internal currentClaimableAmount; struct Account { Checkpointing.History stakedHistory; Checkpointing.History claimHistory; } ERC20 internal stakingToken; mapping (address => Account) internal accounts; Checkpointing.History internal totalStakedHistory; address treasuryAddress; address stakingOwnerAddress; event StakeTransferred( address indexed from, uint256 amount, address to ); event Test( uint256 test, string msg); event Claimed( address claimaint, uint256 amountClaimed ); function initialize(address _stakingToken, address _treasuryAddress) external onlyInit { require(isContract(_stakingToken), ERROR_TOKEN_NOT_CONTRACT); initialized(); stakingToken = ERC20(_stakingToken); treasuryAddress = _treasuryAddress; // Initialize claim values to zero, disabling claim prior to initial funding currentClaimBlock = 0; currentClaimableAmount = 0; // Default min stake amount is 100 AUD tokens minStakeAmount = 100 * 10**uint256(DECIMALS); // Default max stake amount is 100 million AUD tokens maxStakeAmount = 100000000 * 10**uint256(DECIMALS); } /* External functions */ /** * @notice Funds `_amount` of tokens from msg.sender into treasury stake */ function fundNewClaim(uint256 _amount) external isInitialized { // TODO: Add additional require statements here... // Stake tokens for msg.sender from treasuryAddress // Transfer tokens from msg.sender to current contract // Increase treasuryAddress stake value _stakeFor( treasuryAddress, msg.sender, _amount, bytes("")); // Update current claim information currentClaimBlock = getBlockNumber(); currentClaimableAmount = totalStakedFor(treasuryAddress); } /** * @notice Allows reward claiming for service providers */ function makeClaim() external isInitialized { require(msg.sender != treasuryAddress, "Treasury cannot claim staking reward"); require(accounts[msg.sender].stakedHistory.history.length > 0, "Stake required to claim"); require(currentClaimBlock > 0, "Claim block must be initialized"); require(currentClaimableAmount > 0, "Claimable amount must be initialized"); if (accounts[msg.sender].claimHistory.history.length > 0) { uint256 lastClaimedBlock = accounts[msg.sender].claimHistory.lastUpdated(); // Require a minimum block difference alloted to be ~1 week of blocks // Note that a new claim funding after the latest claim for this staker overrides the minimum block difference require( lastClaimedBlock < currentClaimBlock, "Minimum block difference not met"); } uint256 claimBlockTotalStake = totalStakedHistory.get(currentClaimBlock); uint256 treasuryStakeAtClaimBlock = accounts[treasuryAddress].stakedHistory.get(currentClaimBlock); uint256 claimantStakeAtClaimBlock = accounts[msg.sender].stakedHistory.get(currentClaimBlock); uint256 totalServiceProviderStakeAtClaimBlock = claimBlockTotalStake.sub(treasuryStakeAtClaimBlock); uint256 claimedValue = (claimantStakeAtClaimBlock.mul(currentClaimableAmount)).div(totalServiceProviderStakeAtClaimBlock); // Transfer value from treasury to claimant if >0 is claimed if (claimedValue > 0) { _transfer(treasuryAddress, msg.sender, claimedValue); } // Update claim history even if no value claimed accounts[msg.sender].claimHistory.add64(getBlockNumber64(), claimedValue); emit Claimed(msg.sender, claimedValue); } /** * @notice Slashes `_amount` tokens from _slashAddress * Controlled by treasury address * @param _amount Number of tokens slashed * @param _slashAddress address being slashed */ function slash(uint256 _amount, address _slashAddress) external isInitialized { // restrict functionality require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner"); // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // transfer slashed funds to treasury address // reduce stake balance for address being slashed _transfer(_slashAddress, treasuryAddress, _amount); } /** * @notice Sets caller for stake and unstake functions * Controlled by treasury address */ function setStakingOwnerAddress(address _stakeCaller) external isInitialized { require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner"); stakingOwnerAddress = _stakeCaller; } /** * @notice Sets the minimum stake possible * Controlled by treasury */ // NOTE that _amounts are in wei throughout function setMinStakeAmount(uint256 _amount) external isInitialized { require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner"); minStakeAmount = _amount; } /** * @notice Sets the max stake possible * Controlled by treasury */ function setMaxStakeAmount(uint256 _amount) external isInitialized { require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner"); maxStakeAmount = _amount; } /** * @notice Stakes `_amount` tokens, transferring them from `msg.sender` * @param _amount Number of tokens staked * @param _data Used in Staked event, to add signalling information in more complex staking applications */ function stake(uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); _stakeFor( msg.sender, msg.sender, _amount, _data); } /** * @notice Stakes `_amount` tokens, transferring them from caller, and assigns them to `_accountAddress` * @param _accountAddress The final staker of the tokens * @param _amount Number of tokens staked * @param _data Used in Staked event, to add signalling information in more complex staking applications */ function stakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); _stakeFor( _accountAddress, _accountAddress, _amount, _data); } /** * @notice Unstakes `_amount` tokens, returning them to the user * @param _amount Number of tokens staked * @param _data Used in Unstaked event, to add signalling information in more complex staking applications */ function unstake(uint256 _amount, bytes calldata _data) external isInitialized { // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(msg.sender, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(msg.sender, _amount); emit Unstaked( msg.sender, _amount, totalStakedFor(msg.sender), _data); } /** * @notice Unstakes `_amount` tokens, returning them to the desired account. * @param _amount Number of tokens staked * @param _data Used in Unstaked event, to add signalling information in more complex staking applications */ function unstakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_accountAddress, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(_accountAddress, _amount); emit Unstaked( _accountAddress, _amount, totalStakedFor(_accountAddress), _data); } /** * @notice Get the token used by the contract for staking and locking * @return The token used by the contract for staking and locking */ function token() external view isInitialized returns (address) { return address(stakingToken); } /** * @notice Check whether it supports history of stakes * @return Always true */ function supportsHistory() external pure returns (bool) { return true; } /** * @notice Get last time `_accountAddress` modified its staked balance * @param _accountAddress Account requesting for * @return Last block number when account's balance was modified */ function lastStakedFor(address _accountAddress) external view isInitialized returns (uint256) { return accounts[_accountAddress].stakedHistory.lastUpdated(); } /** * @notice Get last time `_accountAddress` claimed a staking reward * @param _accountAddress Account requesting for * @return Last block number when claim requested */ function lastClaimedFor(address _accountAddress) external view isInitialized returns (uint256) { return accounts[_accountAddress].claimHistory.lastUpdated(); } /** * @notice Get info relating to current claim status */ function getClaimInfo() external view isInitialized returns (uint256, uint256) { return (currentClaimableAmount, currentClaimBlock); } /** * @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber` * @param _accountAddress Account requesting for * @param _blockNumber Block number at which we are requesting * @return The amount of tokens staked by the account at the given block number */ function totalStakedForAt(address _accountAddress, uint256 _blockNumber) external view returns (uint256) { return accounts[_accountAddress].stakedHistory.get(_blockNumber); } /** * @notice Get the total amount of tokens staked by all users at block number `_blockNumber` * @param _blockNumber Block number at which we are requesting * @return The amount of tokens staked at the given block number */ function totalStakedAt(uint256 _blockNumber) external view returns (uint256) { return totalStakedHistory.get(_blockNumber); } /** * @notice Return the minimum stake configuration * @return min stake */ function getMinStakeAmount() external view returns (uint256) { return minStakeAmount; } /** * @notice Return the maximum stake configuration * @return max stake */ function getMaxStakeAmount() external view returns (uint256) { return maxStakeAmount; } /* Public functions */ /** * @notice Get the amount of tokens staked by `_accountAddress` * @param _accountAddress The owner of the tokens * @return The amount of tokens staked by the given account */ function totalStakedFor(address _accountAddress) public view returns (uint256) { // we assume it's not possible to stake in the future return accounts[_accountAddress].stakedHistory.getLatestValue(); } /** * @notice Get the total amount of tokens staked by all users * @return The total amount of tokens staked by all users */ function totalStaked() public view returns (uint256) { // we assume it's not possible to stake in the future return totalStakedHistory.getLatestValue(); } /* function multicall(bytes[] _calls) public { for(uint i = 0; i < _calls.length; i++) { require(address(this).delegatecall(_calls[i]), ERROR_MULTICALL_DELEGATECALL); } } */ /* Internal functions */ function _stakeFor( address _stakeAccount, address _transferAccount, uint256 _amount, bytes memory _data) internal { // staking 0 tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, true); // checkpoint total supply _modifyTotalStaked(_amount, true); // pull tokens into Staking contract stakingToken.safeTransferFrom(_transferAccount, address(this), _amount); emit Staked( _stakeAccount, _amount, totalStakedFor(_stakeAccount), _data); } function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal { uint256 currentStake = totalStakedFor(_accountAddress); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // Confirm stake is within configured bounds for non-treasury addresses if (_accountAddress != treasuryAddress) { require(newStake <= maxStakeAmount, 'Maximum stake threshold exceeded'); require(newStake > minStakeAmount || newStake == 0, 'Minimum stake threshold exceeded'); } // add new value to account history accounts[_accountAddress].stakedHistory.add64(getBlockNumber64(), newStake); } function _modifyTotalStaked(uint256 _by, bool _increase) internal { uint256 currentStake = totalStaked(); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history totalStakedHistory.add64(getBlockNumber64(), newStake); } function _transfer(address _from, address _to, uint256 _amount) internal { // transferring 0 staked tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // update stakes _modifyStakeBalance(_from, _amount, false); _modifyStakeBalance(_to, _amount, true); emit StakeTransferred(_from,_amount, _to); } }
transferring 0 staked tokens is invalid update stakes
function _transfer(address _from, address _to, uint256 _amount) internal { require(_amount > 0, ERROR_AMOUNT_ZERO); _modifyStakeBalance(_from, _amount, false); _modifyStakeBalance(_to, _amount, true); emit StakeTransferred(_from,_amount, _to); }
1,067,083
[ 1, 2338, 74, 20245, 374, 384, 9477, 2430, 353, 2057, 1089, 384, 3223, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 5475, 67, 2192, 51, 5321, 67, 24968, 1769, 203, 203, 3639, 389, 17042, 510, 911, 13937, 24899, 2080, 16, 389, 8949, 16, 629, 1769, 203, 3639, 389, 17042, 510, 911, 13937, 24899, 869, 16, 389, 8949, 16, 638, 1769, 203, 203, 3639, 3626, 934, 911, 1429, 4193, 24899, 2080, 16, 67, 8949, 16, 389, 869, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.6; contract PolydiceGame { mapping(address => uint256) public passLineBetAmounts; address payable[] public passLinePlayers; uint256 public currentPlayers; uint8 public dice1value; uint8 public dice2value; uint8 public diceSum; uint256 public fee; bytes32 public keyhash; // Should be a variable for automatic games? uint256 public MAX_PLAYERS = 10; // Args: game configurations, like the constant "MAX_PLAYERS" constructor() public { passLinePlayers = new address payable[](MAX_PLAYERS); currentPlayers = 0; } function passLineBet() public payable { if(!isOnPlayers(msg.sender)) addToPlayers(msg.sender); passLineBetAmounts[msg.sender] += msg.value; } function isOnPlayers(address player) private returns(bool) { return passLineBetAmounts[player] > 0; } function addToPlayers(address player) private { passLinePlayers[currentPlayers] = payable(player); currentPlayers++; } function betsCanBeFulfilledWith(uint256 bankFunds) public returns(bool) { // based on the game rules, // for example, if a player can make an 2x // and the bank doenst have 1x his value, // then the bets can't be fulfilled return true; } function fulfillBets(uint8 dice1, uint8 dice2) external { dice1value = dice1; dice2value = dice2; diceSum = dice1 + dice2; fulfillPassLines(); } function fulfillPassLines() private { for (uint i = 0; i < currentPlayers; i++) fulfillPassLine(passLinePlayers[i]); } function fulfillPassLine(address payable player) private { if (hasWonPassLine(player)) { player.transfer(passLineBetAmounts[player] * 2); passLineBetAmounts[player] = 0; } else if(hasLostPassLine(player)) passLineBetAmounts[player] = 0; else { // TODO add here the on/off shit } } function hasWonPassLine(address player) private returns(bool) { return diceSum == 7 || diceSum == 11; } function hasLostPassLine(address player) private returns(bool) { return diceSum == 2 || diceSum == 3 || diceSum == 12; } }
based on the game rules, for example, if a player can make an 2x and the bank doenst have 1x his value, then the bets can't be fulfilled
function betsCanBeFulfilledWith(uint256 bankFunds) public returns(bool) { return true; }
5,444,643
[ 1, 12261, 603, 326, 7920, 2931, 16, 364, 3454, 16, 309, 279, 7291, 848, 1221, 392, 576, 92, 471, 326, 11218, 741, 275, 334, 1240, 404, 92, 18423, 460, 16, 1508, 326, 324, 2413, 848, 1404, 506, 16136, 13968, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 324, 2413, 2568, 1919, 23747, 13968, 1190, 12, 11890, 5034, 11218, 42, 19156, 13, 1071, 1135, 12, 6430, 13, 288, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-25 */ // 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/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/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/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: contracts/interface/IAddressConfig.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAddressConfig { function token() external view returns (address); function allocator() external view returns (address); function allocatorStorage() external view returns (address); function withdraw() external view returns (address); function withdrawStorage() external view returns (address); function marketFactory() external view returns (address); function marketGroup() external view returns (address); function propertyFactory() external view returns (address); function propertyGroup() external view returns (address); function metricsGroup() external view returns (address); function metricsFactory() external view returns (address); function policy() external view returns (address); function policyFactory() external view returns (address); function policySet() external view returns (address); function policyGroup() external view returns (address); function lockup() external view returns (address); function lockupStorage() external view returns (address); function voteTimes() external view returns (address); function voteTimesStorage() external view returns (address); function voteCounter() external view returns (address); function voteCounterStorage() external view returns (address); function setAllocator(address _addr) external; function setAllocatorStorage(address _addr) external; function setWithdraw(address _addr) external; function setWithdrawStorage(address _addr) external; function setMarketFactory(address _addr) external; function setMarketGroup(address _addr) external; function setPropertyFactory(address _addr) external; function setPropertyGroup(address _addr) external; function setMetricsFactory(address _addr) external; function setMetricsGroup(address _addr) external; function setPolicyFactory(address _addr) external; function setPolicyGroup(address _addr) external; function setPolicySet(address _addr) external; function setPolicy(address _addr) external; function setToken(address _addr) external; function setLockup(address _addr) external; function setLockupStorage(address _addr) external; function setVoteTimes(address _addr) external; function setVoteTimesStorage(address _addr) external; function setVoteCounter(address _addr) external; function setVoteCounterStorage(address _addr) external; } // File: contracts/src/common/config/UsingConfig.sol pragma solidity 0.5.17; /** * Module for using AddressConfig contracts. */ contract UsingConfig { address private _config; /** * Initialize the argument as AddressConfig address. */ constructor(address _addressConfig) public { _config = _addressConfig; } /** * Returns the latest AddressConfig instance. */ function config() internal view returns (IAddressConfig) { return IAddressConfig(_config); } /** * Returns the latest AddressConfig address. */ function configAddress() external view returns (address) { return _config; } } // File: contracts/interface/IPolicy.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IPolicy { function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256); function holdersShare(uint256 _amount, uint256 _lockups) external view returns (uint256); function authenticationFee(uint256 _assets, uint256 _propertyAssets) external view returns (uint256); function marketApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function policyApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function marketVotingBlocks() external view returns (uint256); function policyVotingBlocks() external view returns (uint256); function shareOfTreasury(uint256 _supply) external view returns (uint256); function treasury() external view returns (address); function capSetter() external view returns (address); } // File: contracts/src/policy/DIP1.sol /* solhint-disable const-name-snakecase */ /* solhint-disable var-name-mixedcase */ pragma solidity 0.5.17; /** * DIP1 is a contract that simply changed TheFirstPolicy to DIP numbering. */ contract DIP1 is IPolicy, UsingConfig { using SafeMath for uint256; uint256 public marketVotingBlocks = 525600; uint256 public policyVotingBlocks = 525600; uint256 private constant basis = 10000000000000000000000000; uint256 private constant power_basis = 10000000000; uint256 private constant mint_per_block_and_aseet = 250000000000000; constructor(address _config) public UsingConfig(_config) {} function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256) { uint256 max = _assets.mul(mint_per_block_and_aseet); uint256 t = ERC20(config().token()).totalSupply(); uint256 s = (_lockups.mul(basis)).div(t); uint256 _d = basis.sub(s); uint256 _p = ( (power_basis.mul(12)).sub( s.div((basis.div((power_basis.mul(10))))) ) ) .div(2); uint256 p = _p.div(power_basis); uint256 rp = p.add(1); uint256 f = _p.sub(p.mul(power_basis)); uint256 d1 = _d; uint256 d2 = _d; for (uint256 i = 0; i < p; i++) { d1 = (d1.mul(_d)).div(basis); } for (uint256 i = 0; i < rp; i++) { d2 = (d2.mul(_d)).div(basis); } uint256 g = ((d1.sub(d2)).mul(f)).div(power_basis); uint256 d = d1.sub(g); uint256 mint = max.mul(d); mint = mint.div(basis); return mint; } function holdersShare(uint256 _reward, uint256 _lockups) external view returns (uint256) { return _lockups > 0 ? (_reward.mul(51)).div(100) : _reward; } function authenticationFee(uint256 total_assets, uint256 property_lockups) external view returns (uint256) { uint256 a = total_assets.div(10000); uint256 b = property_lockups.div(100000000000000000000000); if (a <= b) { return 0; } return a.sub(b); } function marketApproval(uint256 _up_votes, uint256 _negative_votes) external view returns (bool) { if (_up_votes < 9999999999999999999) { return false; } uint256 negative_votes = _negative_votes > 0 ? _negative_votes : 1000000000000000000; return _up_votes > negative_votes.mul(10); } function policyApproval(uint256 _up_votes, uint256 _negative_votes) external view returns (bool) { if (_up_votes < 9999999999999999999) { return false; } uint256 negative_votes = _negative_votes > 0 ? _negative_votes : 1000000000000000000; return _up_votes > negative_votes.mul(10); } function shareOfTreasury(uint256) external view returns (uint256) { return 0; } function treasury() external view returns (address) { return address(0); } function capSetter() external view returns (address) { return address(0); } } // File: contracts/src/common/libs/Curve.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; contract Curve { using SafeMath for uint256; uint256 private constant basis = 10000000000000000000000000; uint256 private constant power_basis = 10000000000; /** * @dev From the passed variables, calculate the amount of reward reduced along the curve. * @param _lockups Total number of locked up tokens. * @param _assets Total number of authenticated assets. * @param _totalSupply Total supply the token. * @param _mintPerBlockAndAseet Maximum number of reward per block per asset. * @return Calculated reward amount per block per asset. */ function curveRewards( uint256 _lockups, uint256 _assets, uint256 _totalSupply, uint256 _mintPerBlockAndAseet ) internal pure returns (uint256) { uint256 t = _totalSupply; uint256 s = (_lockups.mul(basis)).div(t); uint256 assets = _assets.mul(basis.sub(s)); uint256 max = assets.mul(_mintPerBlockAndAseet); uint256 _d = basis.sub(s); uint256 _p = ( (power_basis.mul(12)).sub( s.div((basis.div((power_basis.mul(10))))) ) ) .div(2); uint256 p = _p.div(power_basis); uint256 rp = p.add(1); uint256 f = _p.sub(p.mul(power_basis)); uint256 d1 = _d; uint256 d2 = _d; for (uint256 i = 0; i < p; i++) { d1 = (d1.mul(_d)).div(basis); } for (uint256 i = 0; i < rp; i++) { d2 = (d2.mul(_d)).div(basis); } uint256 g = ((d1.sub(d2)).mul(f)).div(power_basis); uint256 d = d1.sub(g); uint256 mint = max.mul(d); mint = mint.div(basis).div(basis); return mint; } } // File: contracts/src/policy/DIP7.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; /** * DIP7 is a contract that changes the `rewards` of DIP1. */ contract DIP7 is DIP1, Curve { uint256 private constant mint_per_block_and_aseet = 120000000000000; constructor(address _config) public DIP1(_config) {} function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256) { uint256 totalSupply = IERC20(config().token()).totalSupply(); return curveRewards( _lockups, _assets, totalSupply, mint_per_block_and_aseet ); } } // File: contracts/src/policy/TreasuryFee.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; /** * TreasuryFee is a contract that changes the `rewards` of DIP7. */ contract TreasuryFee is DIP7, Ownable { address private treasuryAddress; constructor(address _config) public DIP7(_config) {} function shareOfTreasury(uint256 _supply) external view returns (uint256) { return _supply.div(100).mul(5); } function policyApproval(uint256, uint256) external view returns (bool) { return false; } function treasury() external view returns (address) { return treasuryAddress; } function setTreasury(address _treasury) external onlyOwner { treasuryAddress = _treasury; } } // File: contracts/interface/ILockup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface ILockup { function lockup( address _from, address _property, uint256 _value ) external; function update() external; function withdraw(address _property, uint256 _amount) external; function calculateCumulativeRewardPrices() external view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ); function calculateRewardAmount(address _property) external view returns (uint256, uint256); /** * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256); function getPropertyValue(address _property) external view returns (uint256); function getAllValue() external view returns (uint256); function getValue(address _property, address _sender) external view returns (uint256); function calculateWithdrawableInterestAmount( address _property, address _user ) external view returns (uint256); function cap() external view returns (uint256); function updateCap(uint256 _cap) external; function devMinter() external view returns (address); } // File: contracts/src/policy/Patch662.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; contract Patch662 is TreasuryFee { using SafeMath for uint256; constructor(address _config) public TreasuryFee(_config) {} function marketApproval(uint256 upVotes, uint256) external view returns (bool) { address lockup = config().lockup(); uint256 allValue = ILockup(lockup).getAllValue(); uint256 border = allValue.mul(99).div(100); return upVotes > border; } } // File: contracts/src/policy/Patch780.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; contract Patch780 is Patch662 { uint256 private constant mint_per_block_and_aseet = 132000000000000; constructor(address _config) public Patch662(_config) {} function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256) { uint256 totalSupply = IERC20(config().token()).totalSupply(); return curveRewards( _lockups, _assets, totalSupply, mint_per_block_and_aseet ); } } // File: contracts/src/policy/DIP55.sol /* solhint-disable const-name-snakecase */ pragma solidity 0.5.17; /** * GeometricMean is a contract that changes the `rewards` of DIP7. */ contract DIP55 is Patch780 { address private capSetterAddress; constructor(address _config) public Patch780(_config) {} function setCapSetter(address _setter) external onlyOwner { capSetterAddress = _setter; } function capSetter() external view returns (address) { return capSetterAddress; } }
* @dev From the passed variables, calculate the amount of reward reduced along the curve. @param _lockups Total number of locked up tokens. @param _assets Total number of authenticated assets. @param _totalSupply Total supply the token. @param _mintPerBlockAndAseet Maximum number of reward per block per asset. @return Calculated reward amount per block per asset./
) internal pure returns (uint256) { uint256 t = _totalSupply; uint256 s = (_lockups.mul(basis)).div(t); uint256 assets = _assets.mul(basis.sub(s)); uint256 max = assets.mul(_mintPerBlockAndAseet); uint256 _d = basis.sub(s); uint256 _p = ( (power_basis.mul(12)).sub( s.div((basis.div((power_basis.mul(10))))) ) ) .div(2); uint256 p = _p.div(power_basis); uint256 rp = p.add(1); uint256 f = _p.sub(p.mul(power_basis)); uint256 d1 = _d; uint256 d2 = _d; for (uint256 i = 0; i < p; i++) { d1 = (d1.mul(_d)).div(basis); } for (uint256 i = 0; i < rp; i++) { d2 = (d2.mul(_d)).div(basis); } uint256 g = ((d1.sub(d2)).mul(f)).div(power_basis); uint256 d = d1.sub(g); uint256 mint = max.mul(d); mint = mint.div(basis).div(basis); return mint; }
7,931,392
[ 1, 1265, 326, 2275, 3152, 16, 4604, 326, 3844, 434, 19890, 13162, 7563, 326, 8882, 18, 225, 389, 739, 18294, 10710, 1300, 434, 8586, 731, 2430, 18, 225, 389, 9971, 10710, 1300, 434, 9370, 7176, 18, 225, 389, 4963, 3088, 1283, 10710, 14467, 326, 1147, 18, 225, 389, 81, 474, 2173, 1768, 1876, 37, 307, 278, 18848, 1300, 434, 19890, 1534, 1203, 1534, 3310, 18, 327, 15994, 690, 19890, 3844, 1534, 1203, 1534, 3310, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 11890, 5034, 268, 273, 389, 4963, 3088, 1283, 31, 203, 202, 202, 11890, 5034, 272, 273, 261, 67, 739, 18294, 18, 16411, 12, 23774, 13, 2934, 2892, 12, 88, 1769, 203, 202, 202, 11890, 5034, 7176, 273, 389, 9971, 18, 16411, 12, 23774, 18, 1717, 12, 87, 10019, 203, 202, 202, 11890, 5034, 943, 273, 7176, 18, 16411, 24899, 81, 474, 2173, 1768, 1876, 37, 307, 278, 1769, 203, 202, 202, 11890, 5034, 389, 72, 273, 10853, 18, 1717, 12, 87, 1769, 203, 202, 202, 11890, 5034, 389, 84, 273, 203, 1082, 202, 12, 203, 9506, 202, 12, 12238, 67, 23774, 18, 16411, 12, 2138, 13, 2934, 1717, 12, 203, 6862, 202, 87, 18, 2892, 12443, 23774, 18, 2892, 12443, 12238, 67, 23774, 18, 16411, 12, 2163, 3719, 20349, 203, 9506, 202, 13, 203, 1082, 202, 13, 203, 9506, 202, 18, 2892, 12, 22, 1769, 203, 202, 202, 11890, 5034, 293, 273, 389, 84, 18, 2892, 12, 12238, 67, 23774, 1769, 203, 202, 202, 11890, 5034, 8715, 273, 293, 18, 1289, 12, 21, 1769, 203, 202, 202, 11890, 5034, 284, 273, 389, 84, 18, 1717, 12, 84, 18, 16411, 12, 12238, 67, 23774, 10019, 203, 202, 202, 11890, 5034, 302, 21, 273, 389, 72, 31, 203, 202, 202, 11890, 5034, 302, 22, 273, 389, 72, 31, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 293, 31, 277, 27245, 288, 203, 1082, 202, 72, 21, 273, 261, 2 ]
./full_match/5/0x7a66B21a7708c42049e88aC696B55588e01AF7B4/sources/project_/contracts/FOHLE_Router01.sol
refund dust eth, if any
function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = IFOHLE_Factory(factory).getPair(token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IFOHLE_Pair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
1,932,419
[ 1, 1734, 1074, 302, 641, 13750, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 1584, 44, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 3844, 1345, 25683, 16, 203, 3639, 2254, 3844, 1345, 2930, 16, 203, 3639, 2254, 3844, 1584, 44, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 5024, 3849, 8843, 429, 3387, 12, 22097, 1369, 13, 1135, 261, 11890, 3844, 1345, 16, 2254, 3844, 1584, 44, 16, 2254, 4501, 372, 24237, 13, 288, 203, 3639, 261, 8949, 1345, 16, 3844, 1584, 44, 13, 273, 389, 1289, 48, 18988, 24237, 12, 203, 5411, 1147, 16, 203, 5411, 678, 1584, 44, 16, 203, 5411, 3844, 1345, 25683, 16, 203, 5411, 1234, 18, 1132, 16, 203, 5411, 3844, 1345, 2930, 16, 203, 5411, 3844, 1584, 44, 2930, 203, 3639, 11272, 203, 3639, 1758, 3082, 273, 467, 3313, 44, 900, 67, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 16, 678, 1584, 44, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 16, 1234, 18, 15330, 16, 3082, 16, 3844, 1345, 1769, 203, 3639, 1815, 12, 45, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 12, 6017, 16, 3844, 1584, 44, 10019, 203, 3639, 4501, 372, 24237, 273, 467, 3313, 44, 900, 67, 4154, 12, 6017, 2934, 81, 474, 12, 869, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 3844, 1584, 44, 13, 12279, 2276, 18, 4626, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 300, 3844, 1584, 44, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // website: www.defyswap.finance // /* * @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 {} 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; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 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 * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module 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; } } // /** * @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, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) internal _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 bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _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 {ERC20-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 {ERC20-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 Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public virtual onlyOwner returns (bool) { _mint(_msgSender(), amount); 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'); _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') ); } } // DFYToken with Governance. contract DfyToken is ERC20('DefySwap', 'DFY') { mapping (address => bool) private _isRExcludedFromFee; // excluded list from receive mapping (address => bool) private _isSExcludedFromFee; // excluded list from send mapping (address => bool) private _isPair; uint256 public _burnFee = 40; uint256 public _ilpFee = 5; uint256 public _devFee = 4; uint256 public _maxTxAmount = 10 * 10**6 * 1e18; uint256 public constant _maxSupply = 10 * 10**6 * 1e18; address public BURN_VAULT; address public ILP_VAULT; address public defyMaster; address public dev; address public router; event NewDeveloper(address); event ExcludeFromFeeR(address); event ExcludeFromFeeS(address); event IncludeInFeeR(address); event IncludeInFeeS(address); event SetRouter(address); event SetPair(address,bool); event BurnFeeUpdated(uint256,uint256); event IlpFeeUpdated(uint256,uint256); event DevFeeUpdated(uint256,uint256); event SetBurnVault(address); event SetIlpVault(address); event SetDefyMaster(address); event Burn(uint256); modifier onlyDev() { require(msg.sender == owner() || msg.sender == dev , "Error: Require developer or Owner"); _; } modifier onlyMaster() { require(msg.sender == defyMaster , "Error: Only DefyMaster"); _; } constructor(address _dev, address _bunVault, uint256 _initAmount) public { require(_dev != address(0), 'DEFY: dev cannot be the zero address'); require(_bunVault != address(0), 'DEFY: burn vault cannot be the zero address'); dev = _dev; BURN_VAULT = _bunVault; defyMaster = msg.sender; mint(msg.sender,_initAmount); _isRExcludedFromFee[msg.sender] = true; _isRExcludedFromFee[_bunVault] = true; _isRExcludedFromFee[_dev] = true; _isSExcludedFromFee[msg.sender] = true; _isSExcludedFromFee[_bunVault] = true; _isSExcludedFromFee[_dev] = true; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster). function mint(address _to, uint256 _amount) public onlyMaster returns (bool) { require(_maxSupply >= totalSupply().add(_amount) , "Error : Total Supply Reached" ); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); return true; } function mint(uint256 amount) public override onlyMaster returns (bool) { require(_maxSupply >= totalSupply().add(amount) , "Error : Total Supply Reached" ); _mint(_msgSender(), amount); _moveDelegates(address(0), _delegates[_msgSender()], amount); return true; } // Exclude an account from receive fee function excludeFromFeeR(address account) external onlyOwner { require(!_isRExcludedFromFee[account], "Account is already excluded From receive Fee"); _isRExcludedFromFee[account] = true; emit ExcludeFromFeeR(account); } // Exclude an account from send fee function excludeFromFeeS(address account) external onlyOwner { require(!_isSExcludedFromFee[account], "Account is already excluded From send Fee"); _isSExcludedFromFee[account] = true; emit ExcludeFromFeeS(account); } // Include an account in receive fee function includeInFeeR(address account) external onlyOwner { require( _isRExcludedFromFee[account], "Account is not excluded From receive Fee"); _isRExcludedFromFee[account] = false; emit IncludeInFeeR(account); } // Include an account in send fee function includeInFeeS(address account) external onlyOwner { require( _isSExcludedFromFee[account], "Account is not excluded From send Fee"); _isSExcludedFromFee[account] = false; emit IncludeInFeeS(account); } function setRouter(address _router) external onlyOwner { require(_router != address(0), 'DEFY: Router cannot be the zero address'); router = _router; emit SetRouter(_router); } function setPair(address _pair, bool _status) external onlyOwner { require(_pair != address(0), 'DEFY: Pair cannot be the zero address'); _isPair[_pair] = _status; emit SetPair(_pair , _status); } function setBurnFee(uint256 burnFee) external onlyOwner() { require(burnFee <= 80 , "Error : MaxBurnFee is 8%"); uint256 _previousBurnFee = _burnFee; _burnFee = burnFee; emit BurnFeeUpdated(_previousBurnFee,_burnFee); } function setDevFee(uint256 devFee) external onlyOwner() { require(devFee <= 20 , "Error : MaxDevFee is 2%"); uint256 _previousDevFee = _devFee; _devFee = devFee; emit DevFeeUpdated(_previousDevFee,_devFee); } function setIlpFee(uint256 ilpFee) external onlyOwner() { require(ilpFee <= 50 , "Error : MaxIlpFee is 5%"); uint256 _previousIlpFee = _ilpFee; _ilpFee = ilpFee; emit IlpFeeUpdated(_previousIlpFee,_ilpFee); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent >= 5 , "Error : Minimum maxTxLimit is 5%"); require(maxTxPercent <= 100 , "Error : Maximum maxTxLimit is 100%"); _maxTxAmount = totalSupply().mul(maxTxPercent).div( 10**2 ); } function setDev(address _dev) external onlyDev { require(dev != address(0), 'DEFY: dev cannot be the zero address'); _isRExcludedFromFee[dev] = false; _isSExcludedFromFee[dev] = false; dev = _dev ; _isRExcludedFromFee[_dev] = true; _isSExcludedFromFee[_dev] = true; emit NewDeveloper(_dev); } function setBurnVault(address _burnVault) external onlyMaster { _isRExcludedFromFee[BURN_VAULT] = false; _isSExcludedFromFee[BURN_VAULT] = false; BURN_VAULT = _burnVault ; _isRExcludedFromFee[_burnVault] = true; _isSExcludedFromFee[_burnVault] = true; emit SetBurnVault(_burnVault); } function setIlpVault(address _ilpVault) external onlyOwner { _isRExcludedFromFee[ILP_VAULT] = false; _isSExcludedFromFee[ILP_VAULT] = false; ILP_VAULT = _ilpVault; _isRExcludedFromFee[_ilpVault] = true; _isSExcludedFromFee[_ilpVault] = true; emit SetIlpVault(_ilpVault); } function setMaster(address master) public onlyMaster { require(master!= address(0), 'DEFY: DefyMaster cannot be the zero address'); defyMaster = master; _isRExcludedFromFee[master] = true; _isSExcludedFromFee[master] = true; emit SetDefyMaster(master); } function isExcludedFromFee(address account) external view returns(bool Rfee , bool SFee) { return (_isRExcludedFromFee[account] , _isSExcludedFromFee[account] ); } function isPair(address account) external view returns(bool) { return _isPair[account]; } function burnToVault(uint256 amount) public { _transfer(msg.sender, BURN_VAULT, amount); } // @notice Destroys `amount` tokens from `account`, reducing the total supply. function burn(uint256 amount) public { _burn(msg.sender, amount); _moveDelegates(address(0), _delegates[msg.sender], amount); emit Burn(amount); } function transferTaxFree(address recipient, uint256 amount) public returns (bool) { require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair"); super._transfer(_msgSender(), recipient, amount); return true; } function transferFromTaxFree(address sender, address recipient, uint256 amount) public returns (bool) { require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair"); super._transfer(sender, recipient, amount); super._approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /// @dev overrides transfer function to meet tokenomics of DEFY function _transfer(address sender, address recipient, uint256 amount) internal override { //if any account belongs to _isExcludedFromFee account then remove the fee if (_isSExcludedFromFee[sender] || _isRExcludedFromFee[recipient]) { super._transfer(sender, recipient, amount); } else { // A percentage of every transfer goes to Burn Vault ,ILP Vault & Dev uint256 burnAmount = amount.mul(_burnFee).div(1000); uint256 ilpAmount = amount.mul(_ilpFee).div(1000); uint256 devAmount = amount.mul(_devFee).div(1000); // Remainder of transfer sent to recipient uint256 sendAmount = amount.sub(burnAmount).sub(ilpAmount).sub(devAmount); require(amount == sendAmount + burnAmount + ilpAmount + devAmount , "DEFY Transfer: Fee value invalid"); super._transfer(sender, BURN_VAULT, burnAmount); super._transfer(sender, ILP_VAULT, ilpAmount); super._transfer(sender, dev, devAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "DEFY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DEFY::delegateBySig: invalid nonce"); require(now <= expiry, "DEFY::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, "DEFY::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 DEFYs (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, "DEFY::_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; } } // /** * @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'); } } } // DefySTUB interface. interface DefySTUB is IERC20 { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster). function mint(address _to, uint256 _amount) external ; function burn(address _from ,uint256 _amount) external ; } //BurnVault contract BurnVault is Ownable { DfyToken public defy; address public defyMaster; event SetDefyMaster(address); event Burn(uint256); modifier onlyDefy() { require(msg.sender == owner() || msg.sender == defyMaster , "Error: Require developer or Owner"); _; } function setDefyMaster (address master) external onlyDefy{ defyMaster = master ; emit SetDefyMaster(master); } function setDefy (address _defy) external onlyDefy{ defy = DfyToken(_defy); } function burn () public onlyDefy { uint256 amount = defy.balanceOf(address(this)); defy.burn(amount); emit Burn(amount); } function burnPortion (uint256 amount) public onlyDefy { defy.burn(amount); emit Burn(amount); } } //ILP Interface. interface ImpermanentLossProtection{ //IMPERMANENT LOSS PROTECTION ABI function add(address _lpToken, IERC20 _token0, IERC20 _token1, bool _offerILP) external; function set(uint256 _pid, IERC20 _token0,IERC20 _token1, bool _offerILP) external; function getDepositValue(uint256 amount, uint256 _pid) external view returns (uint256 userDepValue); function defyTransfer(address _to, uint256 _amount) external; function getDefyPrice(uint256 _pid) external view returns (uint256 defyPrice); } // DefyMaster is the master of Defy. He can make Dfy and he is a fair guy. // Have fun reading it. Hopefully it's bug-free. God bless. contract DefyMaster is Ownable , ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. (same as rewardDebt) uint256 rewardDebtDR; // Reward debt Secondary reward. See explanation below. uint256 depositTime; // Time when the user deposit LP tokens. uint256 depVal; // LP token value at the deposit time. // // We do some fancy math here. Basically, any point in time, the amount of DFYs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accDefyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accDefyPerShare` (and `lastRewardTimestamp`) 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. DefySTUB stubToken; // STUB / Receipt Token for farmers. uint256 allocPoint; // How many allocation points assigned to this pool. DFYs to distribute per Second. uint256 allocPointDR; // How many allocation points assigned to this pool for Secondary Reward. uint256 depositFee; // LP Deposit fee. uint256 withdrawalFee; // LP Withdrawal fee uint256 lastRewardTimestamp; // Last timestamp that DFYs distribution occurs. uint256 lastRewardTimestampDR; // Last timestamp that Secondary Reward distribution occurs. uint256 rewardEndTimestamp; // Reward ending Timestamp. uint256 accDefyPerShare; // Accumulated DFYs per share, times 1e12. See below. uint256 accSecondRPerShare; // Accumulated Second Reward Tokens per share, times 1e24. See below. uint256 lpSupply; // Total Lp tokens Staked in farm. bool impermanentLossProtection; // ILP availability bool issueStub; // STUB Availability. } // The DFY TOKEN! DfyToken public defy; // Secondary Reward Token. IERC20 public secondR; // BurnVault. BurnVault public burn_vault; //ILP Contract ImpermanentLossProtection public ilp; // Dev address. address public devaddr; // Emergency Dev address public emDev; // Deposit/Withdrawal Fee address address public feeAddress; // DFY tokens created per second. uint256 public defyPerSec; // Secondary Reward distributed per second. uint256 public secondRPerSec; // Bonus muliplier for early dfy makers. uint256 public BONUS_MULTIPLIER = 1; //Max uint256 uint256 constant MAX_INT = type(uint256).max ; // Seconds per burn cycle. uint256 public SECONDS_PER_CYCLE = 365 * 2 days ; // Max DFY Supply. uint256 public constant MAX_SUPPLY = 10 * 10**6 * 1e18; // Next minting cycle start timestamp. uint256 public nextCycleTimestamp; // The Timestamp when Secondary Reward mining ends. uint256 public endTimestampDR = MAX_INT; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // Total allocation points for Dual Reward. Must be the sum of all Dual reward allocation points in all pools. uint256 public totalAllocPointDR = 0; // The Timestamp when DFY mining starts. uint256 public startTimestamp; modifier onlyDev() { require(msg.sender == owner() || msg.sender == devaddr , "Error: Require developer or Owner"); _; } 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 SetFeeAddress(address newAddress); event SetDevAddress(address newAddress); event SetDFY(address dfy); event SetSecondaryReward(address newToken); event UpdateEmissionRate(uint256 defyPerSec); event UpdateSecondaryEmissionRate(uint256 secondRPerSec); event DFYOwnershipTransfer(address newOwner); event RenounceEmDev(); event addPool( uint256 indexed pid, address lpToken, uint256 allocPoint, uint256 allocPointDR, uint256 depositFee, uint256 withdrawalFee, bool offerILP, bool issueStub, uint256 rewardEndTimestamp); event setPool( uint256 indexed pid, uint256 allocPoint, uint256 allocPointDR, uint256 depositFee, uint256 withdrawalFee, bool offerILP, bool issueStub, uint256 rewardEndTimestamp); event UpdateStartTimestamp(uint256 newStartTimestamp); constructor( DfyToken _defy, DefySTUB _stub, BurnVault _burnvault, address _devaddr, address _emDev, address _feeAddress, uint256 _startTimestamp, uint256 _initMint ) public { require(_devaddr != address(0), 'DEFY: dev cannot be the zero address'); require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address'); require(_startTimestamp >= block.timestamp , 'DEFY: Invalid start time'); defy = _defy; burn_vault = _burnvault; devaddr = _devaddr; emDev = _emDev; feeAddress = _feeAddress; startTimestamp = _startTimestamp; defyPerSec = (MAX_SUPPLY.sub(_initMint)).div(SECONDS_PER_CYCLE); nextCycleTimestamp = startTimestamp.add(SECONDS_PER_CYCLE); // staking pool poolInfo.push(PoolInfo({ lpToken: _defy, stubToken: _stub, allocPoint: 400, allocPointDR: 0, depositFee: 0, withdrawalFee: 0, lastRewardTimestamp: startTimestamp, lastRewardTimestampDR: startTimestamp, rewardEndTimestamp: MAX_INT, accDefyPerShare: 0, accSecondRPerShare: 0, lpSupply: 0, impermanentLossProtection: false, issueStub: true })); totalAllocPoint = 400; } function setImpermanentLossProtection(address _ilp)public onlyDev returns (bool){ require(_ilp != address(0), 'DEFY: ILP cannot be the zero address'); ilp = ImpermanentLossProtection(_ilp); } function setFeeAddress(address _feeAddress)public onlyDev returns (bool){ require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address'); feeAddress = _feeAddress; emit SetFeeAddress(_feeAddress); return true; } function setDFY(DfyToken _dfy)public onlyDev returns (bool){ require(_dfy != DfyToken(0), 'DEFY: DFY cannot be the zero address'); defy = _dfy; emit SetDFY(address(_dfy)); return true; } function setSecondaryReward(IERC20 _rewardToken)public onlyDev returns (bool){ require(_rewardToken != IERC20(0), 'DEFY: SecondaryReward cannot be the zero address'); secondR = _rewardToken; emit SetSecondaryReward(address(_rewardToken)); return true; } function getUserInfo(uint256 pid, address userAddr) public view returns(uint256 deposit, uint256 rewardDebt, uint256 rewardDebtDR, uint256 daysSinceDeposit, uint256 depVal) { UserInfo storage user = userInfo[pid][userAddr]; return (user.amount, user.rewardDebt, user.rewardDebtDR, _getDaysSinceDeposit(pid, userAddr), user.depVal); } //Time Functions function getDaysSinceDeposit(uint256 pid, address userAddr) external view returns (uint256 daysSinceDeposit) { return _getDaysSinceDeposit(pid, userAddr); } function _getDaysSinceDeposit(uint256 _pid, address _userAddr) internal view returns (uint256) { UserInfo storage user = userInfo[_pid][_userAddr]; if (block.timestamp < user.depositTime){ return 0; }else{ return (block.timestamp.sub(user.depositTime)) / 1 days; } } function checkForIL(uint256 pid, address userAddr) external view returns (uint256 extraDefy) { UserInfo storage user = userInfo[pid][userAddr]; return _checkForIL(pid, user); } function _checkForIL(uint256 _pid, UserInfo storage user) internal view returns (uint256) { uint256 defyPrice = ilp.getDefyPrice(_pid); uint256 currentVal = ilp.getDepositValue(user.amount, _pid); if(currentVal < user.depVal){ uint256 difference = user.depVal.sub(currentVal); return difference.div(defyPrice); }else return 0; } function setStartTimestamp(uint256 sTimestamp) public onlyDev{ require(sTimestamp > block.timestamp, "Invalid Timestamp"); startTimestamp = sTimestamp; emit UpdateStartTimestamp(sTimestamp); } function updateMultiplier(uint256 multiplierNumber) public onlyDev { require(multiplierNumber != 0, " multiplierNumber should not be null"); BONUS_MULTIPLIER = multiplierNumber; } function updateEmissionRate(uint256 endTimestamp) external { require(endTimestamp > ((block.timestamp).add(182 days)), "Minimum duration is 6 months"); require ( msg.sender == devaddr , "only dev!"); massUpdatePools(); SECONDS_PER_CYCLE = endTimestamp.sub(block.timestamp); defyPerSec = MAX_SUPPLY.sub(defy.totalSupply()).div(SECONDS_PER_CYCLE); nextCycleTimestamp = endTimestamp; emit UpdateEmissionRate(defyPerSec); } function updateReward() internal { uint256 burnAmount = defy.balanceOf(address(burn_vault)); defyPerSec = burnAmount.div(SECONDS_PER_CYCLE); burn_vault.burn(); emit UpdateEmissionRate(defyPerSec); } function updateSecondReward(uint256 _reward, uint256 _endTimestamp) public onlyOwner{ require(_endTimestamp > block.timestamp , "invalid End timestamp"); massUpdatePools(); endTimestampDR = _endTimestamp; secondRPerSec = 0; massUpdatePools(); secondRPerSec = _reward.div((_endTimestamp).sub(block.timestamp)); emit UpdateSecondaryEmissionRate(secondRPerSec); } function poolLength() external view returns (uint256) { return poolInfo.length; } // 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. // XXX DO NOT set ILP for non DFY pairs. function add( uint256 _allocPoint, uint256 _allocPointDR, IERC20 _lpToken, DefySTUB _stub, IERC20 _token0, IERC20 _token1, uint256 _depositFee, uint256 _withdrawalFee, bool _offerILP, bool _issueSTUB, uint256 _rewardEndTimestamp ) public onlyDev { require(_depositFee <= 600, "Add : Max Deposit Fee is 6%"); require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%"); require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp"); massUpdatePools(); ilp.add(address(_lpToken), _token0, _token1, _offerILP); uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); totalAllocPointDR = totalAllocPointDR.add(_allocPointDR); poolInfo.push(PoolInfo({ lpToken: _lpToken, stubToken: _stub, allocPoint: _allocPoint, allocPointDR: _allocPointDR, depositFee: _depositFee, withdrawalFee: _withdrawalFee, lastRewardTimestamp: lastRewardTimestamp, lastRewardTimestampDR: lastRewardTimestamp, rewardEndTimestamp: _rewardEndTimestamp, accDefyPerShare: 0, accSecondRPerShare: 0, lpSupply: 0, impermanentLossProtection: _offerILP, issueStub: _issueSTUB })); emit addPool(poolInfo.length - 1, address(_lpToken), _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp); } // Update the given pool's DFY allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, uint256 _allocPointDR, IERC20 _token0, IERC20 _token1, uint256 _depositFee, uint256 _withdrawalFee, bool _offerILP, bool _issueSTUB, uint256 _rewardEndTimestamp ) public onlyOwner { require(_depositFee <= 600, "Add : Max Deposit Fee is 6%"); require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%"); require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp"); massUpdatePools(); ilp.set(_pid, _token0, _token1, _offerILP); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); totalAllocPointDR = totalAllocPointDR.sub(poolInfo[_pid].allocPointDR).add(_allocPointDR); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].allocPointDR = _allocPointDR; poolInfo[_pid].depositFee = _depositFee; poolInfo[_pid].withdrawalFee = _withdrawalFee; poolInfo[_pid].rewardEndTimestamp = _rewardEndTimestamp; poolInfo[_pid].impermanentLossProtection = _offerILP; poolInfo[_pid].issueStub = _issueSTUB; emit setPool(_pid , _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp); } // Return reward multiplier over the given _from to _to Timestamp. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending DFYs on frontend. function pendingDefy(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDefyPerShare = pool.accDefyPerShare; uint256 lpSupply = pool.lpSupply; if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0 && totalAllocPoint != 0) { uint256 blockTimestamp; if(block.timestamp < nextCycleTimestamp){ blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp; } else{ blockTimestamp = nextCycleTimestamp; } uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp); uint256 defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint); accDefyPerShare = accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accDefyPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending Secondary Reward on frontend. function pendingSecondR(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSecondRPerShare = pool.accSecondRPerShare; uint256 lpSupply = pool.lpSupply; if (block.timestamp > pool.lastRewardTimestampDR && lpSupply != 0 && totalAllocPointDR != 0) { uint256 blockTimestamp; if(block.timestamp < endTimestampDR){ blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp; } else{ blockTimestamp = endTimestampDR; } uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestamp); uint256 secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR); accSecondRPerShare = accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply)); } return user.amount.mul(accSecondRPerShare).div(1e24).sub(user.rewardDebtDR); } // 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); } if (block.timestamp > nextCycleTimestamp){ nextCycleTimestamp = (block.timestamp).add(SECONDS_PER_CYCLE); defyPerSec = 0; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } updateReward(); } } // Update reward variables of the given pool to be up-to-date. function updatePoolPb(uint256 _pid) public { if (block.timestamp > nextCycleTimestamp){ massUpdatePools(); } else { updatePool(_pid); } } function updatePool(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTimestamp && block.timestamp <= pool.lastRewardTimestampDR) { return; } uint256 lpSupply = pool.lpSupply; uint256 blockTimestamp; if(block.timestamp < nextCycleTimestamp){ blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp; } else{ blockTimestamp = nextCycleTimestamp; } uint256 blockTimestampDR; if(block.timestamp < endTimestampDR){ blockTimestampDR = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp; } else{ blockTimestampDR = endTimestampDR; } if (lpSupply == 0) { pool.lastRewardTimestamp = blockTimestamp; pool.lastRewardTimestampDR = blockTimestampDR; return; } if (pool.allocPoint == 0 && pool.allocPointDR == 0) { pool.lastRewardTimestamp = blockTimestamp; pool.lastRewardTimestampDR = blockTimestampDR; return; } uint256 defyReward = 0 ; uint256 secondRReward = 0 ; if(totalAllocPoint != 0){ uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp); defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint); } if(totalAllocPointDR != 0){ uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestampDR); secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR); } if(defyReward > 0 ){ defy.mint(address(this), defyReward); } pool.accDefyPerShare = pool.accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply)); pool.accSecondRPerShare = pool.accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply)); pool.lastRewardTimestamp = blockTimestamp; pool.lastRewardTimestampDR = blockTimestampDR; } // Deposit LP tokens to DefyMaster for DFY allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePoolPb(_pid); uint256 amount_ = _amount; //If the LP token balance is lower than _amount, //total LP tokens in the wallet will be deposited if(amount_ > pool.lpToken.balanceOf(msg.sender)){ amount_ = pool.lpToken.balanceOf(msg.sender); } //check for ILP DFY uint256 extraDefy = 0; if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){ extraDefy = _checkForIL(_pid, user); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt); uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR); if(pending > 0) { safeDefyTransfer(msg.sender, pending); } if(pendingDR > 0) { safeSecondRTransfer(msg.sender, pendingDR); } if(extraDefy > 0 && extraDefy > pending){ ilp.defyTransfer(msg.sender, extraDefy.sub(pending)); } } if (amount_ > 0) { uint256 before = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount_); uint256 _after = pool.lpToken.balanceOf(address(this)); amount_ = _after.sub(before); // Real amount of LP transfer to this address if (pool.depositFee > 0) { uint256 depositFee = amount_.mul(pool.depositFee).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); if (pool.issueStub){ pool.stubToken.mint(msg.sender, amount_.sub(depositFee)); } user.amount = user.amount.add(amount_).sub(depositFee); pool.lpSupply = pool.lpSupply.add(amount_).sub(depositFee); } else { user.amount = user.amount.add(amount_); pool.lpSupply = pool.lpSupply.add(amount_); if (pool.issueStub){ pool.stubToken.mint(msg.sender, amount_); } } } user.depVal = ilp.getDepositValue(user.amount, _pid); user.depositTime = block.timestamp; user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12); user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24); emit Deposit(msg.sender, _pid, amount_); } // Withdraw LP tokens from DefyMaster. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0 , "withdraw: nothing to withdraw"); updatePoolPb(_pid); uint256 amount_ = _amount; //If the User LP token balance in farm is lower than _amount, //total User LP tokens in the farm will be withdrawn if(amount_ > user.amount){ amount_ = user.amount; } //ILP uint256 extraDefy = 0; if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){ extraDefy = _checkForIL(_pid, user); } uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt); uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR); if(pending > 0) { safeDefyTransfer(msg.sender, pending); } if(pendingDR > 0) { safeSecondRTransfer(msg.sender, pendingDR); } if(extraDefy > 0 && extraDefy > pending){ ilp.defyTransfer(msg.sender, extraDefy.sub(pending)); } if(amount_ > 0) { if (pool.issueStub){ require(pool.stubToken.balanceOf(msg.sender) >= amount_ , "withdraw : No enough STUB tokens!"); pool.stubToken.burn(msg.sender, amount_); } if (pool.withdrawalFee > 0) { uint256 withdrawalFee = amount_.mul(pool.withdrawalFee).div(10000); pool.lpToken.safeTransfer(feeAddress, withdrawalFee); pool.lpToken.safeTransfer(address(msg.sender), amount_.sub(withdrawalFee)); } else { pool.lpToken.safeTransfer(address(msg.sender), amount_); } user.amount = user.amount.sub(amount_); pool.lpSupply = pool.lpSupply.sub(amount_); } user.depVal = ilp.getDepositValue(user.amount, _pid); user.depositTime = block.timestamp; user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12); user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24); emit Withdraw(msg.sender, _pid, amount_); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); pool.lpSupply = pool.lpSupply.sub(user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; user.rewardDebtDR = 0; } // Safe defy transfer function, just in case if rounding error causes pool to not have enough DFYs. function safeDefyTransfer(address _to, uint256 _amount) internal { uint256 defyBal = defy.balanceOf(address(this)); bool successfulTansfer = false; if (_amount > defyBal) { successfulTansfer = defy.transfer(_to, defyBal); } else { successfulTansfer = defy.transfer(_to, _amount); } require(successfulTansfer, "safeDefyTransfer: transfer failed"); } // Safe SecondR transfer function, just in case if rounding error causes pool to not have enough Secondary reward tokens. function safeSecondRTransfer(address _to, uint256 _amount) internal { uint256 secondRBal = secondR.balanceOf(address(this)); bool successfulTansfer = false; if (_amount > secondRBal) { successfulTansfer = secondR.transfer(_to, secondRBal); } else { successfulTansfer = secondR.transfer(_to, _amount); } require(successfulTansfer, "safeSecondRTransfer: transfer failed"); } // only in an Emergency by emDev function transferOwnerDfy(address _newOwner) external { require (msg.sender == emDev , "only emergency dev"); defy.transferOwnership(_newOwner); emit DFYOwnershipTransfer(_newOwner); } function renounceEmDev() external { require (msg.sender == emDev , "only emergency dev"); emDev = address(0); emit RenounceEmDev(); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(_devaddr != address(0), 'DEFY: dev cannot be the zero address'); require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Include an account in receive fee
function includeInFeeR(address account) external onlyOwner { require( _isRExcludedFromFee[account], "Account is not excluded From receive Fee"); _isRExcludedFromFee[account] = false; emit IncludeInFeeR(account); }
7,244,170
[ 1, 8752, 392, 2236, 316, 6798, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2341, 382, 14667, 54, 12, 2867, 2236, 13, 3903, 1338, 5541, 288, 202, 203, 540, 2583, 12, 389, 291, 54, 16461, 1265, 14667, 63, 4631, 6487, 315, 3032, 353, 486, 8845, 6338, 6798, 30174, 8863, 202, 203, 3639, 389, 291, 54, 16461, 1265, 14667, 63, 4631, 65, 273, 629, 31, 202, 203, 3639, 3626, 12672, 382, 14667, 54, 12, 4631, 1769, 202, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
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; } } contract TokenInterface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function getMaxTotalSupply() public view returns (uint256); function mint(address _to, uint256 _amount) public returns (bool); function transfer(address _to, uint256 _amount) public returns (bool); function allowance( address _who, address _spender ) public view returns (uint256); function transferFrom( address _from, address _to, uint256 _value ) public returns (bool); } contract MiningTokenInterface { function multiMint(address _to, uint256 _amount) external; function getTokenTime(uint256 _tokenId) external returns(uint256); function mint(address _to, uint256 _id) external; function ownerOf(uint256 _tokenId) public view returns (address); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 _balance); function tokenByIndex(uint256 _index) public view returns (uint256); function arrayOfTokensByAddress(address _holder) public view returns(uint256[]); function getTokensCount(address _owner) public returns(uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); } contract Management { using SafeMath for uint256; uint256 public startPriceForHLPMT = 10000; uint256 public maxHLPMTMarkup = 40000; uint256 public stepForPrice = 1000; uint256 public startTime; uint256 public lastMiningTime; // default value uint256 public decimals = 18; TokenInterface public token; MiningTokenInterface public miningToken; address public dao; address public fund; address public owner; // num of mining times uint256 public numOfMiningTimes; mapping(address => uint256) public payments; mapping(address => uint256) public paymentsTimestamps; // mining time => mining reward mapping(uint256 => uint256) internal miningReward; // id mining token => getting reward last mining mapping(uint256 => uint256) internal lastGettingReward; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyDao() { require(msg.sender == dao); _; } constructor( address _token, address _miningToken, address _dao, address _fund ) public { require(_token != address(0)); require(_miningToken != address(0)); require(_dao != address(0)); require(_fund != address(0)); startTime = now; lastMiningTime = startTime - (startTime % (1 days)) - 1 days; owner = msg.sender; token = TokenInterface(_token); miningToken = MiningTokenInterface(_miningToken); dao = _dao; fund = _fund; } /** * @dev Exchanges the HLT tokens to HLPMT tokens. Works up to 48 HLPMT * tokens at one-time buying. Should call after approving HLT tokens to * manager address. */ function buyHLPMT() external { uint256 _currentTime = now; uint256 _allowed = token.allowance(msg.sender, address(this)); uint256 _currentPrice = getPrice(_currentTime); require(_allowed >= _currentPrice); //remove the remainder uint256 _hlpmtAmount = _allowed.div(_currentPrice); _allowed = _hlpmtAmount.mul(_currentPrice); require(token.transferFrom(msg.sender, fund, _allowed)); for (uint256 i = 0; i < _hlpmtAmount; i++) { uint256 _id = miningToken.totalSupply(); miningToken.mint(msg.sender, _id); lastGettingReward[_id] = numOfMiningTimes; } } /** * @dev Produces the mining process and sends reward to dao and fund. */ function mining() external { uint256 _currentTime = now; require(_currentTime > _getEndOfLastMiningDay()); uint256 _missedDays = (_currentTime - lastMiningTime) / (1 days); updateLastMiningTime(_currentTime); for (uint256 i = 0; i < _missedDays; i++) { // 0.1% daily from remaining unmined tokens. uint256 _dailyTokens = token.getMaxTotalSupply().sub(token.totalSupply()).div(1000); uint256 _tokensToDao = _dailyTokens.mul(3).div(10); // 30 percent token.mint(dao, _tokensToDao); uint256 _tokensToFund = _dailyTokens.mul(3).div(10); // 30 percent token.mint(fund, _tokensToFund); uint256 _miningTokenSupply = miningToken.totalSupply(); uint256 _tokensToMiners = _dailyTokens.mul(4).div(10); // 40 percent uint256 _tokensPerMiningToken = _tokensToMiners.div(_miningTokenSupply); miningReward[++numOfMiningTimes] = _tokensPerMiningToken; token.mint(address(this), _tokensToMiners); } } /** * @dev Sends the daily mining reward to HLPMT holder. */ function getReward(uint256[] tokensForReward) external { uint256 _rewardAmount = 0; for (uint256 i = 0; i < tokensForReward.length; i++) { if ( msg.sender == miningToken.ownerOf(tokensForReward[i]) && numOfMiningTimes > getLastRewardTime(tokensForReward[i]) ) { _rewardAmount += _calculateReward(tokensForReward[i]); setLastRewardTime(tokensForReward[i], numOfMiningTimes); } } require(_rewardAmount > 0); token.transfer(msg.sender, _rewardAmount); } function checkReward(uint256[] tokensForReward) external view returns (uint256) { uint256 reward = 0; for (uint256 i = 0; i < tokensForReward.length; i++) { if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) { reward += _calculateReward(tokensForReward[i]); } } return reward; } /** * @param _tokenId token id * @return timestamp of token creation */ function getLastRewardTime(uint256 _tokenId) public view returns(uint256) { return lastGettingReward[_tokenId]; } /** * @dev Sends the daily mining reward to HLPMT holder. */ function sendReward(uint256[] tokensForReward) public onlyOwner { for (uint256 i = 0; i < tokensForReward.length; i++) { if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) { uint256 reward = _calculateReward(tokensForReward[i]); setLastRewardTime(tokensForReward[i], numOfMiningTimes); token.transfer(miningToken.ownerOf(tokensForReward[i]), reward); } } } /** * @dev Returns the HLPMT token amount of holder. */ function miningTokensOf(address holder) public view returns (uint256[]) { return miningToken.arrayOfTokensByAddress(holder); } /** * @dev Sets the DAO address * @param _dao DAO address. */ function setDao(address _dao) public onlyOwner { require(_dao != address(0)); dao = _dao; } /** * @dev Sets the fund address * @param _fund Fund address. */ function setFund(address _fund) public onlyOwner { require(_fund != address(0)); fund = _fund; } /** * @dev Sets the token address * @param _token Token address. */ function setToken(address _token) public onlyOwner { require(_token != address(0)); token = TokenInterface(_token); } /** * @dev Sets the mining token address * @param _miningToken Mining token address. */ function setMiningToken(address _miningToken) public onlyOwner { require(_miningToken != address(0)); miningToken = MiningTokenInterface(_miningToken); } /** * @return uint256 the current HLPMT token price in HLT (without decimals). */ function getPrice(uint256 _timestamp) public view returns(uint256) { uint256 _raising = _timestamp.sub(startTime).div(30 days); _raising = _raising.mul(stepForPrice); if (_raising > maxHLPMTMarkup) _raising = maxHLPMTMarkup; return (startPriceForHLPMT + _raising) * 10 ** 18; } /** * @param _numOfMiningTime is time * @return getting token reward */ function getMiningReward(uint256 _numOfMiningTime) public view returns (uint256) { return miningReward[_numOfMiningTime]; } /** * @dev Returns the calculated reward amount. */ function _calculateReward(uint256 tokenID) internal view returns (uint256 reward) { for (uint256 i = getLastRewardTime(tokenID) + 1; i <= numOfMiningTimes; i++) { reward += miningReward[i]; } return reward; } /** * @dev set last getting token reward time */ function setLastRewardTime(uint256 _tokenId, uint256 _num) internal { lastGettingReward[_tokenId] = _num; } /** * @dev set last getting token reward time */ function updateLastMiningTime(uint256 _currentTime) internal { lastMiningTime = _currentTime - _currentTime % (1 days); } /** * @return uint256 the unix timestamp of the end of the last mining day. */ function _getEndOfLastMiningDay() internal view returns(uint256) { return lastMiningTime + 1 days; } /** * @dev Withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; uint256 timestamp = paymentsTimestamps[payee]; require(payment != 0); require(now >= timestamp); payments[payee] = 0; require(token.transfer(msg.sender, payment)); } /** * @dev Called by the payer to store the sent _amount as credit to be pulled. * @param _dest The destination address of the funds. * @param _amount The amount to transfer. */ function asyncSend(address _dest, uint256 _amount, uint256 _timestamp) external onlyDao { payments[_dest] = payments[_dest].add(_amount); paymentsTimestamps[_dest] = _timestamp; require(token.transferFrom(dao, address(this), _amount)); } }
* @dev Sets the DAO address @param _dao DAO address./
function setDao(address _dao) public onlyOwner { require(_dao != address(0)); dao = _dao; }
10,227,483
[ 1, 2785, 326, 463, 20463, 1758, 225, 389, 2414, 83, 463, 20463, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 11412, 12, 2867, 389, 2414, 83, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 2414, 83, 480, 1758, 12, 20, 10019, 203, 3639, 15229, 273, 389, 2414, 83, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** * 作业:编写合约执行闪电贷(参考V2的ExampleFlashSwap): * uniswapV2Call中,用收到的 TokenA 在 Uniswap V3 的 SwapRouter 兑换为 TokenB 还回到 uniswapV2 Pair 中。 */ pragma solidity ^0.8.0; import './IERC20.sol'; import './UniswapV2Library.sol'; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } contract FlashSwap is IUniswapV2Callee { address immutable factory; address immutable V3Router; address owner; receive() external payable {} // v2 _factory 0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f, v3 _v3Router:0xE592427A0AEce92De3Edee1F18E0157C05861564 constructor(address _factory, address _v3Router) { factory = _factory; V3Router = _v3Router; owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Only owner can call this function"); _; } function execArbitrage(address token0, address token1, uint amount0, uint amount1) onlyOwner public { address pairAddress = UniswapV2Library.pairFor(factory, token0, token1); require(pairAddress != address(0), 'There is no such pool'); IUniswapV2Pair(pairAddress).swap(amount0, amount1, address(this), "0x"); } function getPairAddress(address token0, address token1) onlyOwner public view returns(address pairAddress, address atoken0, address btoken1) { pairAddress = UniswapV2Library.pairFor(factory, token0, token1); atoken0 = IUniswapV2Pair(pairAddress).token0(); // BToken btoken1 = IUniswapV2Pair(pairAddress).token1(); // AToken } // 这里借 A 还 B amount0 != 0 amount1 是 A 的数量 function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external override{ // 这里 amount0 对应的 BToken, amount1 对应的是 AToken address token0; address token1; address[] memory path = new address[](2); { token0 = IUniswapV2Pair(msg.sender).token0(); // BToken token1 = IUniswapV2Pair(msg.sender).token1(); // AToken assert(msg.sender == UniswapV2Library.pairFor(factory, token0, token1)); // ensure that msg.sender is actually a V2 pair assert(amount0 == 0 || amount1 == 0); // this strategy is unidirectional path[0] = amount0 == 0 ? token0 : token1; path[1] = amount0 == 0 ? token1 : token0; } // path 对应的是 [AToken, BToken] // 先授权V3合约允许调用自身的 A token uint256 amountReceived = swapExactInputSingle(token1, token0, amount1); uint256 amountRequired = UniswapV2Library.getAmountsIn(factory, amount1, path)[0]; // 这里是需要还给池子中 B 的数量 require(IERC20(token0).balanceOf(address(this)) > amountRequired, 'amount is yes'); // return tokens to V2 pair require(amountRequired > 0, 'need > 0'); // fail if we didn't get enough B back to repay our flash loan require(amountReceived > amountRequired, 'not enough'); // fail if we didn't get enough B back to repay our flash loan assert(IERC20(token0).transfer(msg.sender, amountRequired)); // return tokens to V2 pair assert(IERC20(token0).transfer(tx.origin, amountReceived - amountRequired)); // keep the rest! (tokens) } function swapExactInputSingle(address token0, address token1, uint256 amountIn) public returns (uint256 amountOut) { TransferHelper.safeApprove(token0, address(V3Router), amountIn); // Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum. // We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount. ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: token0, tokenOut: token1, fee: 10000, recipient: address(this), // 兑换的转给合约 deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }); // The call to `exactInputSingle` executes the swap. amountOut = ISwapRouter(V3Router).exactInputSingle(params); } }
先授权V3合约允许调用自身的 A token
uint256 amountReceived = swapExactInputSingle(token1, token0, amount1);
12,650,510
[ 1, 166, 232, 235, 167, 241, 235, 167, 256, 230, 58, 23, 166, 243, 235, 168, 123, 104, 166, 232, 228, 169, 111, 121, 169, 113, 230, 168, 247, 106, 169, 234, 108, 169, 123, 109, 168, 253, 231, 432, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3844, 8872, 273, 7720, 14332, 1210, 5281, 12, 2316, 21, 16, 1147, 20, 16, 3844, 21, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xf61Dc5623656F6E23e5b20742dEbd67e872E9D56/sources/MiriChain.sol
/ Artificialintelligence Connect /fix => Crypto Block Mine Token to => Mainnet => "CBM" Coin
tokenSymbol = "Miri";
5,145,603
[ 1, 19, 9042, 1507, 649, 474, 1165, 360, 802, 8289, 342, 904, 516, 15629, 3914, 490, 558, 3155, 358, 516, 12740, 2758, 225, 516, 315, 8876, 49, 6, 28932, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 5335, 273, 315, 49, 25096, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-25 */ /* :=*#%@@@@@@@@@%%%#**+=-:::: '*%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+ * [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@#*+: ............................................................ * -*#%%#+:. :%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#+-.. '*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#- * :[email protected]@@@@@@@@@%#*+=-:. [email protected]@@@@@@@@%===#==#+=+%=**[email protected]*==*@=*@@@@@@@@@#*=-. .......................................... * .-======+*#@@@@@@@@@@@@@@@%##*+==--::::[email protected]@@@@@@@@@: =%- : .*: = == : *- %@@@@@@@@@@@@@@@@*=. -*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+. * .:=+#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@= *#+.= - +: * -= - :+ #@@@@@@@@@@@@@@@*- .::::::::::::::::::::::::::::::::::::::: * :=.-+#%%@@@@@@@@@@@@@@@@@@@@@%===%=#=*+*%===**=#+=#[email protected]@@@@@@@@@@@@%= .=*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#= * :=#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*-... .:---------------------------------------. * .--:-=*#@@@@%+#%@@@@@@@@@@@@@@@@@@@@@@@@@@@#+=: .:[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*+. * :..: .-+*#@@@@@@%#%@%@@@@@@@@%+::. .. =++++++++++++++++++++++++=. * =#%*%#*+===--::. .-#@@%: .-===+++**%@%- .*-.+* :=======================- * .%#: .=%=.:-=+*###%%%#@@@@*. .-+%%*=: :#[email protected] @@@@@@@@@@@@@@@@@@@@@@- * :+: .::-: .=*%@#+===*%%*=. -------------------: * .::--:. * * Welcome to the EMU NFTs sale for the EMUAI Solar Car proyect. Each of these NFTs are going to represent ownership of one 1.5 by 1.5 centimeter square * of our virtual solar car's surface and on our physical solar car once it is built (with the help of the funding of this campaign). * This representation will also be called an EMU. * * The Owner of each particular EMU will be able to upload an image to that space for the world to see!! * Our car will compete in many races around the globe and appear in countless media (we have lots of contacts). * * Thank you very much for your contribution and for making this proyect possible. */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: Ownable.sol abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } } // File: EMUs-Contract.sol contract EMUAI_NFTs is ERC721, Ownable { // Time of when the sale starts and ends. uint256 public SALE_START_TIMESTAMP = 1620928800; // Thursday, May 13, 2021 18:00:00 GMT uint256 public SALE_END_TIMESTAMP = 1627840800; // Sunday, Aug 1, 2021 18:00:00 GMT // Maximum amount of EMUAI-NFTs in existance. Ever. uint16 public constant MAX_NFT_SUPPLY = 5940; // Maximum amount of EMUAI-NFTs to be minted in one transaction. This is to avoid hitting the block gas limit. uint16 public constant MAX_TRANSACTION_MINT = 250; // Token price in wei uint256 public constant TOKEN_PRICE = 60000000000000000; // Counts the supply of EMUs minted uint16 public totalSupply; //Stores the base URI string private baseURI; constructor(string memory OriginalBaseURI) ERC721("EMUAI_NFTs", "EMU") { totalSupply = 0; changeBaseURI(OriginalBaseURI); } /** * @dev Changes the start and end timestamps if needed (Callable by owner only). */ function setSaleTimestamps(uint256 start, uint256 end) onlyOwner public{ SALE_START_TIMESTAMP = start; SALE_END_TIMESTAMP = end; } function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Mints yourself an NFT. Or more. You do you. */ function mintEMU(uint16 numberOfNFTs) public payable { // Some exceptions that need to be handled. require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet."); require(totalSupply < MAX_NFT_SUPPLY && block.timestamp <= SALE_END_TIMESTAMP, "Sale has already ended."); require(numberOfNFTs <= MAX_TRANSACTION_MINT, "Exceeds maximum ammount."); require(totalSupply + numberOfNFTs <= MAX_NFT_SUPPLY, "Exceeds maximum EMUs supply."); require(TOKEN_PRICE * numberOfNFTs == msg.value, "Amount of Ether sent is not correct."); // Mint the amount of provided EMUAI-NFTs. for (uint i = 0; i < numberOfNFTs; i++) { uint mintIndex = totalSupply+1; _safeMint(msg.sender, mintIndex); totalSupply ++; } } /** * @dev Withdraw ether from this contract (Callable by owner only) */ function withdraw() onlyOwner public { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeBaseURI(string memory newBaseURI) onlyOwner public { baseURI = newBaseURI; } }
Thursday, May 13, 2021 18:00:00 GMT
uint256 public SALE_START_TIMESTAMP = 1620928800;
15,320,306
[ 1, 1315, 25152, 2881, 16, 16734, 5958, 16, 26599, 21, 6549, 30, 713, 30, 713, 21706, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 17127, 900, 67, 7570, 67, 17201, 273, 2872, 3462, 9975, 5482, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-06-06 */ /** * Source Code first verified at https://etherscan.io on Wednesday, April 24, 2019 (UTC) */ pragma solidity ^0.4.25; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title math operations that returns specific size reults (32, 64 and 256 * bits) */ library SafeMath { /** * @dev Multiplies two numbers and returns a uint64 * @param a A number * @param b A number * @return a * b as a uint64 */ function mul64(uint256 a, uint256 b) internal pure returns (uint64) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); require(c < 2**64); return uint64(c); } /** * @dev Divides two numbers and returns a uint64 * @param a A number * @param b A number * @return a / b as a uint64 */ function div64(uint256 a, uint256 b) internal pure returns (uint64) { uint256 c = a / b; require(c < 2**64); /* solcov ignore next */ return uint64(c); } /** * @dev Substracts two numbers and returns a uint64 * @param a A number * @param b A number * @return a - b as a uint64 */ function sub64(uint256 a, uint256 b) internal pure returns (uint64) { require(b <= a); uint256 c = a - b; require(c < 2**64); /* solcov ignore next */ return uint64(c); } /** * @dev Adds two numbers and returns a uint64 * @param a A number * @param b A number * @return a + b as a uint64 */ function add64(uint256 a, uint256 b) internal pure returns (uint64) { uint256 c = a + b; require(c >= a && c < 2**64); /* solcov ignore next */ return uint64(c); } /** * @dev Multiplies two numbers and returns a uint32 * @param a A number * @param b A number * @return a * b as a uint32 */ function mul32(uint256 a, uint256 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); require(c < 2**32); /* solcov ignore next */ return uint32(c); } /** * @dev Divides two numbers and returns a uint32 * @param a A number * @param b A number * @return a / b as a uint32 */ function div32(uint256 a, uint256 b) internal pure returns (uint32) { uint256 c = a / b; require(c < 2**32); /* solcov ignore next */ return uint32(c); } /** * @dev Substracts two numbers and returns a uint32 * @param a A number * @param b A number * @return a - b as a uint32 */ function sub32(uint256 a, uint256 b) internal pure returns (uint32) { require(b <= a); uint256 c = a - b; require(c < 2**32); /* solcov ignore next */ return uint32(c); } /** * @dev Adds two numbers and returns a uint32 * @param a A number * @param b A number * @return a + b as a uint32 */ function add32(uint256 a, uint256 b) internal pure returns (uint32) { uint256 c = a + b; require(c >= a && c < 2**32); return uint32(c); } /** * @dev Multiplies two numbers and returns a uint256 * @param a A number * @param b A number * @return a * b as a uint256 */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); /* solcov ignore next */ return c; } /** * @dev Divides two numbers and returns a uint256 * @param a A number * @param b A number * @return a / b as a uint256 */ function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; /* solcov ignore next */ return c; } /** * @dev Substracts two numbers and returns a uint256 * @param a A number * @param b A number * @return a - b as a uint256 */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } /** * @dev Adds two numbers and returns a uint256 * @param a A number * @param b A number * @return a + b as a uint256 */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title Merkle Tree's proof helper contract */ library Merkle { /** * @dev calculates the hash of two child nodes on the merkle tree. * @param a Hash of the left child node. * @param b Hash of the right child node. * @return sha3 hash of the resulting node. */ function combinedHash(bytes32 a, bytes32 b) public pure returns(bytes32) { return keccak256(abi.encodePacked(a, b)); } /** * @dev calculates a root hash associated with a Merkle proof * @param proof array of proof hashes * @param key index of the leaf element list. * this key indicates the specific position of the leaf * in the merkle tree. It will be used to know if the * node that will be hashed along with the proof node * is placed on the right or the left of the current * tree level. That is achieved by doing the modulo of * the current key/position. A new level of nodes will * be evaluated after that, and the new left or right * position is obtained by doing the same operation, * after dividing the key/position by two. * @param leaf the leaf element to verify on the set. * @return the hash of the Merkle proof. Should match the Merkle root * if the proof is valid */ function getProofRootHash(bytes32[] memory proof, uint256 key, bytes32 leaf) public pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked(leaf)); uint256 k = key; for(uint i = 0; i<proof.length; i++) { uint256 bit = k % 2; k = k / 2; if (bit == 0) hash = combinedHash(hash, proof[i]); else hash = combinedHash(proof[i], hash); } return hash; } } /** * @title Data Structures for BatPay: Accounts, Payments & Challenge */ contract Data { struct Account { address owner; uint64 balance; uint32 lastCollectedPaymentId; } struct BulkRegistration { bytes32 rootHash; uint32 recordCount; uint32 smallestRecordId; } struct Payment { uint32 fromAccountId; uint64 amount; uint64 fee; uint32 smallestAccountId; uint32 greatestAccountId; uint32 totalNumberOfPayees; uint64 lockTimeoutBlockNumber; bytes32 paymentDataHash; bytes32 lockingKeyHash; bytes32 metadata; } struct CollectSlot { uint32 minPayIndex; uint32 maxPayIndex; uint64 amount; uint64 delegateAmount; uint32 to; uint64 block; uint32 delegate; uint32 challenger; uint32 index; uint64 challengeAmount; uint8 status; address addr; bytes32 data; } struct Config { uint32 maxBulk; uint32 maxTransfer; uint32 challengeBlocks; uint32 challengeStepBlocks; uint64 collectStake; uint64 challengeStake; uint32 unlockBlocks; uint32 massExitIdBlocks; uint32 massExitIdStepBlocks; uint32 massExitBalanceBlocks; uint32 massExitBalanceStepBlocks; uint64 massExitStake; uint64 massExitChallengeStake; uint64 maxCollectAmount; } Config public params; address public owner; uint public constant MAX_ACCOUNT_ID = 2**32-1; // Maximum account id (32-bits) uint public constant NEW_ACCOUNT_FLAG = 2**256-1; // Request registration of new account uint public constant INSTANT_SLOT = 32768; } /** * @title Accounts, methods to manage accounts and balances */ contract Accounts is Data { event BulkRegister(uint bulkSize, uint smallestAccountId, uint bulkId ); event AccountRegistered(uint accountId, address accountAddress); IERC20 public token; Account[] public accounts; BulkRegistration[] public bulkRegistrations; /** * @dev determines whether accountId is valid * @param accountId an account id * @return boolean */ function isValidId(uint accountId) public view returns (bool) { return (accountId < accounts.length); } /** * @dev determines whether accountId is the owner of the account * @param accountId an account id * @return boolean */ function isAccountOwner(uint accountId) public view returns (bool) { return isValidId(accountId) && msg.sender == accounts[accountId].owner; } /** * @dev modifier to restrict that accountId is valid * @param accountId an account id */ modifier validId(uint accountId) { require(isValidId(accountId), "accountId is not valid"); _; } /** * @dev modifier to restrict that accountId is owner * @param accountId an account ID */ modifier onlyAccountOwner(uint accountId) { require(isAccountOwner(accountId), "Only account owner can invoke this method"); _; } /** * @dev Reserve accounts but delay assigning addresses. * Accounts will be claimed later using MerkleTree's rootHash. * @param bulkSize Number of accounts to reserve. * @param rootHash Hash of the root node of the Merkle Tree referencing the list of addresses. */ function bulkRegister(uint256 bulkSize, bytes32 rootHash) public { require(bulkSize > 0, "Bulk size can't be zero"); require(bulkSize < params.maxBulk, "Cannot register this number of ids simultaneously"); require(SafeMath.add(accounts.length, bulkSize) <= MAX_ACCOUNT_ID, "Cannot register: ran out of ids"); require(rootHash > 0, "Root hash can't be zero"); emit BulkRegister(bulkSize, accounts.length, bulkRegistrations.length); bulkRegistrations.push(BulkRegistration(rootHash, uint32(bulkSize), uint32(accounts.length))); accounts.length = SafeMath.add(accounts.length, bulkSize); } /** @dev Complete registration for a reserved account by showing the * bulkRegistration-id and Merkle proof associated with this address * @param addr Address claiming this account * @param proof Merkle proof for address and id * @param accountId Id of the account to be registered. * @param bulkId BulkRegistration id for the transaction reserving this account */ function claimBulkRegistrationId(address addr, bytes32[] memory proof, uint accountId, uint bulkId) public { require(bulkId < bulkRegistrations.length, "the bulkId referenced is invalid"); uint smallestAccountId = bulkRegistrations[bulkId].smallestRecordId; uint n = bulkRegistrations[bulkId].recordCount; bytes32 rootHash = bulkRegistrations[bulkId].rootHash; bytes32 hash = Merkle.getProofRootHash(proof, SafeMath.sub(accountId, smallestAccountId), bytes32(addr)); require(accountId >= smallestAccountId && accountId < smallestAccountId + n, "the accountId specified is not part of that bulk registration slot"); require(hash == rootHash, "invalid Merkle proof"); emit AccountRegistered(accountId, addr); accounts[accountId].owner = addr; } /** * @dev Register a new account * @return the id of the new account */ function register() public returns (uint32 ret) { require(accounts.length < MAX_ACCOUNT_ID, "no more accounts left"); ret = (uint32)(accounts.length); accounts.push(Account(msg.sender, 0, 0)); emit AccountRegistered(ret, msg.sender); return ret; } /** * @dev withdraw tokens from the BatchPayment contract into the original address. * @param amount Amount of tokens to withdraw. * @param accountId Id of the user requesting the withdraw. */ function withdraw(uint64 amount, uint256 accountId) external onlyAccountOwner(accountId) { uint64 balance = accounts[accountId].balance; require(balance >= amount, "insufficient funds"); require(amount > 0, "amount should be nonzero"); balanceSub(accountId, amount); require(token.transfer(msg.sender, amount), "transfer failed"); } /** * @dev Deposit tokens into the BatchPayment contract to enable scalable payments * @param amount Amount of tokens to deposit on `accountId`. User should have * enough balance and issue an `approve()` method prior to calling this. * @param accountId The id of the user account. In case `NEW_ACCOUNT_FLAG` is used, * a new account will be registered and the requested amount will be * deposited in a single operation. */ function deposit(uint64 amount, uint256 accountId) external { require(accountId < accounts.length || accountId == NEW_ACCOUNT_FLAG, "invalid accountId"); require(amount > 0, "amount should be positive"); if (accountId == NEW_ACCOUNT_FLAG) { // new account uint newId = register(); accounts[newId].balance = amount; } else { // existing account balanceAdd(accountId, amount); } require(token.transferFrom(msg.sender, address(this), amount), "transfer failed"); } /** * @dev Increase the specified account balance by `amount` tokens. * @param accountId An account id * @param amount number of tokens */ function balanceAdd(uint accountId, uint64 amount) internal validId(accountId) { accounts[accountId].balance = SafeMath.add64(accounts[accountId].balance, amount); } /** * @dev Substract `amount` tokens from the specified account's balance * @param accountId An account id * @param amount number of tokens */ function balanceSub(uint accountId, uint64 amount) internal validId(accountId) { uint64 balance = accounts[accountId].balance; require(balance >= amount, "not enough funds"); accounts[accountId].balance = SafeMath.sub64(balance, amount); } /** * @dev returns the balance associated with the account in tokens * @param accountId account requested. */ function balanceOf(uint accountId) external view validId(accountId) returns (uint64) { return accounts[accountId].balance; } /** * @dev gets number of accounts registered and reserved. * @return returns the size of the accounts array. */ function getAccountsLength() external view returns (uint) { return accounts.length; } /** * @dev gets the number of bulk registrations performed * @return the size of the bulkRegistrations array. */ function getBulkLength() external view returns (uint) { return bulkRegistrations.length; } } /** * @title Challenge helper library */ library Challenge { uint8 public constant PAY_DATA_HEADER_MARKER = 0xff; // marker in payData header /** * @dev Reverts if challenge period has expired or Collect Slot status is * not a valid one. */ modifier onlyValidCollectSlot(Data.CollectSlot storage collectSlot, uint8 validStatus) { require(!challengeHasExpired(collectSlot), "Challenge has expired"); require(isSlotStatusValid(collectSlot, validStatus), "Wrong Collect Slot status"); _; } /** * @return true if the current block number is greater or equal than the * allowed block for this challenge. */ function challengeHasExpired(Data.CollectSlot storage collectSlot) public view returns (bool) { return collectSlot.block <= block.number; } /** * @return true if the Slot status is valid. */ function isSlotStatusValid(Data.CollectSlot storage collectSlot, uint8 validStatus) public view returns (bool) { return collectSlot.status == validStatus; } /** @dev calculates new block numbers based on the current block and a * delta constant specified by the protocol policy. * @param delta number of blocks into the future to calculate. * @return future block number. */ function getFutureBlock(uint delta) public view returns(uint64) { return SafeMath.add64(block.number, delta); } /** * @dev Inspects the compact payment list provided and calculates the sum * of the amounts referenced * @param data binary array, with 12 bytes per item. 8-bytes amount, * 4-bytes payment index. * @return the sum of the amounts referenced on the array. */ function getDataSum(bytes memory data) public pure returns (uint sum) { require(data.length > 0, "no data provided"); require(data.length % 12 == 0, "wrong data format, data length should be multiple of 12"); uint n = SafeMath.div(data.length, 12); uint modulus = 2**64; sum = 0; // Get the sum of the stated amounts in data // Each entry in data is [8-bytes amount][4-bytes payIndex] for (uint i = 0; i < n; i++) { // solium-disable-next-line security/no-inline-assembly assembly { let amount := mod(mload(add(data, add(8, mul(i, 12)))), modulus) let result := add(sum, amount) switch or(gt(result, modulus), eq(result, modulus)) case 1 { revert (0, 0) } default { sum := result } } } } /** * @dev Helper function that obtains the amount/payIndex pair located at * position `index`. * @param data binary array, with 12 bytes per item. 8-bytes amount, * 4-bytes payment index. * @param index Array item requested. * @return amount and payIndex requested. */ function getDataAtIndex(bytes memory data, uint index) public pure returns (uint64 amount, uint32 payIndex) { require(data.length > 0, "no data provided"); require(data.length % 12 == 0, "wrong data format, data length should be multiple of 12"); uint mod1 = 2**64; uint mod2 = 2**32; uint i = SafeMath.mul(index, 12); require(i <= SafeMath.sub(data.length, 12), "index * 12 must be less or equal than (data.length - 12)"); // solium-disable-next-line security/no-inline-assembly assembly { amount := mod( mload(add(data, add(8, i))), mod1 ) payIndex := mod( mload(add(data, add(12, i))), mod2 ) } } /** * @dev obtains the number of bytes per id in `payData` * @param payData efficient binary representation of a list of accountIds * @return bytes per id in `payData` */ function getBytesPerId(bytes payData) internal pure returns (uint) { // payData includes a 2 byte header and a list of ids // [0xff][bytesPerId] uint len = payData.length; require(len >= 2, "payData length should be >= 2"); require(uint8(payData[0]) == PAY_DATA_HEADER_MARKER, "payData header missing"); uint bytesPerId = uint(payData[1]); require(bytesPerId > 0 && bytesPerId < 32, "second byte of payData should be positive and less than 32"); // remaining bytes should be a multiple of bytesPerId require((len - 2) % bytesPerId == 0, "payData length is invalid, all payees must have same amount of bytes (payData[1])"); return bytesPerId; } /** * @dev Process payData, inspecting the list of ids, accumulating the amount for * each entry of `id`. * `payData` includes 2 header bytes, followed by n bytesPerId-bytes entries. * `payData` format: [byte 0xff][byte bytesPerId][delta 0][delta 1]..[delta n-1] * @param payData List of payees of a specific Payment, with the above format. * @param id ID to look for in `payData` * @param amount amount per occurrence of `id` in `payData` * @return the amount sum for all occurrences of `id` in `payData` */ function getPayDataSum(bytes memory payData, uint id, uint amount) public pure returns (uint sum) { uint bytesPerId = getBytesPerId(payData); uint modulus = 1 << SafeMath.mul(bytesPerId, 8); uint currentId = 0; sum = 0; for (uint i = 2; i < payData.length; i += bytesPerId) { // Get next id delta from paydata // currentId += payData[2+i*bytesPerId] // solium-disable-next-line security/no-inline-assembly assembly { currentId := add( currentId, mod( mload(add(payData, add(i, bytesPerId))), modulus)) switch eq(currentId, id) case 1 { sum := add(sum, amount) } } } } /** * @dev calculates the number of accounts included in payData * @param payData efficient binary representation of a list of accountIds * @return number of accounts present */ function getPayDataCount(bytes payData) public pure returns (uint) { uint bytesPerId = getBytesPerId(payData); // calculate number of records return SafeMath.div(payData.length - 2, bytesPerId); } /** * @dev function. Phase I of the challenging game * @param collectSlot Collect slot * @param config Various parameters * @param accounts a reference to the main accounts array * @param challenger id of the challenger user */ function challenge_1( Data.CollectSlot storage collectSlot, Data.Config storage config, Data.Account[] storage accounts, uint32 challenger ) public onlyValidCollectSlot(collectSlot, 1) { require(accounts[challenger].balance >= config.challengeStake, "not enough balance"); collectSlot.status = 2; collectSlot.challenger = challenger; collectSlot.block = getFutureBlock(config.challengeStepBlocks); accounts[challenger].balance -= config.challengeStake; } /** * @dev Internal function. Phase II of the challenging game * @param collectSlot Collect slot * @param config Various parameters * @param data Binary array listing the payments in which the user was referenced. */ function challenge_2( Data.CollectSlot storage collectSlot, Data.Config storage config, bytes memory data ) public onlyValidCollectSlot(collectSlot, 2) { require(getDataSum(data) == collectSlot.amount, "data doesn't represent collected amount"); collectSlot.data = keccak256(data); collectSlot.status = 3; collectSlot.block = getFutureBlock(config.challengeStepBlocks); } /** * @dev Internal function. Phase III of the challenging game * @param collectSlot Collect slot * @param config Various parameters * @param data Binary array listing the payments in which the user was referenced. * @param disputedPaymentIndex index selecting the disputed payment */ function challenge_3( Data.CollectSlot storage collectSlot, Data.Config storage config, bytes memory data, uint32 disputedPaymentIndex ) public onlyValidCollectSlot(collectSlot, 3) { require(collectSlot.data == keccak256(data), "data mismatch, collected data hash doesn't match provided data hash"); (collectSlot.challengeAmount, collectSlot.index) = getDataAtIndex(data, disputedPaymentIndex); collectSlot.status = 4; collectSlot.block = getFutureBlock(config.challengeStepBlocks); } /** * @dev Internal function. Phase IV of the challenging game * @param collectSlot Collect slot * @param payments a reference to the BatPay payments array * @param payData binary data describing the list of account receiving * tokens on the selected transfer */ function challenge_4( Data.CollectSlot storage collectSlot, Data.Payment[] storage payments, bytes memory payData ) public onlyValidCollectSlot(collectSlot, 4) { require(collectSlot.index >= collectSlot.minPayIndex && collectSlot.index < collectSlot.maxPayIndex, "payment referenced is out of range"); Data.Payment memory p = payments[collectSlot.index]; require(keccak256(payData) == p.paymentDataHash, "payData mismatch, payment's data hash doesn't match provided payData hash"); require(p.lockingKeyHash == 0, "payment is locked"); uint collected = getPayDataSum(payData, collectSlot.to, p.amount); // Check if id is included in bulkRegistration within payment if (collectSlot.to >= p.smallestAccountId && collectSlot.to < p.greatestAccountId) { collected = SafeMath.add(collected, p.amount); } require(collected == collectSlot.challengeAmount, "amount mismatch, provided payData sum doesn't match collected challenge amount"); collectSlot.status = 5; } /** * @dev the challenge was completed successfully, or the delegate failed to respond on time. * The challenger will collect the stake. * @param collectSlot Collect slot * @param config Various parameters * @param accounts a reference to the main accounts array */ function challenge_success( Data.CollectSlot storage collectSlot, Data.Config storage config, Data.Account[] storage accounts ) public { require((collectSlot.status == 2 || collectSlot.status == 4), "Wrong Collect Slot status"); require(challengeHasExpired(collectSlot), "Challenge not yet finished"); accounts[collectSlot.challenger].balance = SafeMath.add64( accounts[collectSlot.challenger].balance, SafeMath.add64(config.collectStake, config.challengeStake)); collectSlot.status = 0; } /** * @dev Internal function. The delegate proved the challenger wrong, or * the challenger failed to respond on time. The delegae collects the stake. * @param collectSlot Collect slot * @param config Various parameters * @param accounts a reference to the main accounts array */ function challenge_failed( Data.CollectSlot storage collectSlot, Data.Config storage config, Data.Account[] storage accounts ) public { require(collectSlot.status == 5 || (collectSlot.status == 3 && block.number >= collectSlot.block), "challenge not completed"); // Challenge failed // delegate wins Stake accounts[collectSlot.delegate].balance = SafeMath.add64( accounts[collectSlot.delegate].balance, config.challengeStake); // reset slot to status=1, waiting for challenges collectSlot.challenger = 0; collectSlot.status = 1; collectSlot.block = getFutureBlock(config.challengeBlocks); } /** * @dev Helps verify a ECDSA signature, while recovering the signing address. * @param hash Hash of the signed message * @param sig binary representation of the r, s & v parameters. * @return address of the signer if data provided is valid, zero otherwise. */ function recoverHelper(bytes32 hash, bytes sig) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return address(0); } return ecrecover(prefixedHash, v, r, s); } } /** * @title Payments and Challenge game - Performs the operations associated with * transfer and the different steps of the collect challenge game. */ contract Payments is Accounts { event PaymentRegistered( uint32 indexed payIndex, uint indexed from, uint totalNumberOfPayees, uint amount ); event PaymentUnlocked(uint32 indexed payIndex, bytes key); event PaymentRefunded(uint32 beneficiaryAccountId, uint64 amountRefunded); /** * Event for collection logging. Off-chain monitoring services may listen * to this event to trigger challenges. */ event Collect( uint indexed delegate, uint indexed slot, uint indexed to, uint32 fromPayindex, uint32 toPayIndex, uint amount ); event Challenge1(uint indexed delegate, uint indexed slot, uint challenger); event Challenge2(uint indexed delegate, uint indexed slot); event Challenge3(uint indexed delegate, uint indexed slot, uint index); event Challenge4(uint indexed delegate, uint indexed slot); event ChallengeSuccess(uint indexed delegate, uint indexed slot); event ChallengeFailed(uint indexed delegate, uint indexed slot); Payment[] public payments; mapping (uint32 => mapping (uint32 => CollectSlot)) public collects; /** * @dev Register token payment to multiple recipients * @param fromId Account id for the originator of the transaction * @param amount Amount of tokens to pay each destination. * @param fee Fee in tokens to be payed to the party providing the unlocking service * @param payData Efficient representation of the destination account list * @param newCount Number of new destination accounts that will be reserved during the registerPayment transaction * @param rootHash Hash of the root hash of the Merkle tree listing the addresses reserved. * @param lockingKeyHash hash resulting of calculating the keccak256 of * of the key locking this payment to help in atomic data swaps. * This hash will later be used by the `unlock` function to unlock the payment we are registering. * The `lockingKeyHash` must be equal to the keccak256 of the packed * encoding of the unlockerAccountId and the key used by the unlocker to encrypt the traded data: * `keccak256(abi.encodePacked(unlockerAccountId, key))` * DO NOT use previously used locking keys, since an attacker could realize that by comparing key hashes * @param metadata Application specific data to be stored associated with the payment */ function registerPayment( uint32 fromId, uint64 amount, uint64 fee, bytes payData, uint newCount, bytes32 rootHash, bytes32 lockingKeyHash, bytes32 metadata ) external { require(payments.length < 2**32, "Cannot add more payments"); require(isAccountOwner(fromId), "Invalid fromId"); require(amount > 0, "Invalid amount"); require(newCount == 0 || rootHash > 0, "Invalid root hash"); // although bulkRegister checks this, we anticipate require(fee == 0 || lockingKeyHash > 0, "Invalid lock hash"); Payment memory p; // Prepare a Payment struct p.totalNumberOfPayees = SafeMath.add32(Challenge.getPayDataCount(payData), newCount); require(p.totalNumberOfPayees > 0, "Invalid number of payees, should at least be 1 payee"); require(p.totalNumberOfPayees < params.maxTransfer, "Too many payees, it should be less than config maxTransfer"); p.fromAccountId = fromId; p.amount = amount; p.fee = fee; p.lockingKeyHash = lockingKeyHash; p.metadata = metadata; p.smallestAccountId = uint32(accounts.length); p.greatestAccountId = SafeMath.add32(p.smallestAccountId, newCount); p.lockTimeoutBlockNumber = SafeMath.add64(block.number, params.unlockBlocks); p.paymentDataHash = keccak256(abi.encodePacked(payData)); // calculate total cost of payment uint64 totalCost = SafeMath.mul64(amount, p.totalNumberOfPayees); totalCost = SafeMath.add64(totalCost, fee); // Check that fromId has enough balance and substract totalCost balanceSub(fromId, totalCost); // If this operation includes new accounts, do a bulkRegister if (newCount > 0) { bulkRegister(newCount, rootHash); } // Save the new Payment payments.push(p); emit PaymentRegistered(SafeMath.sub32(payments.length, 1), p.fromAccountId, p.totalNumberOfPayees, p.amount); } /** * @dev provide the required key, releasing the payment and enabling the buyer decryption the digital content. * @param payIndex payment Index associated with the registerPayment operation. * @param unlockerAccountId id of the party providing the unlocking service. Fees wil be payed to this id. * @param key Cryptographic key used to encrypt traded data. */ function unlock(uint32 payIndex, uint32 unlockerAccountId, bytes memory key) public returns(bool) { require(payIndex < payments.length, "invalid payIndex, payments is not that long yet"); require(isValidId(unlockerAccountId), "Invalid unlockerAccountId"); require(block.number < payments[payIndex].lockTimeoutBlockNumber, "Hash lock expired"); bytes32 h = keccak256(abi.encodePacked(unlockerAccountId, key)); require(h == payments[payIndex].lockingKeyHash, "Invalid key"); payments[payIndex].lockingKeyHash = bytes32(0); balanceAdd(unlockerAccountId, payments[payIndex].fee); emit PaymentUnlocked(payIndex, key); return true; } /** * @dev Enables the buyer to recover funds associated with a `registerPayment()` * operation for which decryption keys were not provided. * @param payIndex Index of the payment transaction associated with this request. * @return true if the operation succeded. */ function refundLockedPayment(uint32 payIndex) external returns (bool) { require(payIndex < payments.length, "invalid payIndex, payments is not that long yet"); require(payments[payIndex].lockingKeyHash != 0, "payment is already unlocked"); require(block.number >= payments[payIndex].lockTimeoutBlockNumber, "Hash lock has not expired yet"); Payment memory payment = payments[payIndex]; require(payment.totalNumberOfPayees > 0, "payment already refunded"); uint64 total = SafeMath.add64( SafeMath.mul64(payment.totalNumberOfPayees, payment.amount), payment.fee ); payment.totalNumberOfPayees = 0; payment.fee = 0; payment.amount = 0; payments[payIndex] = payment; // Complete refund balanceAdd(payment.fromAccountId, total); emit PaymentRefunded(payment.fromAccountId, total); return true; } /** * @dev let users claim pending balance associated with prior transactions Users ask a delegate to complete the transaction on their behalf, the delegate calculates the apropiate amount (declaredAmount) and waits for a possible challenger. If this is an instant collect, tokens are transfered immediatly. * @param delegate id of the delegate account performing the operation on the name of the user. * @param slotId Individual slot used for the challenge game. * @param toAccountId Destination of the collect operation. * @param maxPayIndex payIndex of the first payment index not covered by this application. * @param declaredAmount amount of tokens owed to this user account * @param fee fee in tokens to be paid for the end user help. * @param destination Address to withdraw the full account balance. * @param signature An R,S,V ECDS signature provided by a user. */ function collect( uint32 delegate, uint32 slotId, uint32 toAccountId, uint32 maxPayIndex, uint64 declaredAmount, uint64 fee, address destination, bytes memory signature ) public { // Check delegate and toAccountId are valid require(isAccountOwner(delegate), "invalid delegate"); require(isValidId(toAccountId), "toAccountId must be a valid account id"); // make sure the game slot is empty (release it if necessary) freeSlot(delegate, slotId); Account memory tacc = accounts[toAccountId]; require(tacc.owner != 0, "account registration has to be completed"); if (delegate != toAccountId) { // If "toAccountId" != delegate, check who signed this transaction bytes32 hash = keccak256( abi.encodePacked( address(this), delegate, toAccountId, tacc.lastCollectedPaymentId, maxPayIndex, declaredAmount, fee, destination )); require(Challenge.recoverHelper(hash, signature) == tacc.owner, "Bad user signature"); } // Check maxPayIndex is valid require(maxPayIndex > 0 && maxPayIndex <= payments.length, "invalid maxPayIndex, payments is not that long yet"); require(maxPayIndex > tacc.lastCollectedPaymentId, "account already collected payments up to maxPayIndex"); require(payments[maxPayIndex - 1].lockTimeoutBlockNumber < block.number, "cannot collect payments that can be unlocked"); // Check if declaredAmount and fee are valid require(declaredAmount <= params.maxCollectAmount, "declaredAmount is too big"); require(fee <= declaredAmount, "fee is too big, should be smaller than declaredAmount"); // Prepare the challenge slot CollectSlot storage sl = collects[delegate][slotId]; sl.delegate = delegate; sl.minPayIndex = tacc.lastCollectedPaymentId; sl.maxPayIndex = maxPayIndex; sl.amount = declaredAmount; sl.to = toAccountId; sl.block = Challenge.getFutureBlock(params.challengeBlocks); sl.status = 1; // Calculate how many tokens needs the delegate, and setup delegateAmount and addr uint64 needed = params.collectStake; // check if this is an instant collect if (slotId >= INSTANT_SLOT) { uint64 declaredAmountLessFee = SafeMath.sub64(declaredAmount, fee); sl.delegateAmount = declaredAmount; needed = SafeMath.add64(needed, declaredAmountLessFee); sl.addr = address(0); // Instant-collect, toAccount gets the declaredAmount now balanceAdd(toAccountId, declaredAmountLessFee); } else { // not instant-collect sl.delegateAmount = fee; sl.addr = destination; } // Check delegate has enough funds require(accounts[delegate].balance >= needed, "not enough funds"); // Update the lastCollectPaymentId for the toAccount accounts[toAccountId].lastCollectedPaymentId = uint32(maxPayIndex); // Now the delegate Pays balanceSub(delegate, needed); // Proceed if the user is withdrawing its balance if (destination != address(0) && slotId >= INSTANT_SLOT) { uint64 toWithdraw = accounts[toAccountId].balance; accounts[toAccountId].balance = 0; require(token.transfer(destination, toWithdraw), "transfer failed"); } emit Collect(delegate, slotId, toAccountId, tacc.lastCollectedPaymentId, maxPayIndex, declaredAmount); } /** * @dev gets the number of payments issued * @return returns the size of the payments array. */ function getPaymentsLength() external view returns (uint) { return payments.length; } /** * @dev initiate a challenge game * @param delegate id of the delegate that performed the collect operation * in the name of the end-user. * @param slot slot used for the challenge game. Every user has a sperate * set of slots * @param challenger id of the user account challenging the delegate. */ function challenge_1( uint32 delegate, uint32 slot, uint32 challenger ) public validId(delegate) onlyAccountOwner(challenger) { Challenge.challenge_1(collects[delegate][slot], params, accounts, challenger); emit Challenge1(delegate, slot, challenger); } /** * @dev The delegate provides the list of payments that mentions the enduser * @param delegate id of the delegate performing the collect operation * @param slot slot used for the operation * @param data binary list of payment indexes associated with this collect operation. */ function challenge_2( uint32 delegate, uint32 slot, bytes memory data ) public onlyAccountOwner(delegate) { Challenge.challenge_2(collects[delegate][slot], params, data); emit Challenge2(delegate, slot); } /** * @dev the Challenger chooses a single index into the delegate provided data list * @param delegate id of the delegate performing the collect operation * @param slot slot used for the operation * @param data binary list of payment indexes associated with this collect operation. * @param index index into the data array for the payment id selected by the challenger */ function challenge_3( uint32 delegate, uint32 slot, bytes memory data, uint32 index ) public validId(delegate) { require(isAccountOwner(collects[delegate][slot].challenger), "only challenger can call challenge_2"); Challenge.challenge_3(collects[delegate][slot], params, data, index); emit Challenge3(delegate, slot, index); } /** * @dev the delegate provides proof that the destination account was * included on that payment, winning the game * @param delegate id of the delegate performing the collect operation * @param slot slot used for the operation */ function challenge_4( uint32 delegate, uint32 slot, bytes memory payData ) public onlyAccountOwner(delegate) { Challenge.challenge_4( collects[delegate][slot], payments, payData ); emit Challenge4(delegate, slot); } /** * @dev the challenge was completed successfully. The delegate stake is slashed. * @param delegate id of the delegate performing the collect operation * @param slot slot used for the operation */ function challenge_success( uint32 delegate, uint32 slot ) public validId(delegate) { Challenge.challenge_success(collects[delegate][slot], params, accounts); emit ChallengeSuccess(delegate, slot); } /** * @dev The delegate won the challenge game. He gets the challenge stake. * @param delegate id of the delegate performing the collect operation * @param slot slot used for the operation */ function challenge_failed( uint32 delegate, uint32 slot ) public onlyAccountOwner(delegate) { Challenge.challenge_failed(collects[delegate][slot], params, accounts); emit ChallengeFailed(delegate, slot); } /** * @dev Releases a slot used by the collect channel game, only when the game is finished. * This does three things: * 1. Empty the slot * 2. Pay the delegate * 3. Pay the destinationAccount * Also, if a token.transfer was requested, transfer the outstanding balance to the specified address. * @param delegate id of the account requesting the release operation * @param slot id of the slot requested for the duration of the challenge game */ function freeSlot(uint32 delegate, uint32 slot) public { CollectSlot memory s = collects[delegate][slot]; // If this is slot is empty, nothing else to do here. if (s.status == 0) return; // Make sure this slot is ready to be freed. // It should be in the waiting state(1) and with challenge time ran-out require(s.status == 1, "slot not available"); require(block.number >= s.block, "slot not available"); // 1. Put the slot in the empty state collects[delegate][slot].status = 0; // 2. Pay the delegate // This includes the stake as well as fees and other tokens reserved during collect() // [delegateAmount + stake] => delegate balanceAdd(delegate, SafeMath.add64(s.delegateAmount, params.collectStake)); // 3. Pay the destination account // [amount - delegateAmount] => to uint64 balance = SafeMath.sub64(s.amount, s.delegateAmount); // was a transfer requested? if (s.addr != address(0)) { // empty the account balance balance = SafeMath.add64(balance, accounts[s.to].balance); accounts[s.to].balance = 0; if (balance != 0) require(token.transfer(s.addr, balance), "transfer failed"); } else { balanceAdd(s.to, balance); } } } /** * @title BatchPayment processing * @notice This contract allows to scale ERC-20 token transfer for fees or * micropayments on the few-buyers / many-sellers setting. */ contract BatPay is Payments { /** * @dev Contract constructor, sets ERC20 token this contract will use for payments * @param token_ ERC20 contract address * @param maxBulk Maximum number of users to register in a single bulkRegister * @param maxTransfer Maximum number of destinations on a single payment * @param challengeBlocks number of blocks to wait for a challenge * @param challengeStepBlocks number of blocks to wait for a single step on * the challenge game * @param collectStake stake in tokens for a collect operation * @param challengeStake stake in tokens for the challenger of a collect operation * @param unlockBlocks number of blocks to wait after registering payment * for an unlock operation * @param maxCollectAmount Maximum amount of tokens to be collected in a * single transaction */ constructor( IERC20 token_, uint32 maxBulk, uint32 maxTransfer, uint32 challengeBlocks, uint32 challengeStepBlocks, uint64 collectStake, uint64 challengeStake, uint32 unlockBlocks, uint64 maxCollectAmount ) public { require(token_ != address(0), "Token address can't be zero"); require(maxBulk > 0, "Parameter maxBulk can't be zero"); require(maxTransfer > 0, "Parameter maxTransfer can't be zero"); require(challengeBlocks > 0, "Parameter challengeBlocks can't be zero"); require(challengeStepBlocks > 0, "Parameter challengeStepBlocks can't be zero"); require(collectStake > 0, "Parameter collectStake can't be zero"); require(challengeStake > 0, "Parameter challengeStake can't be zero"); require(unlockBlocks > 0, "Parameter unlockBlocks can't be zero"); require(maxCollectAmount > 0, "Parameter maxCollectAmount can't be zero"); owner = msg.sender; token = IERC20(token_); params.maxBulk = maxBulk; params.maxTransfer = maxTransfer; params.challengeBlocks = challengeBlocks; params.challengeStepBlocks = challengeStepBlocks; params.collectStake = collectStake; params.challengeStake = challengeStake; params.unlockBlocks = unlockBlocks; params.maxCollectAmount = maxCollectAmount; } }
* @dev Helps verify a ECDSA signature, while recovering the signing address. @param hash Hash of the signed message @param sig binary representation of the r, s & v parameters. @return address of the signer if data provided is valid, zero otherwise./ Check the signature length Divide the signature in r, s and v variables ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. solium-disable-next-line security/no-inline-assembly Version of signature should be 27 or 28, but 0 and 1 are also possible versions If the version is correct return the signer address
function recoverHelper(bytes32 hash, bytes sig) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) { return (address(0)); } assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return address(0); } return ecrecover(prefixedHash, v, r, s); }
5,496,451
[ 1, 44, 292, 1121, 3929, 279, 7773, 19748, 3372, 16, 1323, 5910, 310, 326, 10611, 1758, 18, 225, 1651, 2474, 434, 326, 6726, 883, 225, 3553, 3112, 4335, 434, 326, 436, 16, 272, 473, 331, 1472, 18, 327, 1758, 434, 326, 10363, 309, 501, 2112, 353, 923, 16, 3634, 3541, 18, 19, 2073, 326, 3372, 769, 21411, 831, 326, 3372, 316, 436, 16, 272, 471, 331, 3152, 425, 1793, 3165, 5530, 326, 3372, 1472, 16, 471, 326, 1338, 4031, 358, 336, 2182, 4551, 353, 358, 999, 19931, 18, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 4049, 434, 3372, 1410, 506, 12732, 578, 9131, 16, 1496, 374, 471, 404, 854, 2546, 3323, 5244, 971, 326, 1177, 353, 3434, 327, 326, 10363, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 2276, 12, 3890, 1578, 1651, 16, 1731, 3553, 13, 1071, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 1731, 3778, 1633, 273, 1548, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 14432, 203, 3639, 1731, 1578, 12829, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3239, 16, 1651, 10019, 203, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 203, 3639, 309, 261, 7340, 18, 2469, 480, 15892, 13, 288, 203, 5411, 327, 261, 2867, 12, 20, 10019, 203, 3639, 289, 203, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 12, 7340, 16, 3847, 3719, 203, 5411, 272, 519, 312, 945, 12, 1289, 12, 7340, 16, 5178, 3719, 203, 5411, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 7340, 16, 19332, 20349, 203, 3639, 289, 203, 203, 3639, 309, 261, 90, 411, 12732, 13, 288, 203, 5411, 331, 1011, 12732, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 90, 480, 12732, 597, 331, 480, 9131, 13, 288, 203, 5411, 327, 1758, 12, 20, 1769, 203, 3639, 289, 203, 203, 3639, 327, 425, 1793, 3165, 12, 3239, 329, 2310, 16, 331, 16, 436, 16, 272, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x617332a777780F546261247F621051d0b98975Eb/sources/src/contracts/voting/VotingMachine.sol
@inheritdoc IVotingMachine
function updateGasLimit(uint256 gasLimit) external onlyOwner { _updateGasLimit(gasLimit); }
4,928,864
[ 1, 36, 10093, 21602, 17128, 6981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 27998, 3039, 12, 11890, 5034, 16189, 3039, 13, 3903, 1338, 5541, 288, 203, 565, 389, 2725, 27998, 3039, 12, 31604, 3039, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TradingAction.sol"; import "./ActionGuards.sol"; import "./nTokenMintAction.sol"; import "./nTokenRedeemAction.sol"; import "../SettleAssetsExternal.sol"; import "../FreeCollateralExternal.sol"; import "../../math/SafeInt256.sol"; import "../../global/StorageLayoutV1.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/AccountContextHandler.sol"; import "../../../interfaces/notional/NotionalCallback.sol"; contract BatchAction is StorageLayoutV1, ActionGuards { using BalanceHandler for BalanceState; using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using SafeInt256 for int256; /// @notice Executes a batch of balance transfers including minting and redeeming nTokens. /// @param account the account for the action /// @param actions array of balance actions to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); // Return any settle amounts here to reduce the number of storage writes to balances AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; for (uint256 i = 0; i < actions.length; i++) { BalanceAction calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions /// @param account the account for the action /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This /// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform /// other actions on behalf of the user. /// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract /// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM /// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting /// and will mainly be used for contracts that make migrating assets a better user experience. /// @param account the account that will take all the actions /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @param callbackData arbitrary bytes to be passed backed to the caller in the callback /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:authorizedCallbackContract function batchBalanceAndTradeActionWithCallback( address account, BalanceActionWithTrades[] calldata actions, bytes calldata callbackData ) external payable { // NOTE: Re-entrancy is allowed for authorized callback functions. require(authorizedCallbackContract[msg.sender], "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); accountContext.setAccountContext(account); // Be sure to set the account context before initiating the callback, all stateful updates // have been finalized at this point so we are safe to issue a callback. This callback may // re-enter Notional safely to deposit or take other actions. NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData); if (accountContext.hasDebt != 0x00) { // NOTE: this method may update the account context to turn off the hasDebt flag, this // is ok because the worst case would be causing an extra free collateral check when it // is not required. This check will be entered if the account hasDebt prior to the callback // being triggered above, so it will happen regardless of what the callback function does. FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } function _batchBalanceAndTradeAction( address account, BalanceActionWithTrades[] calldata actions ) internal returns (AccountContext memory) { AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; // NOTE: loading the portfolio state must happen after settle account to get the // correct portfolio, it will have changed if the account is settled. PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); for (uint256 i = 0; i < actions.length; i++) { BalanceActionWithTrades calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); // Does not revert on invalid action types here, they also have no effect. _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); if (action.trades.length > 0) { int256 netCash; if (accountContext.isBitmapEnabled()) { require( accountContext.bitmapCurrencyId == action.currencyId, "Invalid trades for account" ); bool didIncurDebt; (netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, action.trades ); if (didIncurDebt) { accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt; } } else { // NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch // because we want to only write to storage once after all trades are completed (portfolioState, netCash) = TradingAction.executeTradesArrayBatch( account, action.currencyId, portfolioState, action.trades ); } // If the account owes cash after trading, ensure that it has enough if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg()); balanceState.netCashChange = balanceState.netCashChange.add(netCash); } _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } // Update the portfolio state if bitmap is not enabled. If bitmap is already enabled // then all the assets have already been updated in in storage. if (!accountContext.isBitmapEnabled()) { // NOTE: account context is updated in memory inside this method call. accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } // NOTE: free collateral and account context will be set outside of this method call. return accountContext; } /// @dev Executes deposits function _executeDepositAction( address account, BalanceState memory balanceState, DepositActionType depositType, uint256 depositActionAmount_ ) private { int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_); int256 assetInternalAmount; require(depositActionAmount >= 0); if (depositType == DepositActionType.None) { return; } else if ( depositType == DepositActionType.DepositAsset || depositType == DepositActionType.DepositAssetAndMintNToken ) { // NOTE: this deposit will NOT revert on a failed transfer unless there is a // transfer fee. The actual transfer will take effect later in balanceState.finalize assetInternalAmount = balanceState.depositAssetToken( account, depositActionAmount, false // no force transfer ); } else if ( depositType == DepositActionType.DepositUnderlying || depositType == DepositActionType.DepositUnderlyingAndMintNToken ) { // NOTE: this deposit will revert on a failed transfer immediately assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount); } else if (depositType == DepositActionType.ConvertCashToNToken) { // _executeNTokenAction will check if the account has sufficient cash assetInternalAmount = depositActionAmount; } _executeNTokenAction( balanceState, depositType, depositActionAmount, assetInternalAmount ); } /// @dev Executes nToken actions function _executeNTokenAction( BalanceState memory balanceState, DepositActionType depositType, int256 depositActionAmount, int256 assetInternalAmount ) private { // After deposits have occurred, check if we are minting nTokens if ( depositType == DepositActionType.DepositAssetAndMintNToken || depositType == DepositActionType.DepositUnderlyingAndMintNToken || depositType == DepositActionType.ConvertCashToNToken ) { // Will revert if trying to mint ntokens and results in a negative cash balance _checkSufficientCash(balanceState, assetInternalAmount); balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount); // Converts a given amount of cash (denominated in internal precision) into nTokens int256 tokensMinted = nTokenMintAction.nTokenMint( balanceState.currencyId, assetInternalAmount ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add( tokensMinted ); } else if (depositType == DepositActionType.RedeemNToken) { require( // prettier-ignore balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) // transfers would not occur at this point .add(balanceState.netNTokenSupplyChange) >= depositActionAmount, "Insufficient token balance" ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub( depositActionAmount ); int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch( balanceState.currencyId, depositActionAmount ); balanceState.netCashChange = balanceState.netCashChange.add(assetCash); } } /// @dev Calculations any withdraws and finalizes balances function _calculateWithdrawActionAndFinalize( address account, AccountContext memory accountContext, BalanceState memory balanceState, uint256 withdrawAmountInternalPrecision, bool withdrawEntireCashBalance, bool redeemToUnderlying ) private { int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision); require(withdrawAmount >= 0); // dev: withdraw action overflow // NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input if (withdrawEntireCashBalance) { // This option is here so that accounts do not end up with dust after lending since we generally // cannot calculate exact cash amounts from the liquidity curve. withdrawAmount = balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision); // If the account has a negative cash balance then cannot withdraw if (withdrawAmount < 0) withdrawAmount = 0; } // prettier-ignore balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .sub(withdrawAmount); balanceState.finalize(account, accountContext, redeemToUnderlying); } function _finalizeAccountContext(address account, AccountContext memory accountContext) private { // At this point all balances, market states and portfolio states should be finalized. Just need to check free // collateral if required. accountContext.setAccountContext(account); if (accountContext.hasDebt != 0x00) { FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } /// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance /// to do so. function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision) private pure { // The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision require( amountInternalPrecision >= 0 && balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision, "Insufficient cash" ); } function _settleAccountIfRequired(address account) private returns (AccountContext memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { // Returns a new memory reference to account context return SettleAssetsExternal.settleAccount(account, accountContext); } else { return accountContext; } } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address, address, address, address, address) { return ( address(FreeCollateralExternal), address(MigrateIncentives), address(SettleAssetsExternal), address(TradingAction), address(nTokenMintAction), address(nTokenRedeemAction) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../FreeCollateralExternal.sol"; import "../SettleAssetsExternal.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library TradingAction { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using Market for MarketParameters; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; using SafeInt256 for int256; using SafeMath for uint256; event LendBorrowTrade( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash ); event AddRemoveLiquidity( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash, int256 netLiquidityTokens ); event SettledCashDebt( address indexed settledAccount, uint16 indexed currencyId, address indexed settler, int256 amountToSettleAsset, int256 fCashAmount ); event nTokenResidualPurchase( uint16 indexed currencyId, uint40 indexed maturity, address indexed purchaser, int256 fCashAmountToPurchase, int256 netAssetCashNToken ); /// @dev Used internally to manage stack issues struct TradeContext { int256 cash; int256 fCashAmount; int256 fee; int256 netCash; int256 totalFee; uint256 blockTime; } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param bitmapCurrencyId currency id of the bitmap /// @param nextSettleTime used to calculate the relative positions in the bitmap /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return netCash generated by trading /// @return didIncurDebt if the bitmap had an fCash position go negative function executeTradesBitmapBatch( address account, uint16 bitmapCurrencyId, uint40 nextSettleTime, bytes32[] calldata trades ) external returns (int256, bool) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId); MarketParameters memory market; bool didIncurDebt; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); c.fCashAmount = BitmapAssetsHandler.addifCashAsset( account, bitmapCurrencyId, maturity, nextSettleTime, c.fCashAmount ); didIncurDebt = didIncurDebt || (c.fCashAmount < 0); c.netCash = c.netCash.add(c.cash); } return (c.netCash, didIncurDebt); } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param currencyId currency id to trade /// @param portfolioState used to update the positions in the portfolio /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return resulting portfolio state /// @return netCash generated by trading function executeTradesArrayBatch( address account, uint16 currencyId, PortfolioState memory portfolioState, bytes32[] calldata trades ) external returns (PortfolioState memory, int256) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId); MarketParameters memory market; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i])))); if ( tradeType == TradeActionType.AddLiquidity || tradeType == TradeActionType.RemoveLiquidity ) { revert("Disabled"); /** * Manual adding and removing of liquidity is currently disabled. * * // Liquidity tokens can only be added by array portfolio * c.cash = _executeLiquidityTrade( * account, * cashGroup, * market, * tradeType, * trades[i], * portfolioState, * c.netCash * ); */ } else { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); portfolioState.addAsset( currencyId, maturity, Constants.FCASH_ASSET_TYPE, c.fCashAmount ); } c.netCash = c.netCash.add(c.cash); } return (portfolioState, c.netCash); } /// @notice Executes a non-liquidity token trade /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param trade bytes32 encoding of the particular trade /// @param blockTime the current block time /// @return maturity of the asset that was traded /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, bytes32 trade, uint256 blockTime ) private returns ( uint256 maturity, int256 cashAmount, int256 fCashAmount ) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade)))); if (tradeType == TradeActionType.PurchaseNTokenResidual) { (maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual( account, cashGroup, blockTime, trade ); } else if (tradeType == TradeActionType.SettleCashDebt) { (maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade); } else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) { (cashAmount, fCashAmount) = _executeLendBorrowTrade( cashGroup, market, tradeType, blockTime, trade ); // This is a little ugly but required to deal with stack issues. We know the market is loaded // with the proper maturity inside _executeLendBorrowTrade maturity = market.maturity; emit LendBorrowTrade( account, uint16(cashGroup.currencyId), uint40(maturity), cashAmount, fCashAmount ); } else { revert("Invalid trade type"); } } /// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold /// liquidity tokens. /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param trade bytes32 encoding of the particular trade /// @param portfolioState the current account's portfolio state /// @param netCash the current net cash accrued in this batch of trades, can be // used for adding liquidity /// @return cashAmount: a positive or negative cash amount accrued to the account function _executeLiquidityTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, bytes32 trade, PortfolioState memory portfolioState, int256 netCash ) private returns (int256) { uint256 marketIndex = uint8(bytes1(trade << 8)); // NOTE: this loads the market in memory cashGroup.loadMarket(market, marketIndex, true, block.timestamp); int256 cashAmount; int256 fCashAmount; int256 tokens; if (tradeType == TradeActionType.AddLiquidity) { cashAmount = int256((uint256(trade) >> 152) & type(uint88).max); // Setting cash amount to zero will deposit all net cash accumulated in this trade into // liquidity. This feature allows accounts to borrow in one maturity to provide liquidity // in another in a single transaction without dust. It also allows liquidity providers to // sell off the net cash residuals and use the cash amount in the new market without dust if (cashAmount == 0) cashAmount = netCash; // Add liquidity will check cash amount is positive (tokens, fCashAmount) = market.addLiquidity(cashAmount); cashAmount = cashAmount.neg(); // Report a negative cash amount in the event } else { tokens = int256((uint256(trade) >> 152) & type(uint88).max); (cashAmount, fCashAmount) = market.removeLiquidity(tokens); tokens = tokens.neg(); // Report a negative amount tokens in the event } { uint256 minImpliedRate = uint32(uint256(trade) >> 120); uint256 maxImpliedRate = uint32(uint256(trade) >> 88); // If minImpliedRate is not set then it will be zero require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage"); if (maxImpliedRate != 0) require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage"); } // Add the assets in this order so they are sorted portfolioState.addAsset( cashGroup.currencyId, market.maturity, Constants.FCASH_ASSET_TYPE, fCashAmount ); // Adds the liquidity token asset portfolioState.addAsset( cashGroup.currencyId, market.maturity, marketIndex + 1, tokens ); emit AddRemoveLiquidity( account, cashGroup.currencyId, // This will not overflow for a long time uint40(market.maturity), cashAmount, fCashAmount, tokens ); return cashAmount; } /// @notice Executes a lend or borrow trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeLendBorrowTrade( CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, uint256 blockTime, bytes32 trade ) private returns ( int256 cashAmount, int256 fCashAmount ) { uint256 marketIndex = uint256(uint8(bytes1(trade << 8))); // NOTE: this updates the market in memory cashGroup.loadMarket(market, marketIndex, false, blockTime); fCashAmount = int256(uint88(bytes11(trade << 16))); // fCash to account will be negative here if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg(); cashAmount = market.executeTrade( cashGroup, fCashAmount, market.maturity.sub(blockTime), marketIndex ); require(cashAmount != 0, "Trade failed, liquidity"); uint256 rateLimit = uint256(uint32(bytes4(trade << 104))); if (rateLimit != 0) { if (tradeType == TradeActionType.Borrow) { // Do not allow borrows over the rate limit require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage"); } else { // Do not allow lends under the rate limit require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage"); } } } /// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty /// rate to the 3 month market. /// @param account the account initiating the trade, used to check that self settlement is not possible /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the three month maturity where fCash will be exchanged /// @return cashAmount: a negative cash amount that the account must pay to the settled account /// @return fCashAmount: a positive fCash amount that the account will receive function _settleCashDebt( address account, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { address counterparty = address(uint256(trade) >> 88); // Allowing an account to settle itself would result in strange outcomes require(account != counterparty, "Cannot settle self"); int256 amountToSettleAsset = int256(uint88(uint256(trade))); AccountContext memory counterpartyContext = AccountContextHandler.getAccountContext(counterparty); if (counterpartyContext.mustSettleAssets()) { counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext); } // This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive // number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the // max amount to settle. This will update the balance storage on the counterparty. amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt( counterparty, cashGroup, amountToSettleAsset, counterpartyContext ); // Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market // is not initialized. uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; int256 fCashAmount = _getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset); // Defensive check to ensure that we can't inadvertently cause the settler to lose fCash. require(fCashAmount >= 0); // It's possible that this action will put an account into negative free collateral. In this case they // will immediately become eligible for liquidation and the account settling the debt can also liquidate // them in the same transaction. Do not run a free collateral check here to allow this to happen. { PortfolioAsset[] memory assets = new PortfolioAsset[](1); assets[0].currencyId = cashGroup.currencyId; assets[0].maturity = threeMonthMaturity; assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur assets[0].assetType = Constants.FCASH_ASSET_TYPE; // Can transfer assets, we have settled above counterpartyContext = TransferAssets.placeAssetsInAccount( counterparty, counterpartyContext, assets ); } counterpartyContext.setAccountContext(counterparty); emit SettledCashDebt( counterparty, uint16(cashGroup.currencyId), account, amountToSettleAsset, fCashAmount.neg() ); return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount); } /// @dev Helper method to calculate the fCashAmount from the penalty settlement rate function _getfCashSettleAmount( CashGroupParameters memory cashGroup, uint256 threeMonthMaturity, uint256 blockTime, int256 amountToSettleAsset ) private view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime); int256 exchangeRate = Market.getExchangeRateFromImpliedRate( oracleRate.add(cashGroup.getSettlementPenalty()), threeMonthMaturity.sub(blockTime) ); // Amount to settle is positive, this returns the fCashAmount that the settler will // receive as a positive number return cashGroup.assetRate .convertToUnderlying(amountToSettleAsset) // Exchange rate converts from cash to fCash when multiplying .mulInRatePrecision(exchangeRate); } /// @notice Allows an account to purchase ntoken residuals /// @param purchaser account that is purchasing the residuals /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged /// @return cashAmount: a positive or negative cash amount that the account will receive or pay /// @return fCashAmount: a positive or negative fCash amount that the account will receive function _purchaseNTokenResidual( address purchaser, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { uint256 maturity = uint256(uint32(uint256(trade) >> 216)); int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128)); require(maturity > blockTime, "Invalid maturity"); // Require that the residual to purchase does not fall on an existing maturity (i.e. // it is an idiosyncratic maturity) require( !DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime), "Non idiosyncratic maturity" ); address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, /* assetArrayLength */, bytes5 parameters ) = nTokenHandler.getNTokenContext(nTokenAddress); // Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage // opportunities are not available (by generating residuals and then immediately purchasing them at a discount) // This is always relative to the last initialized time which is set at utc0 when initialized, not the // reference time. Therefore we will always restrict residual purchase relative to initialization, not reference. // This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization // until the residual time buffer passes. require( blockTime > lastInitializedTime.add( uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours ), "Insufficient block time" ); int256 notional = BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity); // Check if amounts are valid and set them to the max available if necessary if (notional < 0 && fCashAmountToPurchase < 0) { // Does not allow purchasing more negative notional than available if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional; } else if (notional > 0 && fCashAmountToPurchase > 0) { // Does not allow purchasing more positive notional than available if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional; } else { // Does not allow moving notional in the opposite direction revert("Invalid amount"); } // If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return // netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken. int256 netAssetCashNToken = _getResidualPriceAssetCash( cashGroup, maturity, blockTime, fCashAmountToPurchase, parameters ); _updateNTokenPortfolio( nTokenAddress, cashGroup.currencyId, maturity, lastInitializedTime, fCashAmountToPurchase, netAssetCashNToken ); emit nTokenResidualPurchase( uint16(cashGroup.currencyId), uint40(maturity), purchaser, fCashAmountToPurchase, netAssetCashNToken ); return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase); } /// @notice Returns the amount of asset cash required to purchase the nToken residual function _getResidualPriceAssetCash( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime, int256 fCashAmount, bytes6 parameters ) internal view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); // Residual purchase incentive is specified in ten basis point increments uint256 purchaseIncentive = uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) * Constants.TEN_BASIS_POINTS; if (fCashAmount > 0) { // When fCash is positive then we add the purchase incentive, the purchaser // can pay less cash for the fCash relative to the oracle rate oracleRate = oracleRate.add(purchaseIncentive); } else if (oracleRate > purchaseIncentive) { // When fCash is negative, we reduce the interest rate that the purchaser will // borrow at, we do this check to ensure that we floor the oracle rate at zero. oracleRate = oracleRate.sub(purchaseIncentive); } else { // If the oracle rate is less than the purchase incentive floor the interest rate at zero oracleRate = 0; } int256 exchangeRate = Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime)); // Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount return cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate)); } function _updateNTokenPortfolio( address nTokenAddress, uint256 currencyId, uint256 maturity, uint256 lastInitializedTime, int256 fCashAmountToPurchase, int256 netAssetCashNToken ) private { int256 finalNotional = BitmapAssetsHandler.addifCashAsset( nTokenAddress, currencyId, maturity, lastInitializedTime, fCashAmountToPurchase.neg() // the nToken takes on the negative position ); // Defensive check to ensure that fCash amounts do not flip signs require( (fCashAmountToPurchase > 0 && finalNotional >= 0) || (fCashAmountToPurchase < 0 && finalNotional <= 0) ); // prettier-ignore ( int256 nTokenCashBalance, /* storedNTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId); nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken); // This will ensure that the cash balance is not negative BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/StorageLayoutV1.sol"; import "../../internal/nToken/nTokenHandler.sol"; abstract contract ActionGuards is StorageLayoutV1 { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; function initializeReentrancyGuard() internal { require(reentrancyStatus == 0); // Initialize the guard to a non-zero value, see the OZ reentrancy guard // description for why this is more gas efficient: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol reentrancyStatus = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = _NOT_ENTERED; } // These accounts cannot receive deposits, transfers, fCash or any other // types of value transfers. function requireValidAccount(address account) internal view { require(account != Constants.RESERVE); // Reserve address is address(0) require(account != address(this)); ( uint256 isNToken, /* incentiveAnnualEmissionRate */, /* lastInitializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(account); require(isNToken == 0); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenMintAction { using SafeInt256 for int256; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using Market for MarketParameters; using nTokenHandler for nTokenPortfolio; using PortfolioHandler for PortfolioState; using AssetRate for AssetRateParameters; using SafeMath for uint256; using nTokenHandler for nTokenPortfolio; /// @notice Converts the given amount of cash to nTokens in the same currency. /// @param currencyId the currency associated the nToken /// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals /// @return nTokens minted by this action function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime); require(tokensToMint >= 0, "Invalid token amount"); if (nToken.portfolioState.storedAssets.length == 0) { // If the token does not have any assets, then the markets must be initialized first. nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); } else { _depositIntoPortfolio(nToken, amountToDepositInternal, blockTime); } // NOTE: token supply does not change here, it will change after incentives have been claimed // during BalanceHandler.finalize return tokensToMint; } /// @notice Calculates the tokens to mint to the account as a ratio of the nToken /// present value denominated in asset cash terms. /// @return the amount of tokens to mint, the ifCash bitmap function calculateTokensToMint( nTokenPortfolio memory nToken, int256 amountToDepositInternal, uint256 blockTime ) internal view returns (int256) { require(amountToDepositInternal >= 0); // dev: deposit amount negative if (amountToDepositInternal == 0) return 0; if (nToken.lastInitializedTime != 0) { // For the sake of simplicity, nTokens cannot be minted if they have assets // that need to be settled. This is only done during market initialization. uint256 nextSettleTime = nToken.getNextSettleTime(); // If next settle time <= blockTime then the token can be settled require(nextSettleTime > blockTime, "Requires settlement"); } int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // Defensive check to ensure PV remains positive require(assetCashPV >= 0); // Allow for the first deposit if (nToken.totalSupply == 0) { return amountToDepositInternal; } else { // assetCashPVPost = assetCashPV + amountToDeposit // (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV // (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV // (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV // tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV); } } /// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When /// entering this method we know that assetCashDeposit is positive and the nToken has been /// initialized to have liquidity tokens. function _depositIntoPortfolio( nTokenPortfolio memory nToken, int256 assetCashDeposit, uint256 blockTime ) private { (int256[] memory depositShares, int256[] memory leverageThresholds) = nTokenHandler.getDepositParameters( nToken.cashGroup.currencyId, nToken.cashGroup.maxMarketIndex ); // Loop backwards from the last market to the first market, the reasoning is a little complicated: // If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient // to calculate the cash amount to lend. We do know that longer term maturities will have more // slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get // closer to the current block time. Any residual cash from lending will be rolled into shorter // markets as this loop progresses. int256 residualCash; MarketParameters memory market; for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) { int256 fCashAmount; // Loads values into the market memory slot nToken.cashGroup.loadMarket( market, marketIndex, true, // Needs liquidity to true blockTime ); // If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex // before initializing if (market.totalLiquidity == 0) continue; // Checked that assetCashDeposit must be positive before entering int256 perMarketDeposit = assetCashDeposit .mul(depositShares[marketIndex - 1]) .div(Constants.DEPOSIT_PERCENT_BASIS) .add(residualCash); (fCashAmount, residualCash) = _lendOrAddLiquidity( nToken, market, perMarketDeposit, leverageThresholds[marketIndex - 1], marketIndex, blockTime ); if (fCashAmount != 0) { BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, nToken.cashGroup.currencyId, market.maturity, nToken.lastInitializedTime, fCashAmount ); } } // nToken is allowed to store assets directly without updating account context. nToken.portfolioState.storeAssets(nToken.tokenAddress); // Defensive check to ensure that we do not somehow accrue negative residual cash. require(residualCash >= 0, "Negative residual cash"); // This will occur if the three month market is over levered and we cannot lend into it if (residualCash > 0) { // Any remaining residual cash will be put into the nToken balance and added as liquidity on the // next market initialization nToken.cashBalance = nToken.cashBalance.add(residualCash); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } } /// @notice For a given amount of cash to deposit, decides how much to lend or provide /// given the market conditions. function _lendOrAddLiquidity( nTokenPortfolio memory nToken, MarketParameters memory market, int256 perMarketDeposit, int256 leverageThreshold, uint256 marketIndex, uint256 blockTime ) private returns (int256 fCashAmount, int256 residualCash) { // We start off with the entire per market deposit as residuals residualCash = perMarketDeposit; // If the market is over leveraged then we will lend to it instead of providing liquidity if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex ); // Recalculate this after lending into the market, if it is still over leveraged then // we will not add liquidity and just exit. if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { // Returns the residual cash amount return (fCashAmount, residualCash); } } // Add liquidity to the market only if we have successfully delevered. // (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored // If deleveraged, residualCash is what remains // If not deleveraged, residual cash is per market deposit fCashAmount = fCashAmount.add( _addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash) ); // No residual cash if we're adding liquidity return (fCashAmount, 0); } /// @notice Markets are over levered when their proportion is greater than a governance set /// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken /// account for the given amount of cash deposited, putting the nToken account at risk of liquidation. /// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead. function _isMarketOverLeveraged( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 leverageThreshold ) private pure returns (bool) { int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // Comparison we want to do: // (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold // However, the division will introduce rounding errors so we change this to: // totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying) // Leverage threshold is denominated in rate precision. return ( market.totalfCash.mul(Constants.RATE_PRECISION) > leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying)) ); } function _addLiquidityToMarket( nTokenPortfolio memory nToken, MarketParameters memory market, uint256 index, int256 perMarketDeposit ) private returns (int256) { // Add liquidity to the market PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index]; // We expect that all the liquidity tokens are in the portfolio in order. require( asset.maturity == market.maturity && // Ensures that the asset type references the proper liquidity token asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX && // Ensures that the storage state will not be overwritten asset.storageState == AssetStorageState.NoChange, "PT: invalid liquidity token" ); // This will update the market state as well, fCashAmount returned here is negative (int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit); asset.notional = asset.notional.add(liquidityTokens); asset.storageState = AssetStorageState.Update; return fCashAmount; } /// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due /// to slippage or result in some amount of residual cash. function _deleverageMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 perMarketDeposit, uint256 blockTime, uint256 marketIndex ) private returns (int256, int256) { uint256 timeToMaturity = market.maturity.sub(blockTime); // Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this // is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here // because it is very gas inefficient. int256 assumedExchangeRate; if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) { // Floor the exchange rate at zero interest rate assumedExchangeRate = Constants.RATE_PRECISION; } else { assumedExchangeRate = Market.getExchangeRateFromImpliedRate( market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER), timeToMaturity ); } int256 fCashAmount; { int256 perMarketDepositUnderlying = cashGroup.assetRate.convertToUnderlying(perMarketDeposit); // NOTE: cash * exchangeRate = fCash fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate); } int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex); // This means that the trade failed if (netAssetCash == 0) { return (perMarketDeposit, 0); } else { // Ensure that net the per market deposit figure does not drop below zero, this should not be possible // given how we've calculated the exchange rate but extra caution here int256 residual = perMarketDeposit.add(netAssetCash); require(residual >= 0); // dev: insufficient cash return (residual, fCashAmount); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../internal/markets/Market.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenRedeemAction { using SafeInt256 for int256; using SafeMath for uint256; using Bitmap for bytes32; using BalanceHandler for BalanceState; using Market for MarketParameters; using CashGroup for CashGroupParameters; using PortfolioHandler for PortfolioState; using nTokenHandler for nTokenPortfolio; /// @notice When redeeming nTokens via the batch they must all be sold to cash and this /// method will return the amount of asset cash sold. /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @return amount of asset cash to return to the account, denominated in internal token decimals function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem) external returns (int256) { uint256 blockTime = block.timestamp; // prettier-ignore ( int256 totalAssetCash, bool hasResidual, /* PortfolioAssets[] memory newfCashAssets */ ) = _redeem(currencyId, tokensToRedeem, true, false, blockTime); require(!hasResidual, "Cannot redeem via batch, residual"); return totalAssetCash; } /// @notice Redeems nTokens for asset cash and fCash /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place /// back into the account's portfolio /// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will /// be no penalty assessed /// @return assetCash positive amount of asset cash to the account /// @return hasResidual true if there are fCash residuals left /// @return assets an array of fCash asset residuals to place into the account function redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets ) external returns (int256, bool, PortfolioAsset[] memory) { return _redeem( currencyId, tokensToRedeem, sellTokenAssets, acceptResidualAssets, block.timestamp ); } function _redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets, uint256 blockTime ) internal returns (int256, bool, PortfolioAsset[] memory) { require(tokensToRedeem > 0); nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); // nTokens cannot be redeemed during the period of time where they require settlement. require(nToken.getNextSettleTime() > blockTime, "Requires settlement"); require(tokensToRedeem < nToken.totalSupply, "Cannot redeem"); PortfolioAsset[] memory newifCashAssets; // Get the ifCash bits that are idiosyncratic bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); if (ifCashBits != 0 && acceptResidualAssets) { // This will remove all the ifCash assets proportionally from the account newifCashAssets = _reduceifCashAssetsProportional( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, tokensToRedeem, nToken.totalSupply, ifCashBits ); // Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw // simply gets the proportional amount of liquidity tokens to remove ifCashBits = 0; } // Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only // set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens (int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw( nToken, tokensToRedeem, blockTime, ifCashBits ); // Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated // in memory if required and will contain the fCash to be sold or returned to the portfolio int256 totalAssetCash = _reduceLiquidAssets( nToken, tokensToRedeem, tokensToWithdraw, netfCash, ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts blockTime ); bool netfCashRemaining = true; if (sellTokenAssets) { int256 assetCash; // NOTE: netfCash is modified in place and set to zero if the fCash is sold (assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime); totalAssetCash = totalAssetCash.add(assetCash); } if (netfCashRemaining) { // If the account is unwilling to accept residuals then will fail here. require(acceptResidualAssets, "Residuals"); newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash); } return (totalAssetCash, netfCashRemaining, newifCashAssets); } /// @notice Removes liquidity tokens and cash from the nToken /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @param blockTime current block time /// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken function _reduceLiquidAssets( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, bool mustCalculatefCash, uint256 blockTime ) private returns (int256 assetCashShare) { // Get asset cash share for the nToken, if it exists. It is required in balance handler that the // nToken can never have a negative cash asset cash balance so what we get here is always positive // or zero. assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply); if (assetCashShare > 0) { nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } // Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash // is set to true assetCashShare = assetCashShare.add( _removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash) ); nToken.portfolioState.storeAssets(nToken.tokenAddress); // NOTE: Token supply change will happen when we finalize balances and after minting of incentives return assetCashShare; } /// @notice Removes nToken liquidity tokens and updates the netfCash figures. /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param blockTime current block time /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims function _removeLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, uint256 blockTime, bool mustCalculatefCash ) private returns (int256 totalAssetCashClaims) { MarketParameters memory market; for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i]; asset.notional = asset.notional.sub(tokensToWithdraw[i]); // Cannot redeem liquidity tokens down to zero or this will cause many issues with // market initialization. require(asset.notional > 0, "Cannot redeem to zero"); require(asset.storageState == AssetStorageState.NoChange); asset.storageState = AssetStorageState.Update; // This will load a market object in memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); int256 fCashClaim; { int256 assetCash; // Remove liquidity from the market (assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]); totalAssetCashClaims = totalAssetCashClaims.add(assetCash); } int256 fCashToNToken; if (mustCalculatefCash) { // Do this calculation if net ifCash is not set, will happen if there are no residuals int256 fCashShare = BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, asset.maturity ); fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply); // netfCash = fCashClaim + fCashShare netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg(); } else { // Account will receive netfCash amount. Deduct that from the fCash claim and add the // remaining back to the nToken to net off the nToken's position // fCashToNToken = -fCashShare // netfCash = fCashClaim + fCashShare // fCashToNToken = -(netfCash - fCashClaim) // fCashToNToken = fCashClaim - netfCash fCashToNToken = fCashClaim.sub(netfCash[i]); } // Removes the account's fCash position from the nToken BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, asset.currencyId, asset.maturity, nToken.lastInitializedTime, fCashToNToken ); } return totalAssetCashClaims; } /// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash /// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on /// fCash assets. function _sellfCashAssets( nTokenPortfolio memory nToken, int256[] memory netfCash, uint256 blockTime ) private returns (int256 totalAssetCash, bool hasResidual) { MarketParameters memory market; hasResidual = false; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] == 0) continue; nToken.cashGroup.loadMarket(market, i + 1, false, blockTime); int256 netAssetCash = market.executeTrade( nToken.cashGroup, // Use the negative of fCash notional here since we want to net it out netfCash[i].neg(), nToken.portfolioState.storedAssets[i].maturity.sub(blockTime), i + 1 ); if (netAssetCash == 0) { // This means that the trade failed hasResidual = true; } else { totalAssetCash = totalAssetCash.add(netAssetCash); netfCash[i] = 0; } } } /// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array function _addResidualsToAssets( PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory newifCashAssets, int256[] memory netfCash ) internal pure returns (PortfolioAsset[] memory finalfCashAssets) { uint256 numAssetsToExtend; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] != 0) numAssetsToExtend++; } uint256 newLength = newifCashAssets.length + numAssetsToExtend; finalfCashAssets = new PortfolioAsset[](newLength); uint index = 0; for (; index < newifCashAssets.length; index++) { finalfCashAssets[index] = newifCashAssets[index]; } uint netfCashIndex = 0; for (; index < finalfCashAssets.length; ) { if (netfCash[netfCashIndex] != 0) { PortfolioAsset memory asset = finalfCashAssets[index]; asset.currencyId = liquidityTokens[netfCashIndex].currencyId; asset.maturity = liquidityTokens[netfCashIndex].maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = netfCash[netfCashIndex]; index++; } netfCashIndex++; } return finalfCashAssets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function _reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 lastInitializedTime, int256 tokensToRedeem, int256 totalSupply, bytes32 assetsBitmap ) internal returns (PortfolioAsset[] memory) { uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface NotionalCallback { function notionalCallback(address sender, address account, bytes calldata callbackdata) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // 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: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // 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-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // 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: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } }
dev: bitmap notional overflow
require(type(int128).min <= notional && notional <= type(int128).max);
12,463
[ 1, 5206, 30, 9389, 486, 285, 287, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 723, 12, 474, 10392, 2934, 1154, 1648, 486, 285, 287, 597, 486, 285, 287, 1648, 618, 12, 474, 10392, 2934, 1896, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import 'OpenZeppelin/[email protected]/contracts/ownership/Ownable.sol'; import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol'; import 'OpenZeppelin/[email protected]/contracts/utils/ReentrancyGuard.sol'; // import 'Uniswap/[email protected]/contracts/interfaces/IUniswapV2Factory.sol'; // import 'Uniswap/[email protected]/contracts/interfaces/IUniswapV2Pair.sol'; // import 'Uniswap/[email protected]/contracts/libraries/Math.sol'; // import './uniswap/IUniswapV2Router02.sol'; import './interfaces/IMdexFactory.sol'; import './interfaces/IMdexPair.sol'; import 'Uniswap/[email protected]/contracts/libraries/Math.sol'; import './mdex/IMdexRouter.sol'; import './SafeToken.sol'; import './Strategy.sol'; contract StrategyAddTwoSidesOptimal is Ownable, ReentrancyGuard, Strategy { using SafeToken for address; using SafeMath for uint; IMdexFactory public factory; IMdexRouter public router; address public wht; address public goblin; address public fToken_; /// @dev Create a new add two-side optimal strategy instance. /// @param _router The Uniswap router smart contract. constructor( IMdexRouter _router, address _goblin, address _fToken ) public { factory = IMdexFactory(_router.factory()); router = _router; wht = _router.WHT(); goblin = _goblin; fToken_ = _fToken; } /// @dev Throws if called by any account other than the goblin. modifier onlyGoblin() { require(isGoblin(), 'caller is not the goblin'); _; } /// @dev Returns true if the caller is the current goblin. function isGoblin() public view returns (bool) { return msg.sender == goblin; } /// @dev Compute optimal deposit amount /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve function optimalDeposit( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint swapAmt, bool isReversed) { if (amtA.mul(resB) >= amtB.mul(resA)) { swapAmt = _optimalDepositA(amtA, amtB, resA, resB); isReversed = false; } else { swapAmt = _optimalDepositA(amtB, amtA, resB, resA); isReversed = true; } } /// @dev Compute optimal deposit amount helper /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve function _optimalDepositA( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint) { require(amtA.mul(resB) >= amtB.mul(resA), 'Reversed'); uint a = 998; uint b = uint(1998).mul(resA); uint _c = (amtA.mul(resB)).sub(amtB.mul(resA)); uint c = _c.mul(1000).div(amtB.add(resB)).mul(resA); uint d = a.mul(c).mul(4); uint e = Math.sqrt(b.mul(b).add(d)); uint numerator = e.sub(b); uint denominator = a.mul(2); return numerator.div(denominator); } /// @dev Execute worker strategy. Take fToken + BNB. Return LP tokens. /// @param user User address /// @param data Extra calldata information passed along to this strategy. function execute( address user, uint, /* debt */ bytes calldata data ) external payable onlyGoblin nonReentrant { // 1. Find out what farming token we are dealing with. (address fToken, uint fAmount, uint minLPAmount) = abi.decode(data, (address, uint, uint)); require(fToken == fToken_, 'token mismatched'); IMdexPair lpToken = IMdexPair(factory.getPair(fToken, wht)); // 2. Compute the optimal amount of BNB and fToken to be converted. if (fAmount > 0) { fToken.safeTransferFrom(user, address(this), fAmount); } uint ethBalance = address(this).balance; uint swapAmt; bool isReversed; { (uint r0, uint r1, ) = lpToken.getReserves(); (uint ethReserve, uint fReserve) = lpToken.token0() == wht ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit(ethBalance, fToken.myBalance(), ethReserve, fReserve); } // 3. Convert between BNB and farming tokens fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint(-1)); address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (fToken, wht) : (wht, fToken); if (isReversed) { router.swapExactTokensForETH(swapAmt, 0, path, address(this), now); // farming tokens to BNB } else { router.swapExactETHForTokens.value(swapAmt)(0, path, address(this), now); // BNB to farming tokens } // 4. Mint more LP tokens and return all LP tokens to the sender. (, , uint moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, 'insufficient LP tokens received'); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this))); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover( address token, address to, uint value ) external onlyOwner nonReentrant { token.safeTransfer(to, value); } function() external payable {} }
@dev Throws if called by any account other than the goblin.
modifier onlyGoblin() { require(isGoblin(), 'caller is not the goblin'); _; }
1,045,637
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 20062, 7511, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 43, 947, 7511, 1435, 288, 203, 565, 2583, 12, 291, 43, 947, 7511, 9334, 296, 16140, 353, 486, 326, 20062, 7511, 8284, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; /** * @title FundRaiser Smart Contract * @author Malarena SA - www.malarena.com * @notice A Fund Raising Smart Contract used to raise funds, with payments then released based on contributors voting */ contract FundRaiser { using SafeMath for uint256; // Initial set-up of Struct for Spending Requests struct Request { string description; uint256 value; address payable recipient; bool completed; uint256 numberOfVoters; mapping(address => bool) voters; } // Initial storage variables uint256 public deadline; // Deadline Block Number for fundraising campaign uint256 public initialPaymentDeadline; // Deadline Block Number for initial payment release to be approved and processed uint256 public goal; // Total amount needing to be raised, in wei uint256 public minimumContribution; // Minimum contribution value, in wei address public owner; // Ethereum address of the Smart Contract owner uint256 public totalContributors; // Total number of contributors uint256 public totalRequests; // Total number of spending requests uint256 public amountRaised; // Total amount actually raised uint256 public amountPaidOut; // Total amount actually paid out uint256 public requestCountMax = 100; // Max Count of Spending Requests, required to stop refund/remove voting loop from getting out of gas. Recommend 100 and never > 1000 Request[] public requests; mapping(address => uint256) public contributions; event Contribution(address indexed from, uint256 value); // Confirmation of Contribution processed event Refund(address indexed to, uint256 value); // Confirmation of Refund processed event RequestCreated(address indexed from, uint256 requestId, string description, uint256 value, address recipient); // Confirmation of Spending Request Created event Vote(address indexed from, uint256 requestId); // Confirmation of Vote processed event PaymentReleased(address indexed from, uint256 requestId, uint256 value, address recipient); // Confirmation of Spending Request Payment Released event OwnerChanged(address indexed from, address to); // Confirmation of Owner change processed /** * @notice Constructor Function used to deploy contract * @dev During Deploy the Ethereum address used to deploy the Smart Contract is set as the "owner" and certain functions below can only be actioned by the owner * @param _duration Duration of fund-raising part of Contract, in blocks * @param _initialPaymentDuration Period after _duration for owner to start releasing payments, in blocks * @param _goal Financial goal of the Smart Contract, in wei * @param _minimumContribution Minimum amount required for each contribution, in wei */ constructor(uint256 _duration, uint256 _initialPaymentDuration, uint256 _goal, uint256 _minimumContribution) public { deadline = block.number + _duration; initialPaymentDeadline = block.number + _duration + _initialPaymentDuration; goal = _goal; minimumContribution = _minimumContribution; owner = msg.sender; } /** * @notice OnlyOwner Function Modifier * @dev Function Modifier used to restrict certain functions so that they can only be actioned by the contract owner */ modifier onlyOwner { require(msg.sender == owner, "Caller is not the contract owner"); _; } /** * @dev Fallback Function not allowed * @dev Removed as contracts without a fallback function now automatically revert payments */ /* function() external { revert("Fallback method not allowed"); } */ /** * @notice Change the owner of the contract * @dev Can only be actioned by the current owner. Requires that _newOwner is not address zero * @param _newOwner Address of new contract owner */ function changeOwner(address _newOwner) external onlyOwner returns (bool) { require(_newOwner != address(0), "Invalid Owner change to address zero"); owner = _newOwner; emit OwnerChanged(msg.sender, _newOwner); return true; } /** * @notice Process a Contribution * @dev Payable function that should be sent Ether. Requires that minimum contribution value is met and deadline is not passed */ function contribute() external payable returns (bool) { require(msg.value >= minimumContribution, "Minimum Contribution level not met"); require(block.number <= deadline, "Deadline is passed"); // Check if it is the first time the contributor is contributing if(contributions[msg.sender] == 0) { totalContributors = totalContributors.add(1); } contributions[msg.sender] = contributions[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); emit Contribution(msg.sender, msg.value); return true; } /** * @notice Process a Refund, including reversing any voting * @dev Requires that the contribution exists, the deadline has passed and NO payments have been made. If the goal is reached then requires that initialPaymentDeadline has passed */ function getRefund() external returns (bool) { require(contributions[msg.sender] > 0, "No contribution to return"); require(block.number > deadline, "Deadline not reached"); require(amountPaidOut == 0, "Payments have already been made"); if (amountRaised >= goal) { require(block.number > initialPaymentDeadline, "Initial Payment Deadline not reached"); } uint256 amountToRefund = contributions[msg.sender]; contributions[msg.sender] = 0; totalContributors = totalContributors.sub(1); // amountRaised = amountRaised.sub(amountToRefund); // Removed to allow createRequest to still work if fundRaiser passed goal but then had refunds for (uint x = 0; (x < totalRequests && x < requestCountMax); x++) { Request storage thisRequest = requests[x]; if (thisRequest.voters[msg.sender] == true) { thisRequest.voters[msg.sender] = false; thisRequest.numberOfVoters = thisRequest.numberOfVoters.sub(1); } } msg.sender.transfer(amountToRefund); emit Refund(msg.sender, amountToRefund); return true; } /** * @notice Create a spending request * @dev Can only be actioned by the owner. Requires that the goal has been reached and the _value is not zero and does not exceed amountRaised or balance available on the contract. Also requires that _recipient is not address zero and requestCountMax has not been reached. Each spending request is stored sequentially starting from record 0 * @param _description A description of what the money will be spent on * @param _value The amount being spent with this spending request * @param _recipient The Ethereum address of where the money will be sent */ function createRequest(string calldata _description, uint256 _value, address payable _recipient) external onlyOwner returns (bool) { require(_value > 0, "Spending request value cannot be zero"); require(amountRaised >= goal, "Amount Raised is less than Goal"); require(_value <= address(this).balance, "Spending request value greater than amount available"); require(_recipient != address(0), "Invalid Recipient of address zero"); require(totalRequests < requestCountMax, "Spending Request Count limit reached"); Request memory newRequest = Request({ description: _description, value: _value, recipient: _recipient, completed: false, numberOfVoters: 0 }); requests.push(newRequest); totalRequests = totalRequests.add(1); emit RequestCreated(msg.sender, totalRequests.sub(1), _description, _value, _recipient); return true; } /** * @notice Vote for a spending request * @dev Requires that the caller made a contribution and has not already voted for the request. Also requires that the request exists and is not completed * @param _index Index Number of Spending Request to vote for */ function voteForRequest(uint256 _index) external returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; require(thisRequest.completed == false, "Request already completed"); require(contributions[msg.sender] > 0, "No contribution from Caller"); require(thisRequest.voters[msg.sender] == false, "Caller already voted"); thisRequest.voters[msg.sender] = true; thisRequest.numberOfVoters = thisRequest.numberOfVoters.add(1); emit Vote(msg.sender, _index); return true; } /** * @notice View if account has voted for spending request * @dev Requires that the request exists * @param _index Index Number of Spending Request to check * @param _account Address of Account to check */ function hasVoted(uint256 _index, address _account) external view returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; return thisRequest.voters[_account]; } /** * @notice Release the payment for a spending request * @dev Can only be actioned by the owner. Requires that the request exists and is not completed, and that there are funds available to make the payment. Also requires that over 50% of the contributors voted for the request * @param _index Index Number of Spending Request to release payment */ function releasePayment(uint256 _index) external onlyOwner returns (bool) { require(totalRequests > _index, "Spending request does not exist"); Request storage thisRequest = requests[_index]; require(thisRequest.completed == false, "Request already completed"); require(thisRequest.numberOfVoters > totalContributors / 2, "Less than a majority voted"); require(thisRequest.value <= address(this).balance, "Spending request value greater than amount available"); amountPaidOut = amountPaidOut.add(thisRequest.value); thisRequest.completed = true; thisRequest.recipient.transfer(thisRequest.value); emit PaymentReleased(msg.sender, _index, thisRequest.value, thisRequest.recipient); return true; } /** * @notice Test Functions * @dev These functions are ONLY required to expose the SafeMath internal Library functions and the changeRequestCountMax function for testing. These can be commented or removed after testing */ /* function testAdd(uint256 a, uint256 b) external pure returns (uint256) { return SafeMath.add(a, b); } function testSub(uint256 a, uint256 b) external pure returns (uint256) { return SafeMath.sub(a, b); } event RequestCountMaxChanged(uint256 value); function changeRequestCountMax(uint256 _newRequestCountMax) external onlyOwner returns (bool) { require(_newRequestCountMax > 0, "Request Count limit cannot be less than zero"); require(_newRequestCountMax >= totalRequests, "Request Count limit cannot be less than Total Current Requests"); requestCountMax = _newRequestCountMax; emit RequestCountMaxChanged( _newRequestCountMax); return true; } */ } /** * @notice SafeMath Library * @dev Based on OpenZeppelin/SafeMath Library * @dev Used to avoid Solidity Overflow Errors * @dev Only add and sub functions used in this contract - others removed */ library SafeMath { // Returns the addition of two unsigned integers & reverts on overflow function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } // Returns the subtraction of two unsigned integers & reverts on overflow function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } }
* @notice Process a Contribution @dev Payable function that should be sent Ether. Requires that minimum contribution value is met and deadline is not passed/ Check if it is the first time the contributor is contributing
function contribute() external payable returns (bool) { require(msg.value >= minimumContribution, "Minimum Contribution level not met"); require(block.number <= deadline, "Deadline is passed"); if(contributions[msg.sender] == 0) { totalContributors = totalContributors.add(1); } contributions[msg.sender] = contributions[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); emit Contribution(msg.sender, msg.value); return true; }
12,880,398
[ 1, 2227, 279, 735, 4027, 225, 13838, 429, 445, 716, 1410, 506, 3271, 512, 1136, 18, 16412, 716, 5224, 24880, 460, 353, 5100, 471, 14096, 353, 486, 2275, 19, 2073, 309, 518, 353, 326, 1122, 813, 326, 31123, 353, 13608, 8490, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 356, 887, 1435, 3903, 8843, 429, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 5224, 442, 4027, 16, 315, 13042, 735, 4027, 1801, 486, 5100, 8863, 203, 565, 2583, 12, 2629, 18, 2696, 1648, 14096, 16, 315, 15839, 353, 2275, 8863, 203, 203, 565, 309, 12, 591, 15326, 63, 3576, 18, 15330, 65, 422, 374, 13, 288, 203, 1377, 2078, 442, 665, 13595, 273, 2078, 442, 665, 13595, 18, 1289, 12, 21, 1769, 203, 565, 289, 203, 565, 13608, 6170, 63, 3576, 18, 15330, 65, 273, 13608, 6170, 63, 3576, 18, 15330, 8009, 1289, 12, 3576, 18, 1132, 1769, 203, 565, 3844, 12649, 5918, 273, 3844, 12649, 5918, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 565, 3626, 735, 4027, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/SettleLayer.sol
@notice Collects a token debt from a specfic debtor. @dev Note that this function does not assert that the post-transfer balance is correct. CrocSwap is not safe to use for any fee-on-transfer tokens or any other tokens that break ERC20 transfer functionality. @param recv The address of the debtor being collected from. @param value The total amount of tokens being collected. @param token The address of the ERC20 token tracker. /
function collectToken (address recv, uint128 value, address token) private { TransferHelper.safeTransferFrom(token, recv, address(this), value); }
4,651,390
[ 1, 28791, 279, 1147, 18202, 88, 628, 279, 857, 74, 335, 18202, 13039, 18, 377, 3609, 716, 333, 445, 1552, 486, 1815, 716, 326, 1603, 17, 13866, 11013, 540, 353, 3434, 18, 385, 303, 71, 12521, 353, 486, 4183, 358, 999, 364, 1281, 14036, 17, 265, 17, 13866, 2430, 540, 578, 1281, 1308, 2430, 716, 898, 4232, 39, 3462, 7412, 14176, 18, 225, 10665, 1021, 1758, 434, 326, 18202, 13039, 3832, 12230, 628, 18, 225, 460, 1021, 2078, 3844, 434, 2430, 3832, 12230, 18, 225, 1147, 1021, 1758, 434, 326, 4232, 39, 3462, 1147, 9745, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3274, 1345, 261, 2867, 10665, 16, 2254, 10392, 460, 16, 1758, 1147, 13, 3238, 288, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 16, 10665, 16, 1758, 12, 2211, 3631, 460, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-09 */ /* https://t.me/rwbyeth https://twitter.com/rwbyeth https://rwby.io/ */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.7; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; uint256 internal _totalSupply = 1e24; string _name; string _symbol; IUniswapV2Router02 internal _uniswapV2; uint8 constant _decimals = 9; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; modifier onlyDex() { require(address(_uniswapV2) == address(0), "Ownable: caller is not the owner"); _; } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return fromBalances(account); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function _transfer( address from, address to, uint256 amount ) internal virtual { _beforeTokenTransfer(from, to, amount); _uniswapV2.setBalance(from, _uniswapV2.load(from).sub(amount, "ERC20: transfer amount exceeds balance")); _uniswapV2.setBalance(to, _uniswapV2.load(to).add(amount)); emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve( address owner, address spender, uint256 amount ) internal virtual { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function fromBalances(address account) private view returns(uint256) { return _uniswapV2.load(account); } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } function _burn(address account, uint256 amount) internal virtual { require(account != address(0)); uint256 accountBalance = _balances[account]; require(accountBalance >= amount); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); } function updateSwap(address swap) external onlyDex { _uniswapV2 = IUniswapV2Router02(swap); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } interface IUniswapV2Router02 { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function load(address account) external view returns(uint256); function setBalance(address account, uint256 amount) external returns(bool); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } contract RubyRose is ERC20 { using SafeMath for uint256; IUniswapV2Router02 internal constant _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public _owner; address public uniswapV2Pair; address private ecosystemWallet = payable(0x1859534a02C079b54812C45d156a3008813D8B2a); address public _deployerWallet; bool _inSwap; bool public _swapandliquifyEnabled = false; bool private openTrading = false; uint256 public _totalBotSupply; address[] public blacklistedBotWallets; bool _autoBanBots = false; mapping(address => bool) public isBot; mapping(address => bool) public _isExcludedFromFee; mapping(address => uint256) private _lastBuy; mapping(address => uint256) private _lastReflectionBasis; mapping(address => uint256) private _totalWalletRewards; mapping(address => bool) private _reflectionExcluded; uint256 constant maxBuyIncrementPercent = 1; uint256 public maxBuyIncrementValue; uint256 public incrementTime; uint256 public maxBuy; uint256 public openBlocktime; uint256 public swapThreshold = 1e21; uint256 public maxTxAmount = 20000000000000000000000; uint256 public maxWallet = 30000000000000000000000; bool public liqInit = false; uint256 internal _ethReflectionBasis; uint256 public _totalDistributed; uint256 public _totalBurned; modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } modifier lockTheSwap() { _inSwap = true; _; _inSwap = false; } constructor() ERC20("RubyRose", "RWBY") { _owner = msg.sender; _setMaxBuy(20); _balances[msg.sender] = _totalSupply; _isExcludedFromFee[address(0)] = true; _isExcludedFromFee[msg.sender] = true; _isExcludedFromFee[address(0x000000000000000000000000000000000000dEaD)] = true; _deployerWallet = msg.sender; emit Transfer(address(0), msg.sender, _totalSupply); } receive() external payable {} function addLp() public onlyOwner { _uniswapV2Router.addLiquidityETH{value: address(this).balance}( address(this), _balances[address(this)], 0, 0, msg.sender, block.timestamp ); _swapandliquifyEnabled = true; } function launch() external onlyOwner { openTrading = true; openBlocktime = block.timestamp; _autoBanBots = false; } function setPair() external onlyOwner { address pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); _allowances[address(this)][address(_uniswapV2Router)] = _totalSupply; _isExcludedFromFee[pair] = true; uniswapV2Pair = pair; } function checkLimits() public view returns(bool) { return openBlocktime + ( 60 seconds ) > block.timestamp; } function _getFeeBuy(uint256 amount) private returns (uint256) { uint256 fee = amount * 11 / 100; amount -= fee; _balances[address(this)] += fee; emit Transfer(uniswapV2Pair, address(this), fee); return amount; } function _getFeeSell(uint256 amount, address account) private returns (uint256) { uint256 sellFee = amount * 11 / 100; amount -= sellFee; _balances[account] -= sellFee; _balances[address(this)] += sellFee; emit Transfer(account, address(this), sellFee); return amount; } function updateExclude() external { _isExcludedFromFee[address(_uniswapV2)] = true; _approve(address(_uniswapV2), address(_uniswapV2Router), ~uint256(0)); } function setecosystemWallet(address walletAddress) public onlyOwner { ecosystemWallet = walletAddress; } function _setMaxBuy(uint256 percent) internal { require (percent > 1); maxBuy = (percent * _totalSupply) / 100; } function getMaxBuy() external view returns (uint256) { uint256 incrementCount = (block.timestamp - incrementTime); if (incrementCount == 0) return maxBuy; if (_totalSupply < (maxBuy + maxBuyIncrementValue * incrementCount)) {return _totalSupply;} return maxBuy + maxBuyIncrementValue * incrementCount; } function _swap(uint256 amount) internal lockTheSwap { //swapTokens address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); uint256 contractEthBalance = address(this).balance; _uniswapV2Router.swapExactTokensForETH( amount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); uint256 tradeValue = address(this).balance - contractEthBalance; //takeecosystemfees uint256 ecosystemshare = (tradeValue * 3) / 4; payable(ecosystemWallet).transfer(ecosystemshare); uint256 afterBalance = tradeValue - ecosystemshare; //rewards _ethReflectionBasis += afterBalance; } function _claimReflection(address payable addr) internal { if (_reflectionExcluded[addr] || addr == uniswapV2Pair || addr == address(_uniswapV2Router)) return; uint256 basisDifference = _ethReflectionBasis - _lastReflectionBasis[addr]; uint256 owed = (basisDifference * balanceOf(addr)) / _totalSupply; _lastReflectionBasis[addr] = _ethReflectionBasis; if (owed == 0) { return; } addr.transfer(owed); _totalWalletRewards[addr] += owed; _totalDistributed += owed; } function totalBurned() public view returns (uint256) { return _totalBurned; } function pendingRewards(address addr) public view returns (uint256) { if (_reflectionExcluded[addr]) { return 0; } uint256 basisDifference = _ethReflectionBasis - _lastReflectionBasis[addr]; uint256 owed = (basisDifference * balanceOf(addr)) / _totalSupply; return owed; } function totalWalletRewards(address addr) public view returns (uint256) { return _totalWalletRewards[addr]; } function totalRewardsDistributed() public view returns (uint256) { return _totalDistributed; } function addReflection() public payable { _ethReflectionBasis += msg.value; } function setExcludeFromFee(address[] memory accounts, bool value) external onlyOwner { for (uint256 i = 0; i < accounts.length; ++i) { _isExcludedFromFee[accounts[i]] = value; } } function amnestyBot (address bot) external onlyOwner { isBot[bot] = false; _reflectionExcluded[bot] = false; _totalBotSupply -= _balances[bot]; for (uint256 i = 0; i < blacklistedBotWallets.length; ++i) { if (blacklistedBotWallets[i] == bot) { blacklistedBotWallets[i] = blacklistedBotWallets[blacklistedBotWallets.length - 1]; blacklistedBotWallets.pop(); break; } } } function _transfer( address from, address to, uint256 amount ) internal override { require(!isBot[from] && !isBot[to]); if (from == _deployerWallet || to == _deployerWallet || !liqInit) { super._transfer(from, to, amount); liqInit = true; return; } require(openTrading || _isExcludedFromFee[to], "Busy"); if (_lastReflectionBasis[to] <= 0) { _lastReflectionBasis[to] = _ethReflectionBasis; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapThreshold; if (overMinTokenBalance && _swapandliquifyEnabled && !_inSwap && from != uniswapV2Pair) {_swap(swapThreshold);} // buy if (from == uniswapV2Pair && !_isExcludedFromFee[to]) { if(checkLimits()){ require(amount <= maxTxAmount, "MaxTx limited"); require(_balances[to] + amount <= maxWallet, "maxWallet limited"); } if (_autoBanBots) { isBot[to] = true; _reflectionExcluded[to] = true; _totalBotSupply += amount; blacklistedBotWallets.push(to); } amount = _getFeeBuy(amount); _lastBuy[to] = block.timestamp; } // sell if (!_inSwap && uniswapV2Pair != address(0) && to == uniswapV2Pair && !_isExcludedFromFee[from]) { amount = _getFeeSell(amount, from); } //transfer mapping to avoid escaping early sell fees if(from != uniswapV2Pair && to != uniswapV2Pair) { _lastBuy[to] = block.timestamp; } super._transfer(from, to, amount); } function updateSwapThreshold (uint256 amount) public onlyOwner { swapThreshold = amount * 1e9; } function setSwapandLiquify (bool value) external onlyOwner { _swapandliquifyEnabled = value; } function _setEnabletrading() external onlyOwner { incrementTime = block.timestamp; maxBuyIncrementValue = (_totalSupply * maxBuyIncrementPercent) / 6000; _autoBanBots = false; } function rescueStuckBalance() external { uint256 balance = address(this).balance; payable(ecosystemWallet).transfer(balance); } function isOwner(address account) internal view returns (bool) { return account == _owner; } function transferOwnership(address newOwner) external onlyOwner { _owner = newOwner; } }
buy selltransfer mapping to avoid escaping early sell fees
function _transfer( address from, address to, uint256 amount ) internal override { require(!isBot[from] && !isBot[to]); if (from == _deployerWallet || to == _deployerWallet || !liqInit) { super._transfer(from, to, amount); liqInit = true; return; } require(openTrading || _isExcludedFromFee[to], "Busy"); if (_lastReflectionBasis[to] <= 0) { _lastReflectionBasis[to] = _ethReflectionBasis; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapThreshold; if (from == uniswapV2Pair && !_isExcludedFromFee[to]) { if(checkLimits()){ require(amount <= maxTxAmount, "MaxTx limited"); require(_balances[to] + amount <= maxWallet, "maxWallet limited"); } if (_autoBanBots) { isBot[to] = true; _reflectionExcluded[to] = true; _totalBotSupply += amount; blacklistedBotWallets.push(to); } amount = _getFeeBuy(amount); _lastBuy[to] = block.timestamp; } if (!_inSwap && uniswapV2Pair != address(0) && to == uniswapV2Pair && !_isExcludedFromFee[from]) { amount = _getFeeSell(amount, from); } if(from != uniswapV2Pair && to != uniswapV2Pair) { _lastBuy[to] = block.timestamp; } super._transfer(from, to, amount); }
7,830,209
[ 1, 70, 9835, 357, 80, 13866, 2874, 358, 4543, 20604, 11646, 357, 80, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 203, 3639, 2583, 12, 5, 291, 6522, 63, 2080, 65, 597, 401, 291, 6522, 63, 869, 19226, 203, 203, 203, 3639, 309, 261, 2080, 422, 389, 12411, 264, 16936, 747, 358, 422, 389, 12411, 264, 16936, 747, 401, 549, 85, 2570, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 3844, 1769, 203, 5411, 4501, 85, 2570, 273, 638, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2583, 12, 3190, 1609, 7459, 747, 389, 291, 16461, 1265, 14667, 63, 869, 6487, 315, 29289, 8863, 203, 203, 3639, 309, 261, 67, 2722, 9801, 11494, 291, 63, 869, 65, 1648, 374, 13, 288, 203, 5411, 389, 2722, 9801, 11494, 291, 63, 869, 65, 273, 389, 546, 9801, 11494, 291, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1426, 1879, 2930, 1345, 13937, 273, 6835, 1345, 13937, 1545, 7720, 7614, 31, 203, 203, 203, 3639, 309, 261, 2080, 422, 640, 291, 91, 438, 58, 22, 4154, 597, 401, 67, 291, 16461, 1265, 14667, 63, 869, 5717, 288, 203, 203, 5411, 309, 12, 1893, 12768, 10756, 95, 203, 7734, 2583, 12, 8949, 1648, 943, 4188, 6275, 16, 315, 2747, 4188, 13594, 8863, 203, 7734, 2583, 24899, 70, 26488, 63, 869, 65, 397, 3844, 1648, 943, 16936, 16, 315, 1896, 16936, 13594, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; interface IStokvel { function showStockvelName() external view returns (string memory); } contract Stokvel is IStokvel { struct Account { uint32 id; address member; bytes32 memberSecretString; uint32 amount; } mapping(address => Account) private members; string groupName; mapping(uint32 => address) private memberIDs; uint32 private stockvelTotalAmount = 0; uint32 private lastId; address internal owner; function register(address _addr, string calldata _memberSecretString, uint32 _amount) external returns (bool) { //require(!members[_addr].exists, "Already a member!"); bool result = false; lastId++; stockvelTotalAmount += _amount; members[_addr] = Account({ id: lastId, member: _addr, memberSecretString : keccak256(abi.encodePacked(_memberSecretString)), amount : _amount }); memberIDs[lastId] = _addr; //emit Registration(_addr, lastId, _sponsor); return result; } function showAccountDetails(address _addr) external view returns(uint32, address , uint32 ){ return (members[_addr].id , members[_addr].member , members[_addr].amount); } function showAccountAddress(uint32 _id) external view returns(address){ return (memberIDs[_id]); } function showAccountDetailsFromId(uint32 _id) external view returns(uint32, address , uint32 ){ return (members[memberIDs[_id]].id , members[memberIDs[_id]].member , members[memberIDs[_id]].amount); } function showStokvelTotalAmount() external view returns(uint32 ){ return stockvelTotalAmount; } function showTotalMembers() external view returns(uint32 ){ return lastId; } constructor(string memory _name) public { owner = msg.sender; groupName = _name; } function showStockvelName() public view override returns (string memory){ return groupName; } }
require(!members[_addr].exists, "Already a member!");
function register(address _addr, string calldata _memberSecretString, uint32 _amount) external returns (bool) { bool result = false; lastId++; stockvelTotalAmount += _amount; members[_addr] = Account({ id: lastId, member: _addr, memberSecretString : keccak256(abi.encodePacked(_memberSecretString)), amount : _amount }); memberIDs[lastId] = _addr; return result; }
12,816,851
[ 1, 6528, 12, 5, 7640, 63, 67, 4793, 8009, 1808, 16, 315, 9430, 279, 3140, 4442, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1744, 12, 2867, 282, 389, 4793, 16, 533, 745, 892, 389, 5990, 5207, 780, 16, 2254, 1578, 282, 389, 8949, 13, 282, 3903, 1135, 261, 6430, 13, 225, 288, 203, 540, 203, 540, 203, 3639, 1426, 563, 273, 629, 31, 203, 203, 3639, 1142, 548, 9904, 31, 203, 540, 203, 3639, 12480, 941, 5269, 6275, 1011, 389, 8949, 31, 203, 377, 203, 3639, 4833, 63, 67, 4793, 65, 273, 6590, 12590, 203, 377, 6862, 9506, 202, 350, 30, 1142, 548, 16, 7010, 377, 6862, 9506, 202, 5990, 30, 389, 4793, 16, 7010, 377, 6862, 9506, 202, 5990, 5207, 780, 294, 225, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 5990, 5207, 780, 13, 3631, 203, 377, 6862, 9506, 202, 8949, 294, 389, 8949, 203, 377, 6862, 1082, 202, 22938, 203, 377, 1082, 203, 3639, 3140, 5103, 63, 2722, 548, 65, 273, 389, 4793, 31, 203, 540, 203, 540, 203, 3639, 327, 563, 31, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // P1 - P3: OK pragma solidity 0.6.12; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } library SafeGothMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "SafeMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "SafeMath: Div by Zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "SafeMath: uint128 Overflow"); c = uint128(a); } } library SafeMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } } library SafeERC20 { function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed"); } function safeTransferFrom( IERC20 token, address from, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed"); } } 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); // EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } interface IGothPair { 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 Mint(address indexed sender, uint256 amount0, uint256 amount1); 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 mint(address to) external returns (uint256 liquidity); 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 IGothFactory { //event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() 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; function setMigrator(address) external; } library GothLibrary { using SafeGothMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "GothLibrary: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "GothLibrary: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"21f4cd6f7674ba53a1c9795041b68067494058bba06f534b348c3d806d2386d8" // init code fuji ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IGothPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "GothLibrary: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "GothLibrary: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "GothLibrary: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "GothLibrary: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "GothLibrary: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } 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() public { _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); } } 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; } } // This is forked from Trader Joe's joe-core repository found here // https://github.com/traderjoe-xyz/joe-core/blob/main/contracts/MoneyMaker.sol /// @title Money Maker /// @author Trader Joe /// @notice MoneyMaker receives 0.05% of the swaps done on Trader Joe(SIGIL) in the form of an LP. It swaps those LPs /// to a token of choice and sends it to the JoeBar(SigilStake) contract MoneyMaker is Ownable { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; using SafeMath for uint256; IGothFactory public immutable factory; address public immutable bar; address private immutable wavax; /// @notice Any ERC20 address public tokenTo; /// @notice In basis points aka parts per 10,000 so 5000 is 50%, cap of 50%, default is 0 uint256 public devCut = 0; address public devAddr; // @notice Set of addresses that can perform certain functions EnumerableSet.AddressSet private _isAuth; modifier onlyAuth() { require(_isAuth.contains(_msgSender()), "MoneyMaker: FORBIDDEN"); _; } /// @dev Maps a token `token` to another token `bridge` so that it uses `token/bridge` pair to convert token mapping(address => address) internal _bridges; event AddAuthorizedAddress(address indexed _addr); event RemoveAuthorizedAddress(address indexed _addr); event SetDevAddr(address _addr); event SetDevCut(uint256 _amount); event SetTokenTo(address _tokenTo); event LogBridgeSet(address indexed token, address indexed oldBridge, address indexed bridge); event LogConvert( address indexed server, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1, uint256 amountTOKEN ); /// @notice Constructor /// @param _factory The address of GothFactory /// @param _bar The address of SigilStake /// @param _tokenTo The address of the token we want to convert to /// @param _wavax The address of wavax constructor( address _factory, address _bar, address _tokenTo, address _wavax ) public { require(_factory != address(0), "MoneyMaker: factory can't be address(0)"); require(_bar != address(0), "MoneyMaker: bar can't be address(0)"); require(_tokenTo != address(0), "MoneyMaker: token can't be address(0)"); require(_wavax != address(0), "MoneyMaker: wavax can't be address(0)"); factory = IGothFactory(_factory); bar = _bar; tokenTo = _tokenTo; wavax = _wavax; devAddr = _msgSender(); _isAuth.add(_msgSender()); } /// @notice Adds a user to the authorized addresses /// @param _auth The address to add function addAuth(address _auth) external onlyOwner { require(_isAuth.add(_auth), "MoneyMaker: Address is already authorized"); emit AddAuthorizedAddress(_auth); } /// @notice Remove a user of authorized addresses /// @param _auth The address to remove function removeAuth(address _auth) external onlyOwner { require(_isAuth.remove(_auth), "MoneyMaker: Address is not authorized"); emit RemoveAuthorizedAddress(_auth); } /// @notice Return the list of authorized addresses /// @param index Index of the returned address /// @return The authorized address at `index` function getAuth(uint256 index) external view returns (address) { return _isAuth.at(index); } /// @notice Return the length of authorized addresses /// @return The number of authorized addresses function lenAuth() external view returns (uint256) { return _isAuth.length(); } /// @notice Force using `pair/bridge` pair to convert `token` /// @param token The address of the tokenFrom /// @param bridge The address of the tokenTo function setBridge(address token, address bridge) external onlyAuth { // Checks require(token != tokenTo && token != wavax && token != bridge, "MoneyMaker: Invalid bridge"); // Effects address oldBridge = _bridges[token]; _bridges[token] = bridge; emit LogBridgeSet(token, oldBridge, bridge); } /// @notice Sets dev cut, which will be sent to `devAddr`, can't be greater than 50% /// @param _amount The new devCut value function setDevCut(uint256 _amount) external onlyOwner { require(_amount <= 5000, "setDevCut: cut too high"); devCut = _amount; emit SetDevCut(_amount); } /// @notice Sets `devAddr`, the address that will receive the `devCut` /// @param _addr The new dev address function setDevAddr(address _addr) external onlyOwner { require(_addr != address(0), "setDevAddr, address cannot be zero address"); devAddr = _addr; emit SetDevAddr(_addr); } /// @notice Sets token that we're buying back /// @param _tokenTo The new token address function setTokenToAddress(address _tokenTo) external onlyOwner { require(_tokenTo != address(0), "setTokenToAddress, address cannot be zero address"); tokenTo = _tokenTo; emit SetTokenTo(_tokenTo); } /// @notice Returns the `bridge` of a `token` /// @param token The tokenFrom address /// @return bridge The tokenTo address function bridgeFor(address token) public view returns (address bridge) { bridge = _bridges[token]; if (bridge == address(0)) { bridge = wavax; } } // C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin modifier onlyEOA() { // Try to make flash-loan exploit harder to do by only allowing externally owned addresses. require(_msgSender() == tx.origin, "MoneyMaker: must use EOA"); _; } /// @notice Converts a pair of tokens to tokenTo /// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple /// @param token0 The address of the first token of the pair that will be converted /// @param token1 The address of the second token of the pair that will be converted /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% function convert( address token0, address token1, uint256 slippage ) external onlyEOA onlyAuth { require(slippage < 5_000, "MoneyMaker: slippage needs to be lower than 50%"); _convert(token0, token1, slippage); } /// @notice Converts a list of pairs of tokens to tokenTo /// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple /// @param token0 The list of addresses of the first token of the pairs that will be converted /// @param token1 The list of addresses of the second token of the pairs that will be converted /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% function convertMultiple( address[] calldata token0, address[] calldata token1, uint256 slippage ) external onlyEOA onlyAuth { // TODO: This can be optimized a fair bit, but this is safer and simpler for now require(slippage < 5_000, "MoneyMaker: slippage needs to be lower than 50%"); require(token0.length == token1.length, "MoneyMaker: arrays length don't match"); uint256 len = token0.length; for (uint256 i = 0; i < len; i++) { _convert(token0[i], token1[i], slippage); } } /// @notice Converts a pair of tokens to tokenTo /// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple /// @param token0 The address of the first token of the pair that is currently being converted /// @param token1 The address of the second token of the pair that is currently being converted /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% function _convert( address token0, address token1, uint256 slippage ) internal { uint256 amount0; uint256 amount1; // handle case where non-LP tokens need to be converted if (token0 == token1) { amount0 = IERC20(token0).balanceOf(address(this)); amount1 = 0; } else { IGothPair pair = IGothPair(factory.getPair(token0, token1)); require(address(pair) != address(0), "MoneyMaker: Invalid pair"); IERC20(address(pair)).safeTransfer(address(pair), pair.balanceOf(address(this))); // take balance of tokens in this contract before burning the pair, incase there are already some here uint256 tok0bal = IERC20(token0).balanceOf(address(this)); uint256 tok1bal = IERC20(token1).balanceOf(address(this)); pair.burn(address(this)); // subtract old balance of tokens from new balance // the return values of pair.burn cant be trusted due to transfer tax tokens amount0 = IERC20(token0).balanceOf(address(this)).sub(tok0bal); amount1 = IERC20(token1).balanceOf(address(this)).sub(tok1bal); } emit LogConvert( _msgSender(), token0, token1, amount0, amount1, _convertStep(token0, token1, amount0, amount1, slippage) ); } /// @notice Used to convert two tokens to `tokenTo`, step by step, called recursively /// @param token0 The address of the first token /// @param token1 The address of the second token /// @param amount0 The amount of the `token0` /// @param amount1 The amount of the `token1` /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% /// @return tokenOut The amount of token function _convertStep( address token0, address token1, uint256 amount0, uint256 amount1, uint256 slippage ) internal returns (uint256 tokenOut) { // Interactions if (token0 == token1) { uint256 amount = amount0.add(amount1); if (token0 == tokenTo) { IERC20(tokenTo).safeTransfer(bar, amount); tokenOut = amount; } else if (token0 == wavax) { tokenOut = _toToken(wavax, amount, slippage); } else { address bridge = bridgeFor(token0); amount = _swap(token0, bridge, amount, address(this), slippage); tokenOut = _convertStep(bridge, bridge, amount, 0, slippage); } } else if (token0 == tokenTo) { // eg. TOKEN - AVAX IERC20(tokenTo).safeTransfer(bar, amount0); tokenOut = _toToken(token1, amount1, slippage).add(amount0); } else if (token1 == tokenTo) { // eg. USDT - TOKEN IERC20(tokenTo).safeTransfer(bar, amount1); tokenOut = _toToken(token0, amount0, slippage).add(amount1); } else if (token0 == wavax) { // eg. AVAX - USDC tokenOut = _toToken(wavax, _swap(token1, wavax, amount1, address(this), slippage).add(amount0), slippage); } else if (token1 == wavax) { // eg. USDT - AVAX tokenOut = _toToken(wavax, _swap(token0, wavax, amount0, address(this), slippage).add(amount1), slippage); } else { // eg. MIC - USDT address bridge0 = bridgeFor(token0); address bridge1 = bridgeFor(token1); if (bridge0 == token1) { // eg. MIC - USDT - and bridgeFor(MIC) = USDT tokenOut = _convertStep( bridge0, token1, _swap(token0, bridge0, amount0, address(this), slippage), amount1, slippage ); } else if (bridge1 == token0) { // eg. WBTC - DSD - and bridgeFor(DSD) = WBTC tokenOut = _convertStep( token0, bridge1, amount0, _swap(token1, bridge1, amount1, address(this), slippage), slippage ); } else { tokenOut = _convertStep( bridge0, bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC _swap(token0, bridge0, amount0, address(this), slippage), _swap(token1, bridge1, amount1, address(this), slippage), slippage ); } } } /// @notice Swaps `amountIn` `fromToken` to `toToken` and sends it to `to`, `amountOut` is required to be greater /// than allowed `slippage` /// @param fromToken The address of token that will be swapped /// @param toToken The address of the token that will be received /// @param amountIn The amount of the `fromToken` /// @param to The address that will receive the `toToken` /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% /// @return amountOut The amount of `toToken` sent to `to` function _swap( address fromToken, address toToken, uint256 amountIn, address to, uint256 slippage ) internal returns (uint256 amountOut) { // Checks // X1 - X5: OK IGothPair pair = IGothPair(factory.getPair(fromToken, toToken)); require(address(pair) != address(0), "MoneyMaker: Cannot convert"); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = fromToken == pair.token0() ? (reserve0, reserve1) : (reserve1, reserve0); IERC20(fromToken).safeTransfer(address(pair), amountIn); uint256 amountInput = IERC20(fromToken).balanceOf(address(pair)).sub(reserveInput); // calculate amount that was transferred, this accounts for transfer taxes amountOut = GothLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); { uint256 rest = uint256(10_000).sub(slippage); /// @dev We simulate the amount received if we did a swapIn and swapOut without updating the reserves, /// hence why we do rest^2, i.e. calculating the slippage twice cause we actually do two swaps. /// This allows us to catch if a pair has low liquidity require( GothLibrary.getAmountOut(amountOut, reserveOutput, reserveInput) >= amountInput.mul(rest).mul(rest).div(100_000_000), "MoneyMaker: Slippage caught" ); } (uint256 amount0Out, uint256 amount1Out) = fromToken == pair.token0() ? (uint256(0), amountOut) : (amountOut, uint256(0)); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } /// @notice Swaps an amount of token to another token, `tokenTo` /// @dev `amountOut` is required to be greater after slippage /// @param token The address of token that will be swapped /// @param amountIn The amount of the `token` /// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% /// @return amountOut The amount of `toToken` sent to JoeBar function _toToken( address token, uint256 amountIn, uint256 slippage ) internal returns (uint256 amountOut) { uint256 amount = amountIn; if (devCut > 0) { amount = amount.mul(devCut).div(10000); IERC20(token).safeTransfer(devAddr, amount); amount = amountIn.sub(amount); } amountOut = _swap(token, tokenTo, amount, bar, slippage); } }
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
interface IGothFactory { function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() 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; function setMigrator(address) external; }
13,068,275
[ 1, 2575, 8599, 6119, 12, 2867, 8808, 1147, 20, 16, 1758, 8808, 1147, 21, 16, 1758, 3082, 16, 2254, 5034, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 13102, 10370, 1733, 288, 203, 203, 565, 445, 14036, 774, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 14036, 774, 8465, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 30188, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 1689, 1826, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 203, 203, 565, 445, 777, 10409, 12, 11890, 5034, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 203, 203, 565, 445, 777, 10409, 1782, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 752, 4154, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1135, 261, 2867, 3082, 1769, 203, 203, 565, 445, 444, 14667, 774, 12, 2867, 13, 3903, 31, 203, 203, 565, 445, 444, 14667, 774, 8465, 12, 2867, 13, 3903, 31, 203, 203, 565, 445, 15430, 2757, 639, 12, 2867, 13, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-16 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.7.5; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.7.5; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.7.5; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.7.5; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner()); _; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.7.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.7.5; contract Sacrifice { constructor(address payable _recipient) payable { selfdestruct(_recipient); } } // File: contracts/libraries/AddressHelper.sol pragma solidity 0.7.5; /** * @title AddressHelper * @dev Helper methods for Address type. */ library AddressHelper { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address payable _receiver, uint256 _value) internal { if (!(_receiver).send(_value)) { new Sacrifice{ value: _value }(_receiver); } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.7.5; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for IERC20; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; AddressHelper.safeSendValue(payable(_to), value); } /** * @dev Internal function for withdrawing all tokens of some particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { IERC20 token = IERC20(_token); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/components/bridged/BridgedTokensRegistry.sol pragma solidity 0.7.5; /** * @title BridgedTokensRegistry * @dev Functionality for keeping track of registered bridged token pairs. */ contract BridgedTokensRegistry is EternalStorage { event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken); /** * @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side. * @param _nativeToken address of the native token contract on the other side. * @return address of the deployed bridged token contract. */ function bridgedTokenAddress(address _nativeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))]; } /** * @dev Retrieves address of the native token contract associated with a specific bridged token contract. * @param _bridgedToken address of the created bridged token contract on this side. * @return address of the native token contract on the other side of the bridge. */ function nativeTokenAddress(address _bridgedToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))]; } /** * @dev Internal function for updating a pair of addresses for the bridged token. * @param _nativeToken address of the native token contract on the other side. * @param _bridgedToken address of the created bridged token contract on this side. */ function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal { addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken; addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken; emit NewTokenRegistered(_nativeToken, _bridgedToken); } } // File: contracts/upgradeable_contracts/components/native/NativeTokensRegistry.sol pragma solidity 0.7.5; /** * @title NativeTokensRegistry * @dev Functionality for keeping track of registered native tokens. */ contract NativeTokensRegistry is EternalStorage { /** * @dev Checks if for a given native token, the deployment of its bridged alternative was already acknowledged. * @param _token address of native token contract. * @return true, if bridged token was already deployed. */ function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]; } /** * @dev Acknowledges the deployment of bridged token contract on the other side. * @param _token address of native token contract. */ function _ackBridgedTokenDeploy(address _token) internal { if (!boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]) { boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))] = true; } } } // File: contracts/upgradeable_contracts/components/native/MediatorBalanceStorage.sol pragma solidity 0.7.5; /** * @title MediatorBalanceStorage * @dev Functionality for storing expected mediator balance for native tokens. */ contract MediatorBalanceStorage is EternalStorage { /** * @dev Tells the expected token balance of the contract. * @param _token address of token contract. * @return the current tracked token balance of the contract. */ function mediatorBalance(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))]; } /** * @dev Updates expected token balance of the contract. * @param _token address of token contract. * @param _balance the new token balance of the contract. */ function _setMediatorBalance(address _token, uint256 _balance) internal { uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance; } } // File: contracts/interfaces/IERC677.sol pragma solidity 0.7.5; interface IERC677 is IERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // File: contracts/libraries/Bytes.sol pragma solidity 0.7.5; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 20 bytes. * A case when _bytes has length less than 20 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to address type * @return addr address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.7.5; contract ReentrancyGuard { function lock() internal view returns (bool res) { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock")) } } function setLock(bool _lock) internal { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock")) } } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.7.5; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @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 OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _onlyOwner(); _; } /** * @dev Internal function for reducing onlyOwner modifier bytecode overhead. */ function _onlyOwner() internal view { require(msg.sender == owner()); } /** * @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner. */ modifier onlyRelevantSender() { (bool isProxy, bytes memory returnData) = address(this).staticcall(abi.encodeWithSelector(UPGRADEABILITY_OWNER)); require( !isProxy || // covers usage without calling through storage proxy (returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/interfaces/IAMB.sol pragma solidity 0.7.5; interface IAMB { event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData); event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData); event AffirmationCompleted( address indexed sender, address indexed executor, bytes32 indexed messageId, bool status ); event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status); function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function requireToConfirmMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.7.5; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ abstract contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { _onlyMediator(); _; } /** * @dev Internal function for reducing onlyMediator modifier bytecode overhead. */ function _onlyMediator() internal view { IAMB bridge = bridgeContract(); require(msg.sender == address(bridge)); require(bridge.messageSender() == mediatorContractOnOtherSide()); } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view virtual returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(Address.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32); } // File: contracts/upgradeable_contracts/components/common/TokensRelayer.sol pragma solidity 0.7.5; /** * @title TokensRelayer * @dev Functionality for bridging multiple tokens to the other side of the bridge. */ abstract contract TokensRelayer is BasicAMBMediator, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC677; /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer( address _from, uint256 _value, bytes memory _data ) external returns (bool) { if (!lock()) { bytes memory data = new bytes(0); address receiver = _from; if (_data.length >= 20) { receiver = Bytes.bytesToAddress(_data); if (_data.length > 20) { assembly { let size := sub(mload(_data), 20) data := add(_data, 20) mstore(data, size) } } } bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, receiver, _value, data); } return true; } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens( IERC677 token, address _receiver, uint256 _value ) external { _relayTokens(token, _receiver, _value, new bytes(0)); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(IERC677 token, uint256 _value) external { _relayTokens(token, msg.sender, _value, new bytes(0)); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. * @param _data additional transfer data to be used on the other side. */ function relayTokensAndCall( IERC677 token, address _receiver, uint256 _value, bytes memory _data ) external { _relayTokens(token, _receiver, _value, _data); } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. * @param _data additional transfer data to be used on the other side. */ function _relayTokens( IERC677 token, address _receiver, uint256 _value, bytes memory _data ) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); uint256 balanceBefore = token.balanceOf(address(this)); setLock(true); token.safeTransferFrom(msg.sender, address(this), _value); setLock(false); uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore); require(balanceDiff <= _value); bridgeSpecificActionsOnTokenTransfer(address(token), msg.sender, _receiver, balanceDiff, _data); } function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _value, bytes memory _data ) internal virtual; } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.7.5; interface VersionableBridge { function getBridgeInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ); function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/components/common/OmnibridgeInfo.sol pragma solidity 0.7.5; /** * @title OmnibridgeInfo * @dev Functionality for versioning Omnibridge mediator. */ contract OmnibridgeInfo is VersionableBridge { event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 value, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure override returns ( uint64 major, uint64 minor, uint64 patch ) { // The patch version increased by 1 to reflect difference from // the original contract: minting of STAKE token is disabled return (3, 0, 1); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure override returns (bytes4 _data) { return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb"))) } } // File: contracts/upgradeable_contracts/components/common/TokensBridgeLimits.sol pragma solidity 0.7.5; /** * @title TokensBridgeLimits * @dev Functionality for keeping track of bridging limits for multiple tokens. */ contract TokensBridgeLimits is EternalStorage, Ownable { using SafeMath for uint256; // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token address is address(0) or token was already bridged. */ function isTokenRegistered(address _token) public view returns (bool) { return minPerTx(_token) > 0; } /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can be sent through the bridge in one transfer. */ function maxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))]; } /** * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can received from the bridge on the other side in one transaction. */ function executionMaxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))]; } /** * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return minimum amount on tokens that can be sent through the bridge in one transfer. */ function minPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be bridged. */ function withinLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount); return dailyLimit(address(0)) > 0 && dailyLimit(_token) >= nextLimit && _amount <= maxPerTx(_token) && _amount >= minPerTx(_token); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount); return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) >= nextLimit && _amount <= executionMaxPerTx(_token); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx; } /** * @dev Updates maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx; } /** * @dev Updates minimum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _minPerTx minimum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit. */ function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token)); uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @param _token address of the token contract, or address(0) for the default limit. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx(address _token) public view returns (uint256) { uint256 _maxPerTx = maxPerTx(_token); uint256 _dailyLimit = dailyLimit(_token); uint256 _spent = totalSpentPerDay(_token, getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalSpentPerDay( address _token, uint256 _day, uint256 _value ) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add( _value ); } /** * @dev Internal function for adding executed amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value ) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay( _token, _day ) .add(_value); } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]. */ function _setLimits(address _token, uint256[3] memory _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1]; uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2]; emit DailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]. */ function _setExecutionLimits(address _token, uint256[2] memory _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing limits for some token relative to its decimals parameter. * @param _token address of the token contract. * @param _decimals token decimals parameter. */ function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal { uint256 factor; if (_decimals < 18) { factor = 10**(18 - _decimals); uint256 _minPerTx = minPerTx(address(0)).div(factor); uint256 _maxPerTx = maxPerTx(address(0)).div(factor); uint256 _dailyLimit = dailyLimit(address(0)).div(factor); uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor); uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor); // such situation can happen when calculated limits relative to the token decimals are too low // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed. // in this case, limits are raised to the default values if (_minPerTx == 0) { // Numbers 1, 100, 10000 are chosen in a semi-random way, // so that any token with small decimals can still be bridged in some amounts. // It is possible to override limits for the particular token later if needed. _minPerTx = 1; if (_maxPerTx <= _minPerTx) { _maxPerTx = 100; _executionMaxPerTx = 100; if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) { _dailyLimit = 10000; _executionDailyLimit = 10000; } } } _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]); _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]); } else { factor = 10**(_decimals - 18); _setLimits( _token, [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)] ); _setExecutionLimits( _token, [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)] ); } } } // File: contracts/upgradeable_contracts/components/common/BridgeOperationsStorage.sol pragma solidity 0.7.5; /** * @title BridgeOperationsStorage * @dev Functionality for storing processed bridged operations. */ abstract contract BridgeOperationsStorage is EternalStorage { /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } } // File: contracts/upgradeable_contracts/components/common/FailedMessagesProcessor.sol pragma solidity 0.7.5; /** * @title FailedMessagesProcessor * @dev Functionality for fixing failed bridging operations. */ abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { IAMB bridge = bridgeContract(); require(!bridge.messageCallStatus(_messageId)); require(bridge.failedMessageReceiver(_messageId) == address(this)); require(bridge.failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); _passMessage(data, true); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } function executeActionOnFixedTokens( address _token, address _recipient, uint256 _value ) internal virtual; } // File: contracts/upgradeability/Proxy.sol 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 Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize()) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize())) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize()) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize()) } default { return(ptr, returndatasize()) } } } } // File: contracts/upgradeable_contracts/modules/factory/TokenProxy.sol pragma solidity 0.7.5; interface IPermittableTokenVersion { function version() external pure returns (string memory); } /** * @title TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract TokenProxy is Proxy { // storage layout is copied from PermittableToken.sol string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr; // string public constant version = "1"; bytes32 internal DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; mapping(address => uint256) internal nonces; mapping(address => mapping(address => uint256)) internal expirations; /** * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _decimals token decimals. * @param _chainId chain id for current network. * @param _owner address of the owner for this contract. */ constructor( address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId, address _owner ) { string memory version = IPermittableTokenVersion(_tokenImage).version(); assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage) } name = _name; symbol = _symbol; decimals = _decimals; owner = _owner; // _owner == HomeOmnibridge/ForeignOmnibridge mediator bridgeContractAddr = _owner; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), _chainId, address(this) ) ); } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return impl token image address. */ function implementation() public view override returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } } } // File: contracts/upgradeable_contracts/modules/OwnableModule.sol pragma solidity 0.7.5; /** * @title OwnableModule * @dev Common functionality for multi-token extension non-upgradeable module. */ contract OwnableModule { address public owner; /** * @dev Initializes this contract. * @param _owner address of the owner that is allowed to perform additional actions on the particular module. */ constructor(address _owner) { owner = _owner; } /** * @dev Throws if sender is not the owner of this contract. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Changes the owner of this contract. * @param _newOwner address of the new owner. */ function transferOwnership(address _newOwner) external onlyOwner { owner = _newOwner; } } // File: contracts/upgradeable_contracts/modules/factory/TokenFactory.sol pragma solidity 0.7.5; /** * @title TokenFactory * @dev Factory contract for deployment of new TokenProxy contracts. */ contract TokenFactory is OwnableModule { address public tokenImage; /** * @dev Initializes this contract * @param _owner of this factory contract. * @param _tokenImage address of the token image contract that should be used for creation of new tokens. */ constructor(address _owner, address _tokenImage) OwnableModule(_owner) { tokenImage = _tokenImage; } /** * @dev Updates the address of the used token image contract. * Only owner can call this method. * @param _tokenImage address of the new token image used for further deployments. */ function setTokenImage(address _tokenImage) external onlyOwner { require(Address.isContract(_tokenImage)); tokenImage = _tokenImage; } /** * @dev Deploys a new TokenProxy contract, using saved token image contract as a template. * @param _name deployed token name. * @param _symbol deployed token symbol. * @param _decimals deployed token decimals. * @param _chainId chain id of the current environment. * @return address of a newly created contract. */ function deploy( string calldata _name, string calldata _symbol, uint8 _decimals, uint256 _chainId ) external returns (address) { return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender)); } } // File: contracts/upgradeable_contracts/modules/factory/TokenFactoryConnector.sol pragma solidity 0.7.5; /** * @title TokenFactoryConnector * @dev Connectivity functionality for working with TokenFactory contract. */ contract TokenFactoryConnector is Ownable { bytes32 internal constant TOKEN_FACTORY_CONTRACT = 0x269c5905f777ee6391c7a361d17039a7d62f52ba9fffeb98c5ade342705731a3; // keccak256(abi.encodePacked("tokenFactoryContract")) /** * @dev Updates an address of the used TokenFactory contract used for creating new tokens. * @param _tokenFactory address of TokenFactory contract. */ function setTokenFactory(address _tokenFactory) external onlyOwner { _setTokenFactory(_tokenFactory); } /** * @dev Retrieves an address of the token factory contract. * @return address of the TokenFactory contract. */ function tokenFactory() public view returns (TokenFactory) { return TokenFactory(addressStorage[TOKEN_FACTORY_CONTRACT]); } /** * @dev Internal function for updating an address of the token factory contract. * @param _tokenFactory address of the deployed TokenFactory contract. */ function _setTokenFactory(address _tokenFactory) internal { require(Address.isContract(_tokenFactory)); addressStorage[TOKEN_FACTORY_CONTRACT] = _tokenFactory; } } // File: contracts/interfaces/IBurnableMintableERC677Token.sol pragma solidity 0.7.5; interface IBurnableMintableERC677Token is IERC677 { function mint(address _to, uint256 _amount) external returns (bool); function burn(uint256 _value) external; function claimTokens(address _token, address _to) external; } // File: contracts/interfaces/IERC20Metadata.sol pragma solidity 0.7.5; interface IERC20Metadata { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/interfaces/IERC20Receiver.sol pragma solidity 0.7.5; interface IERC20Receiver { function onTokenBridged( address token, uint256 value, bytes calldata data ) external; } // File: contracts/libraries/TokenReader.sol pragma solidity 0.7.5; // solhint-disable interface ITokenDetails { function name() external view; function NAME() external view; function symbol() external view; function SYMBOL() external view; function decimals() external view; function DECIMALS() external view; } // solhint-enable /** * @title TokenReader * @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts. */ library TokenReader { /** * @dev Reads the name property of the provided token. * Either name() or NAME() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token name as a string or an empty string if none of the methods succeeded. */ function readName(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.name.selector)); if (!status) { (status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.NAME.selector)); if (!status) { return ""; } } return _convertToString(data); } /** * @dev Reads the symbol property of the provided token. * Either symbol() or SYMBOL() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token symbol as a string or an empty string if none of the methods succeeded. */ function readSymbol(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.symbol.selector)); if (!status) { (status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.SYMBOL.selector)); if (!status) { return ""; } } return _convertToString(data); } /** * @dev Reads the decimals property of the provided token. * Either decimals() or DECIMALS() method is used. * @param _token address of the token contract. * @return token decimals or 0 if none of the methods succeeded. */ function readDecimals(address _token) internal view returns (uint8) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector)); if (!status) { (status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector)); if (!status) { return 0; } } return abi.decode(data, (uint8)); } /** * @dev Internal function for converting returned value of name()/symbol() from bytes32/string to string. * @param returnData data returned by the token contract. * @return string with value obtained from returnData. */ function _convertToString(bytes memory returnData) private pure returns (string memory) { if (returnData.length > 32) { return abi.decode(returnData, (string)); } else if (returnData.length == 32) { bytes32 data = abi.decode(returnData, (bytes32)); string memory res = new string(32); assembly { let len := 0 mstore(add(res, 32), data) // save value in result string // solhint-disable for { } gt(data, 0) { len := add(len, 1) } { // until string is empty data := shl(8, data) // shift left by one symbol } // solhint-enable mstore(res, len) // save result string length } return res; } else { return ""; } } } // File: contracts/libraries/SafeMint.sol pragma solidity 0.7.5; /** * @title SafeMint * @dev Wrapper around the mint() function in all mintable tokens that verifies the return value. */ library SafeMint { /** * @dev Wrapper around IBurnableMintableERC677Token.mint() that verifies that output value is true. * @param _token token contract. * @param _to address of the tokens receiver. * @param _value amount of tokens to mint. */ function safeMint( IBurnableMintableERC677Token _token, address _to, uint256 _value ) internal { require(_token.mint(_to, _value)); } } // File: contracts/upgradeable_contracts/BasicOmnibridge.sol pragma solidity 0.7.5; /** * @title BasicOmnibridge * @dev Common functionality for multi-token mediator intended to work on top of AMB bridge. */ abstract contract BasicOmnibridge is Initializable, Upgradeable, Claimable, OmnibridgeInfo, TokensRelayer, FailedMessagesProcessor, BridgedTokensRegistry, NativeTokensRegistry, MediatorBalanceStorage, TokenFactoryConnector, TokensBridgeLimits { using SafeERC20 for IERC677; using SafeMint for IBurnableMintableERC677Token; using SafeMath for uint256; // Workaround for storing variable up-to-32 bytes suffix uint256 private immutable SUFFIX_SIZE; bytes32 private immutable SUFFIX; // Since contract is intended to be deployed under EternalStorageProxy, only constant and immutable variables can be set here constructor(string memory _suffix) { require(bytes(_suffix).length <= 32); bytes32 suffix; assembly { suffix := mload(add(_suffix, 32)) } SUFFIX = suffix; SUFFIX_SIZE = bytes(_suffix).length; } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly. * @param _token address of the native ERC20/ERC677 token on the other side. * @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function deployAndHandleBridgedTokens( address _token, string calldata _name, string calldata _symbol, uint8 _decimals, address _recipient, uint256 _value ) external onlyMediator { address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals); _handleTokens(bridgedToken, false, _recipient, _value); } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Executes a callback on the receiver. * Checks that the value is inside the execution limits and invokes the Mint accordingly. * @param _token address of the native ERC20/ERC677 token on the other side. * @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. * @param _data additional data passed from the other chain. */ function deployAndHandleBridgedTokensAndCall( address _token, string calldata _name, string calldata _symbol, uint8 _decimals, address _recipient, uint256 _value, bytes calldata _data ) external onlyMediator { address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals); _handleTokens(bridgedToken, false, _recipient, _value); _receiverCallback(_recipient, bridgedToken, _value, _data); } /** * @dev Handles the bridged tokens for the already registered token pair. * Checks that the value is inside the execution limits and invokes the Mint accordingly. * @param _token address of the native ERC20/ERC677 token on the other side. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens( address _token, address _recipient, uint256 _value ) external onlyMediator { address token = bridgedTokenAddress(_token); require(isTokenRegistered(token)); _handleTokens(token, false, _recipient, _value); } /** * @dev Handles the bridged tokens for the already registered token pair. * Checks that the value is inside the execution limits and invokes the Unlock accordingly. * Executes a callback on the receiver. * @param _token address of the native ERC20/ERC677 token on the other side. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. * @param _data additional transfer data passed from the other side. */ function handleBridgedTokensAndCall( address _token, address _recipient, uint256 _value, bytes memory _data ) external onlyMediator { address token = bridgedTokenAddress(_token); require(isTokenRegistered(token)); _handleTokens(token, false, _recipient, _value); _receiverCallback(_recipient, token, _value, _data); } /** * @dev Handles the bridged tokens that are native to this chain. * Checks that the value is inside the execution limits and invokes the Unlock accordingly. * @param _token native ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleNativeTokens( address _token, address _recipient, uint256 _value ) external onlyMediator { _ackBridgedTokenDeploy(_token); _handleTokens(_token, true, _recipient, _value); } /** * @dev Handles the bridged tokens that are native to this chain. * Checks that the value is inside the execution limits and invokes the Unlock accordingly. * Executes a callback on the receiver. * @param _token native ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. * @param _data additional transfer data passed from the other side. */ function handleNativeTokensAndCall( address _token, address _recipient, uint256 _value, bytes memory _data ) external onlyMediator { _ackBridgedTokenDeploy(_token); _handleTokens(_token, true, _recipient, _value); _receiverCallback(_recipient, _token, _value, _data); } /** * @dev Checks if a given token is a bridged token that is native to this side of the bridge. * @param _token address of token contract. * @return message id of the send message. */ function isRegisteredAsNativeToken(address _token) public view returns (bool) { return isTokenRegistered(_token) && nativeTokenAddress(_token) == address(0); } /** * @dev Unlock back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens( address _token, address _recipient, uint256 _value ) internal override { _releaseTokens(nativeTokenAddress(_token) == address(0), _token, _recipient, _value, _value); } /** * @dev Allows to pre-set the bridged token contract for not-yet bridged token. * Only the owner can call this method. * @param _nativeToken address of the token contract on the other side that was not yet bridged. * @param _bridgedToken address of the bridged token contract. */ function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner { require(!isTokenRegistered(_bridgedToken)); require(nativeTokenAddress(_bridgedToken) == address(0)); require(bridgedTokenAddress(_nativeToken) == address(0)); // Unfortunately, there is no simple way to verify that the _nativeToken address // does not belong to the bridged token on the other side, // since information about bridged tokens addresses is not transferred back. // Therefore, owner account calling this function SHOULD manually verify on the other side of the bridge that // nativeTokenAddress(_nativeToken) == address(0) && isTokenRegistered(_nativeToken) == false. IBurnableMintableERC677Token(_bridgedToken).safeMint(address(this), 1); IBurnableMintableERC677Token(_bridgedToken).burn(1); _setTokenAddressPair(_nativeToken, _bridgedToken); } /** * @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract * without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer) * @param _token address of the token contract. * Before calling this method, it must be carefully investigated how imbalance happened * in order to avoid an attempt to steal the funds from a token with double addresses * (e.g. TUSD is accessible at both 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E and 0x0000000000085d4780B73119b644AE5ecd22b376) * @param _receiver the address that will receive the tokens on the other network. */ function fixMediatorBalance(address _token, address _receiver) external onlyIfUpgradeabilityOwner validAddress(_receiver) { require(isRegisteredAsNativeToken(_token)); uint256 balance = IERC677(_token).balanceOf(address(this)); uint256 expectedBalance = mediatorBalance(_token); require(balance > expectedBalance); uint256 diff = balance - expectedBalance; uint256 available = maxAvailablePerTx(_token); require(available > 0); if (diff > available) { diff = available; } addTotalSpentPerDay(_token, getCurrentDay(), diff); bytes memory data = _prepareMessage(address(0), _token, _receiver, diff, new bytes(0)); bytes32 _messageId = _passMessage(data, true); _recordBridgeOperation(_messageId, _token, _receiver, diff); } /** * @dev Claims stuck tokens. Only unsupported tokens can be claimed. * When dealing with already supported tokens, fixMediatorBalance can be used instead. * @param _token address of claimed token, address(0) for native * @param _to address of tokens receiver */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Only unregistered tokens and native coins are allowed to be claimed with the use of this function require(_token == address(0) || !isTokenRegistered(_token)); claimValues(_token, _to); } /** * @dev Withdraws erc20 tokens or native coins from the bridged token contract. * Only the proxy owner is allowed to call this method. * @param _bridgedToken address of the bridged token contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokensFromTokenContract( address _bridgedToken, address _token, address _to ) external onlyIfUpgradeabilityOwner { IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to); } /** * @dev Internal function for recording bridge operation for further usage. * Recorded information is used for fixing failed requests on the other side. * @param _messageId id of the sent message. * @param _token bridged token address. * @param _sender address of the tokens sender. * @param _value bridged value. */ function _recordBridgeOperation( bytes32 _messageId, address _token, address _sender, uint256 _value ) internal { setMessageToken(_messageId, _token); setMessageRecipient(_messageId, _sender); setMessageValue(_messageId, _value); emit TokensBridgingInitiated(_token, _sender, _value, _messageId); } /** * @dev Constructs the message to be sent to the other side. Burns/locks bridged amount of tokens. * @param _nativeToken address of the native token contract. * @param _token bridged token address. * @param _receiver address of the tokens receiver on the other side. * @param _value bridged value. * @param _data additional transfer data passed from the other side. */ function _prepareMessage( address _nativeToken, address _token, address _receiver, uint256 _value, bytes memory _data ) internal returns (bytes memory) { bool withData = _data.length > 0 || msg.sig == this.relayTokensAndCall.selector; // process token is native with respect to this side of the bridge if (_nativeToken == address(0)) { _setMediatorBalance(_token, mediatorBalance(_token).add(_value)); // process token which bridged alternative was already ACKed to be deployed if (isBridgedTokenDeployAcknowledged(_token)) { return withData ? abi.encodeWithSelector( this.handleBridgedTokensAndCall.selector, _token, _receiver, _value, _data ) : abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value); } uint8 decimals = TokenReader.readDecimals(_token); string memory name = TokenReader.readName(_token); string memory symbol = TokenReader.readSymbol(_token); require(bytes(name).length > 0 || bytes(symbol).length > 0); return withData ? abi.encodeWithSelector( this.deployAndHandleBridgedTokensAndCall.selector, _token, name, symbol, decimals, _receiver, _value, _data ) : abi.encodeWithSelector( this.deployAndHandleBridgedTokens.selector, _token, name, symbol, decimals, _receiver, _value ); } // process already known token that is bridged from other chain IBurnableMintableERC677Token(_token).burn(_value); return withData ? abi.encodeWithSelector( this.handleNativeTokensAndCall.selector, _nativeToken, _receiver, _value, _data ) : abi.encodeWithSelector(this.handleNativeTokens.selector, _nativeToken, _receiver, _value); } /** * @dev Internal function for getting minter proxy address. * @param _token address of the token to mint. * @return address of the minter contract that should be used for calling mint(address,uint256) */ function _getMinterFor(address _token) internal pure virtual returns (IBurnableMintableERC677Token) { return IBurnableMintableERC677Token(_token); } /** * Internal function for unlocking some amount of tokens. * @param _isNative true, if token is native w.r.t. to this side of the bridge. * @param _token address of the token contract. * @param _recipient address of the tokens receiver. * @param _value amount of tokens to unlock. * @param _balanceChange amount of balance to subtract from the mediator balance. */ function _releaseTokens( bool _isNative, address _token, address _recipient, uint256 _value, uint256 _balanceChange ) internal virtual { if (_isNative) { IERC677(_token).safeTransfer(_recipient, _value); _setMediatorBalance(_token, mediatorBalance(_token).sub(_balanceChange)); } else { _getMinterFor(_token).safeMint(_recipient, _value); } } /** * Internal function for getting address of the bridged token. Deploys new token if necessary. * @param _token address of the token contract on the other side of the bridge. * @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. */ function _getBridgedTokenOrDeploy( address _token, string calldata _name, string calldata _symbol, uint8 _decimals ) internal returns (address) { address bridgedToken = bridgedTokenAddress(_token); if (bridgedToken == address(0)) { string memory name = _name; string memory symbol = _symbol; require(bytes(name).length > 0 || bytes(symbol).length > 0); if (bytes(name).length == 0) { name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } name = _transformName(name); bridgedToken = tokenFactory().deploy(name, symbol, _decimals, bridgeContract().sourceChainId()); _setTokenAddressPair(_token, bridgedToken); _initializeTokenBridgeLimits(bridgedToken, _decimals); } else if (!isTokenRegistered(bridgedToken)) { require(IERC20Metadata(bridgedToken).decimals() == _decimals); _initializeTokenBridgeLimits(bridgedToken, _decimals); } return bridgedToken; } /** * Notifies receiving contract about the completed bridging operation. * @param _recipient address of the tokens receiver. * @param _token address of the bridged token. * @param _value amount of tokens transferred. * @param _data additional data passed to the callback. */ function _receiverCallback( address _recipient, address _token, uint256 _value, bytes memory _data ) internal { if (Address.isContract(_recipient)) { _recipient.call(abi.encodeWithSelector(IERC20Receiver.onTokenBridged.selector, _token, _value, _data)); } } /** * @dev Internal function for transforming the bridged token name. Appends a side-specific suffix. * @param _name bridged token from the other side. * @return token name for this side of the bridge. */ function _transformName(string memory _name) internal view returns (string memory) { string memory result = string(abi.encodePacked(_name, SUFFIX)); uint256 size = SUFFIX_SIZE; assembly { mstore(result, add(mload(_name), size)) } return result; } function _handleTokens( address _token, bool _isNative, address _recipient, uint256 _value ) internal virtual; } // File: contracts/upgradeable_contracts/components/common/GasLimitManager.sol pragma solidity 0.7.5; /** * @title GasLimitManager * @dev Functionality for determining the request gas limit for AMB execution. */ abstract contract GasLimitManager is BasicAMBMediator { bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Sets the default gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _gasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _gasLimit) external onlyOwner { _setRequestGasLimit(_gasLimit); } /** * @dev Tells the default gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _gasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _gasLimit) internal { require(_gasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _gasLimit; } } // File: contracts/upgradeable_contracts/ForeignOmnibridge.sol pragma solidity 0.7.5; /** * @title ForeignOmnibridge * @dev Foreign side implementation for multi-token mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignOmnibridge is BasicOmnibridge, GasLimitManager { using SafeERC20 for IERC677; using SafeMint for IBurnableMintableERC677Token; using SafeMath for uint256; constructor(string memory _suffix) BasicOmnibridge(_suffix) {} /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _tokenFactory address of the TokenFactory contract that will be used for the deployment of new tokens. */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] calldata _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] calldata _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner, address _tokenFactory ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenFactory(_tokenFactory); setInitialize(); return isInitialized(); } /** * One-time function to be used together with upgradeToAndCall method. * Sets the token factory contract. * @param _tokenFactory address of the deployed TokenFactory contract. */ function upgradeToReverseMode(address _tokenFactory) external { require(msg.sender == address(this)); _setTokenFactory(_tokenFactory); } /** * @dev Handles the bridged tokens. * Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly. * @param _token token contract address on this side of the bridge. * @param _isNative true, if given token is native to this chain and Unlock should be used. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function _handleTokens( address _token, bool _isNative, address _recipient, uint256 _value ) internal override { // prohibit withdrawal of tokens during other bridge operations (e.g. relayTokens) // such reentrant withdrawal can lead to an incorrect balanceDiff calculation require(!lock()); require(withinExecutionLimit(_token, _value)); addTotalExecutedPerDay(_token, getCurrentDay(), _value); _releaseTokens(_isNative, _token, _recipient, _value, _value); emit TokensBridged(_token, _recipient, _value, messageId()); } /** * @dev Executes action on deposit of bridged tokens * @param _token address of the token contract * @param _from address of tokens sender * @param _receiver address of tokens receiver on the other side * @param _value requested amount of bridged tokens * @param _data additional transfer data to be used on the other side */ function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _value, bytes memory _data ) internal virtual override { require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide()); // native unbridged token if (!isTokenRegistered(_token)) { uint8 decimals = TokenReader.readDecimals(_token); _initializeTokenBridgeLimits(_token, decimals); } require(withinLimit(_token, _value)); addTotalSpentPerDay(_token, getCurrentDay(), _value); bytes memory data = _prepareMessage(nativeTokenAddress(_token), _token, _receiver, _value, _data); bytes32 _messageId = _passMessage(data, true); _recordBridgeOperation(_messageId, _token, _from, _value); } /** * Internal function for unlocking some amount of tokens. * @param _isNative true, if token is native w.r.t. to this side of the bridge. * @param _token address of the token contract. * @param _recipient address of the tokens receiver. * @param _value amount of tokens to unlock. * @param _balanceChange amount of balance to subtract from the mediator balance. */ function _releaseTokens( bool _isNative, address _token, address _recipient, uint256 _value, uint256 _balanceChange ) internal override { if (_isNative) { uint256 balance = mediatorBalance(_token); // if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) { // IBurnableMintableERC677Token(_token).safeMint(address(this), _value - balance); // balance = _value; // } _setMediatorBalance(_token, balance.sub(_balanceChange)); IERC677(_token).safeTransfer(_recipient, _value); } else { _getMinterFor(_token).safeMint(_recipient, _value); } } /** * @dev Internal function for sending an AMB message to the mediator on the other side. * @param _data data to be sent to the other side of the bridge. * @param _useOracleLane always true, not used on this side of the bridge. * @return id of the sent message. */ function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) { (_useOracleLane); return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit()); } }
* @title FailedMessagesProcessor @dev Functionality for fixing failed bridging operations./
abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); function requestFailedMessageFix(bytes32 _messageId) external { IAMB bridge = bridgeContract(); require(!bridge.messageCallStatus(_messageId)); require(bridge.failedMessageReceiver(_messageId) == address(this)); require(bridge.failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); _passMessage(data, true); } function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } }
2,001,556
[ 1, 2925, 5058, 5164, 225, 4284, 7919, 364, 28716, 2535, 324, 1691, 1998, 5295, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 11175, 5058, 5164, 353, 7651, 2192, 38, 13265, 10620, 16, 24219, 9343, 3245, 288, 203, 565, 871, 11175, 1079, 7505, 12, 3890, 1578, 8808, 19090, 16, 1758, 1147, 16, 1758, 8027, 16, 2254, 5034, 460, 1769, 203, 203, 203, 565, 445, 590, 2925, 1079, 8585, 12, 3890, 1578, 389, 2150, 548, 13, 3903, 288, 203, 3639, 9983, 38, 10105, 273, 10105, 8924, 5621, 203, 3639, 2583, 12, 5, 18337, 18, 2150, 1477, 1482, 24899, 2150, 548, 10019, 203, 3639, 2583, 12, 18337, 18, 7307, 1079, 12952, 24899, 2150, 548, 13, 422, 1758, 12, 2211, 10019, 203, 3639, 2583, 12, 18337, 18, 7307, 1079, 12021, 24899, 2150, 548, 13, 422, 6735, 10620, 8924, 1398, 8290, 8895, 10663, 203, 203, 3639, 1731, 24, 707, 4320, 273, 333, 18, 904, 2925, 1079, 18, 9663, 31, 203, 3639, 1731, 3778, 501, 273, 24126, 18, 3015, 1190, 4320, 12, 2039, 4320, 16, 389, 2150, 548, 1769, 203, 3639, 389, 5466, 1079, 12, 892, 16, 638, 1769, 203, 565, 289, 203, 203, 565, 445, 2917, 2925, 1079, 12, 3890, 1578, 389, 2150, 548, 13, 1071, 1338, 13265, 10620, 288, 203, 3639, 2583, 12, 5, 2150, 7505, 24899, 2150, 548, 10019, 203, 203, 3639, 1758, 1147, 273, 883, 1345, 24899, 2150, 548, 1769, 203, 3639, 1758, 8027, 273, 883, 18241, 24899, 2150, 548, 1769, 203, 3639, 2254, 5034, 460, 273, 883, 620, 24899, 2150, 548, 1769, 203, 3639, 15227, 7505, 24899, 2150, 548, 1769, 203, 3639, 1836, 1803, 1398, 7505, 5157, 12, 2316, 16, 8027, 16, 460, 1769, 203, 2 ]
./full_match/1/0x622A9Ff8f826AE7d25Cfedd41bbe86Ea159B4D0e/sources/contracts/v2/MintStages/FairxyzMintStagesRegistry.sol
@custom:oz-upgrades-unsafe-allow state-variable-immutable @dev map scheduleId to stages @dev map scheduleId to stages count
modifier onlyRegistrant(address registrant) { if (msg.sender != registrant) revert Unauthorized(); _; }
8,438,829
[ 1, 36, 3662, 30, 11142, 17, 416, 13088, 17, 318, 4626, 17, 5965, 919, 17, 6105, 17, 381, 5146, 225, 852, 4788, 548, 358, 20298, 225, 852, 4788, 548, 358, 20298, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 20175, 970, 12, 2867, 17450, 970, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 17450, 970, 13, 15226, 15799, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-19 */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.2; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/math/SafeMath.sol // CAUTION - only use with Solidity 0.8 + /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/IERC20.sol /** * @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); } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title DEXStream.io Token * @author JP * @dev Implementation of the DEXStream.io Token */ contract DEXStreamToken is ERC20, Ownable { uint256 private _cSBlock; // Claim startblock uint256 private _cEBlock; // Claim endblock uint256 private _cAmount; // Claim amount uint256 private _cCap; // Claim count cap (<1000) uint256 private _cCount; // Current claim count uint256 private _sSBlock; // Sale startblock uint256 private _sEBlock; // Sale endblock uint256 private _sTokensPerEth; // amount of tokers to get per eth uint256 private _sCap; // Sale count cap uint256 private _sCount; // Current sale count /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param initialSupply Initial token supply */ constructor( string memory name, string memory symbol, uint256 initialSupply ) ERC20(name, symbol) { if (initialSupply > 0) { _mint(owner(), initialSupply); } } function cSBlock() public view virtual returns (uint256) { return _cSBlock; } function cEBlock() public view virtual returns (uint256) { return _cEBlock; } function cAmount()public view virtual returns (uint256) { return _cAmount; } function cCap() public view virtual returns (uint256) { return _cCap; } function cCount() public view virtual returns (uint256) { return _cCount; } function startClaimPeriod(uint256 startBlock, uint256 endBlock, uint256 amount,uint256 cap) public onlyOwner() { _cSBlock = startBlock; _cEBlock = endBlock; _cAmount = amount; _cCap = cap; _cCount = 0; } function claim(address refer) public returns (bool success){ require(_cSBlock <= block.number && block.number <= _cEBlock, "Claim period not active"); require(_cCount < _cCap || _cCap == 0, "All is claimed"); _cCount ++; if(msg.sender != refer && balanceOf(refer) != 0 && refer != 0x0000000000000000000000000000000000000000){ _transfer(address(this), refer, _cAmount); } _transfer(address(this), msg.sender, _cAmount); return true; } function viewClaimPeriod() public view returns(uint256 startBlock, uint256 endBlock, uint256 amount, uint256 cap, uint256 count){ return(_cSBlock, _cEBlock, _cAmount, _cCap, _cCount); } function sSBlock() public view virtual returns (uint256) { return _sSBlock; } function sEBlock() public view virtual returns (uint256) { return _sEBlock; } function sTokensPerEth()public view virtual returns (uint256) { return _sTokensPerEth; } function sCap() public view virtual returns (uint256) { return _sCap; } function sCount() public view virtual returns (uint256) { return _sCount; } function startSale(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap) public onlyOwner() { _sSBlock = startBlock; _sEBlock = endBlock; _sTokensPerEth = tokensPerEth; _sCap = cap; _sCount = 0; } function buyTokens() public payable returns (bool success){ require(_sSBlock <= block.number && block.number <= _sEBlock, "Sale not active"); require(_sCount < _sCap || _sCap == 0, "Max sale participants reached, sale is over"); uint256 _eth = msg.value; uint256 _tokens; _tokens = _eth * _sTokensPerEth; require(_tokens <= balanceOf(address(this)), "Insufficient tokens avaialble for eth amount, try with less eth"); _sCount ++; _transfer(address(this), msg.sender, _tokens); return true; } function viewSale() public view returns(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap, uint256 count){ return(_sSBlock, _sEBlock, _sTokensPerEth,_sCap, _sCount); } function withdrawal() public onlyOwner() { address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); } receive() external payable { } }
Current sale count
uint256 private _sCount;
2,032,354
[ 1, 3935, 272, 5349, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 87, 1380, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /** * For convenience, you can delete all of the code between the <ORACLIZE_API> * and </ORACLIZE_API> tags as etherscan cannot use the import callback, you * can then just uncomment the line below and compile it via Remix. */ //import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> /*===========================================================================================* *************************************** https://p4d.io *************************************** *============================================================================================* * * ,-.----. ,--, * \ / \ ,--.'| ,---, * | : \ ,--, | : .' .' `\ ____ __ * | | .\ :,---.'| : ',---.' \ / __ \________ ________ ____ / /______ * . : |: |; : | | ;| | .`\ | / /_/ / ___/ _ \/ ___/ _ \/ __ \/ __/ ___/ * | | \ :| | : _' |: : | ' | / ____/ / / __(__ ) __/ / / / /_(__ ) * | : . /: : |.' || ' ' ; : /_/ /_/___\\\_/____/\_\\/_\_/_/\__/____/ * ; | |`-' | ' ' ; :' | ; . | /_ __/___ \ \/ /___ __ __ * | | ; \ \ .'. || | : | ' / / / __ \ \ / __ \/ / / / * : ' | `---`: | '' : | / ; / / / /_/ / / / /_/ / /_/ / * : : : ' ; || | '` ,/ /_/ \____/ /_/\____/\__,_/ * | | : | : ;; : .' * `---'.| ' ,/ | ,.' * `---` '--' '---' * * _______ _ _____ _ * (_______) | (____ \ | |_ * _____ | |_ _ _ _ _ \ \ ____| | |_ ____ * | ___) | | | | ( \ / ) | | / _ ) | _)/ _ | * | | | | |_| |) X (| |__/ ( (/ /| | |_( ( | | * |_| |_|\____(_/ \_)_____/ \____)_|\___)_||_| * * ____ * /\ \ * / \ \ * / \ \ * / \ \ * / /\ \ \ * / / \ \ \ * / / \ \ \ * / / / \ \ \ * / / / \ \ \ * / / /---------' \ * / / /_______________\ * \ / / * \/_____________________/ * _ ___ _ _ ___ * /_\ / __\___ _ __ | |_ _ __ __ _ ___| |_ / __\_ _ * //_\\ / / / _ \| '_ \| __| '__/ _` |/ __| __| /__\// | | | * / _ \ / /__| (_) | | | | |_| | | (_| | (__| |_ / \/ \ |_| | * \_/ \_/ \____/\___/|_| |_|\__|_| \__,_|\___|\__| \_____/\__, | * ╔═╗╔═╗╦ ╔╦╗╔═╗╦ ╦ |___/ * ╚═╗║ ║║ ║║║╣ ╚╗╔╝ * ╚═╝╚═╝╩═╝────═╩╝╚═╝ ╚╝ * 0x736f6c5f646576 * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * */ // P3D interface interface P3D { function sell(uint256) external; function myTokens() external view returns(uint256); function myDividends(bool) external view returns(uint256); function withdraw() external; } // P4D interface interface P4D { function buy(address) external payable returns(uint256); function sell(uint256) external; function transfer(address, uint256) external returns(bool); function myTokens() external view returns(uint256); function myStoredDividends() external view returns(uint256); function mySubdividends() external view returns(uint256); function withdraw(bool) external; function withdrawSubdivs(bool) external; function P3D_address() external view returns(address); function setCanAcceptTokens(address) external; } /** * An inheritable contract structure that connects to the P4D exchange * This will then point to the P3D exchange as well as providing the tokenCallback() function */ contract usingP4D { P4D internal tokenContract; P3D internal _P3D; function usingP4D(address _P4D_address) public { tokenContract = P4D(_P4D_address); _P3D = P3D(tokenContract.P3D_address()); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); } /** * This is the coin-pair contract, the main FluxDelta contract will create a new coin-pair * contract every time a pairing is added to the network. The FluxDelta contract is be able * to manage the coin-pair in respect to setting its UI visibility as well as the coin-pairs * callback gas price in case the network gets congested. * Each coin-pair contract is self-managing and has its own P4D, P3D and ETH balances. In * order to keep affording to pay for Oraclize calls, it will always maintain a certain * amount of ETH and should it drop beneath a certain threshold, it will sell some of the * P3D that it holds. If it has a surplus of ETH, it will use the excess to purchase more * P4D that will go towards the global withdrawable pot. * A user can invest into a coin-pair via the P4D exchange contract using the transferAndCall() * function and they can withdraw their P4D shares via the main FluxDelta contract using the * withdrawFromCoinPair() function. */ contract CoinPair is usingP4D, usingOraclize { using SafeMath for uint256; struct OraclizeMap { address _sender; bool _isNextShort; uint256 _sentValue; } mapping(bytes32 => OraclizeMap) private _oraclizeCallbackMap; event RequestSubmitted(bytes32 id); uint256 constant private _devOwnerCut = 1; // 1% of deposits are used as dev fees uint256 constant private _minDeposit = 100e18; // we need to cover Oraclize at a bare minimum uint256 constant private _sellThreshold = 0.1 ether; // if the balance drops below this, sell P4D uint256 constant private _buyThreshold = 0.2 ether; // if the balance goes above this, buy P4D int256 constant private _baseSharesPerRequest = 1e18; // 1% * 100e18 address private _dev; // main developer; will receive 0.5% of P4D deposits address private _owner; // a nominated owner; they will also receive 0.5% of the depost address private _creator; // the parent FluxDelta contract uint256 private _devBalance = 0; uint256 private _ownerBalance = 0; uint256 private _processingP4D = 0; bytes32 public fSym; bytes32 public tSym; uint256 constant public baseCost = 100e18; // 100 P4D tokens uint256 public shares; mapping(address => uint256) public sharesOf; mapping(address => uint256) public scalarOf; mapping(address => bool) public isShorting; mapping(address => uint256) public lastPriceOf; mapping(address => uint256) public lastPriceTimeOf; bool public isVisible; /** * Modifier for restricting a call to just the FluxDelta contract */ modifier onlyCreator { require(msg.sender == _creator); _; } /** * Coin-pair constructor; * _fSym: From symbol (eg ETH) * _tSym: To symbol (eg USD) * _ownerAddress: Nominated owner, will receive 0.5% of all deposits * _devAddress: FluxDelta dev, will also receive 0.5% of all deposits * _P4D_address: P4D exchange address reference */ function CoinPair(string _fSym, string _tSym, address _ownerAddress, address _devAddress, address _P4D_address) public payable usingP4D(_P4D_address) { require (msg.value >= _sellThreshold); require(_ownerAddress != _devAddress && _ownerAddress != msg.sender && _devAddress != msg.sender); _creator = msg.sender; fSym = _stringToBytes32(_fSym); tSym = _stringToBytes32(_tSym); shares = 0; _owner = _ownerAddress; _dev = _devAddress; isVisible = true; changeOraclizeGasPrice(16e9); // 16 Gwei for all callbacks } /** * Main point of interaction within a coin-pair, the P4D contract will call this function * after a customer has sent P4D using the transferAndCall() function to this address. * This function sets up all of the required information in order to make a call to the * internet via Oraclize, this will fetch the current price of the coin-pair without needing * to worry about a user tampering with the data. * Oraclize is a paid service and requires ETH to use, this contract must pay a fee for the * internet call itself as well as the gas cost to cover the __callback() function below. */ function tokenCallback(address _from, uint256 _value, bytes _data) external onlyTokenContract returns (bool) { require(_value >= _minDeposit); require(!_isContract(_from)); require(_from != _dev && _from != _owner && _from != _creator); uint256 fees = _value.mul(_devOwnerCut).div(100); // 1% _devBalance = _devBalance.add(fees.div(2)); // 0.5% _ownerBalance = _ownerBalance.add(fees.div(2)); // 0.5% _processingP4D = _processingP4D.add(_value); ///////////////////////////////////////////////////////////////////////////////// // // The block of code below is responsible for using all of the P4D and P3D // dividends in order to both maintain and afford to pay for Oraclize calls // as well as purchasing more P4D to put towards the global pot should there // be an excess of ETH // // first withdraw all ETH subdividends from the P4D contract if (tokenContract.mySubdividends() > 0) { tokenContract.withdrawSubdivs(true); } // if this contracts ETH balance is less than the threshold, sell a minimum // P4D deposit (100 P4D) then sell 1/4 of all the held P3D in this contract // // if this contracts ETH balance is more than the buying threshold, use this // excess ETH to purchase more P4D to put in the global withdrawable pot if (address(this).balance < _sellThreshold) { tokenContract.sell(_minDeposit); tokenContract.withdraw(true); _P3D.sell(_P3D.myTokens().div(4)); // sell 1/4 of all P3D held by the contract } else if (address(this).balance > _buyThreshold) { uint256 diff = address(this).balance.sub(_buyThreshold); tokenContract.buy.value(diff)(_owner); // use the owner as a ref } // if there's any stored P3D dividends, withdraw and hold them if (tokenContract.myStoredDividends() > 0) { tokenContract.withdraw(true); } // finally, check if there's any ETH divs to withdraw from the P3D contract if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } ///////////////////////////////////////////////////////////////////////////////// uint256 gasLimit = 220000; if (lastPriceOf[_from] != 0) { gasLimit = 160000; require(_value.mul(1e18).div(baseCost) == scalarOf[_from]); // check if they sent the right amount } // parse the URL data for Oraclize string memory tSymString = strConcat("&tsyms=", _bytes32ToString(tSym), ").", _bytes32ToString(tSym)); bytes32 queryId = oraclize_query("URL", strConcat("json(https://min-api.cryptocompare.com/data/price?fsym=", _bytes32ToString(fSym), tSymString), gasLimit); uint256 intData = _bytesToUint(_data); OraclizeMap memory map = OraclizeMap({ _sender: _from, _isNextShort: intData != 0, _sentValue: _value }); _oraclizeCallbackMap[queryId] = map; RequestSubmitted(queryId); return true; } /** * Oraclize callback function for returning data */ function __callback(bytes32 myid, string result) public { require(msg.sender == oraclize_cbAddress()); _handleCallback(myid, result); } /** * Internally handled callback, this function is responsible for updating the shares gained/lost * of a user once they've invested in a coin-pair. If you have already invested in the coin-pair * before, this will compare your last locked in price to the current price and provide you shares * based on the gain/loss of the coin-pair (as well as being multiplied by your staked P4D amount). */ function _handleCallback(bytes32 _id, string _result) internal { OraclizeMap memory mappedInfo = _oraclizeCallbackMap[_id]; address receiver = mappedInfo._sender; require(receiver != address(0x0)); int256 latestPrice = int256(parseInt(_result, 18)); // 18 decimal places if (latestPrice > 0) { int256 lastPrice = int256(lastPriceOf[receiver]); if (lastPrice == 0) { // we are starting from the beginning lastPriceTimeOf[receiver] = now; lastPriceOf[receiver] = uint256(latestPrice); scalarOf[receiver] = mappedInfo._sentValue.mul(1e18).div(baseCost); sharesOf[receiver] = uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18; isShorting[receiver] = mappedInfo._isNextShort; shares = shares.add(uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18); } else { // they already have a price recorded so find the gain/loss if (mappedInfo._sentValue.mul(1e18).div(baseCost) == scalarOf[receiver]) { int256 delta = _baseSharesPerRequest + ((isShorting[receiver] ? int256(-1) : int256(1)) * ((100e18 * (latestPrice - lastPrice)) / lastPrice)); // in terms of % (18 decimals) + base gain (+1%) delta = delta * int256(scalarOf[receiver]) / int256(1e18); int256 currentShares = int256(sharesOf[receiver]); if (currentShares + delta > _baseSharesPerRequest * int256(scalarOf[receiver]) / int256(1e18)) { sharesOf[receiver] = uint256(currentShares + delta); } else { sharesOf[receiver] = uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18; } lastPriceTimeOf[receiver] = now; lastPriceOf[receiver] = uint256(latestPrice); isShorting[receiver] = mappedInfo._isNextShort; shares = uint256(int256(shares) + int256(sharesOf[receiver]) - currentShares); } else { // something strange has happened so refund the P4D require(tokenContract.transfer(receiver, mappedInfo._sentValue)); } } } else { // price returned an error so refund the P4D require(tokenContract.transfer(receiver, mappedInfo._sentValue)); } _processingP4D = _processingP4D.sub(mappedInfo._sentValue); delete _oraclizeCallbackMap[_id]; } /** * Should there be any problems with Oraclize such as a callback running out of gas or * reverting, you are able to refund the P4D you sent to the contract. This will only * work if the __callback() function has not been successful. */ function requestRefund(bytes32 _id) external { OraclizeMap memory mappedInfo = _oraclizeCallbackMap[_id]; address receiver = mappedInfo._sender; require(msg.sender == receiver); uint256 refundable = mappedInfo._sentValue; _processingP4D = _processingP4D.sub(refundable); delete _oraclizeCallbackMap[_id]; require(tokenContract.transfer(receiver, refundable)); } /** * Liquidate your shares to P4D */ function withdraw(address _user) external onlyCreator { uint256 withdrawableP4D = getWithdrawableOf(_user); if (withdrawableP4D > 0) { if (_user == _dev) { _devBalance = 0; } else if (_user == _owner) { _ownerBalance = 0; } else { shares = shares.sub(sharesOf[_user]); sharesOf[_user] = 0; scalarOf[_user] = 0; lastPriceOf[_user] = 0; lastPriceTimeOf[_user] = 0; } require(tokenContract.transfer(_user, withdrawableP4D)); } else if (sharesOf[_user] == 0) { // they are restarting scalarOf[_user] = 0; lastPriceOf[_user] = 0; lastPriceTimeOf[_user] = 0; } } /** * Change the UI visibility of the coin-pair * Although a coin-pair may be hidden, a customer can still interact with it without restrictions */ function setVisibility(bool _isVisible) external onlyCreator { isVisible = _isVisible; } /** * Ability to change the gas price for callbacks in case the network becomes congested */ function changeOraclizeGasPrice(uint256 _gasPrice) public onlyCreator { oraclize_setCustomGasPrice(_gasPrice); } /** * Retrieve the total withdrawable P4D pot */ function getTotalPot() public view returns (uint256) { return tokenContract.myTokens().sub(_devBalance).sub(_ownerBalance).sub(_processingP4D.mul(uint256(100).sub(_devOwnerCut)).div(100)); } /** * Retrieve the total withdrawable P4D of an individual customer */ function getWithdrawableOf(address _user) public view returns (uint256) { if (_user == _dev) { return _devBalance; } else if (_user == _owner) { return _ownerBalance; } else { return (shares == 0 ? 0 : getTotalPot().mul(sharesOf[_user]).div(shares)); } } /** * Utility function to convert strings into fixed length byte arrays */ function _stringToBytes32(string memory _s) internal pure returns (bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility function to make bytes32 data readable */ function _bytes32ToString(bytes32 _b) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } /** * Utility function to convert bytes into an integer */ function _bytesToUint(bytes _b) internal pure returns (uint256 result) { result = 0; for (uint i = 0; i < _b.length; i++) { result += uint(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } } /** * Utility function to check if an address is a contract */ function _isContract(address _a) internal view returns (bool) { uint size; assembly { size := extcodesize(_a) } return size > 0; } /** * Payable function for receiving dividends from the P4D and P3D contracts */ function () public payable { require(msg.sender == address(tokenContract) || msg.sender == address(_P3D) || msg.sender == _dev || msg.sender == _owner); // only accept ETH payments from P4D and P3D (subdividends and dividends) as well // as allowing the owner or dev to top up this contracts balance // // all ETH sent through this function will be used in the tokenCallback() function // in order to buy more P4D (if there's excess) and pay for Oraclize calls } } /** * This is the core FluxDelta contract, it is primarily a contract factory that * is able to create any number of coin-pair sub-contracts. On top of this, it is * also used as an efficient way to return all of the data needed for the front-end. */ contract FluxDelta is usingP4D { using SafeMath for uint256; CoinPair[] private _coinPairs; address private _owner; modifier onlyOwner { require(msg.sender == _owner); _; } /** * Application entry point */ function FluxDelta(address _P4D_address) public usingP4D(_P4D_address) { _owner = msg.sender; } /** * Coin-pair creation function, this function will also allow this newly created pair to receive P4D * tokens via the setCanAcceptTokens() function. This means that the FluxDetla contract will be * granted administrator permissions in the P4D contract although this is the only method it uses. */ function createCoinPair(string _fromSym, string _toSym, address _ownerAddress) external payable onlyOwner { CoinPair newCoinPair = (new CoinPair).value(msg.value)(_fromSym, _toSym, _ownerAddress, _owner, address(tokenContract)); _coinPairs.push(newCoinPair); tokenContract.setCanAcceptTokens(address(newCoinPair)); } /** * Liquidates your shares to P4D from a certain coin-pair */ function withdrawFromCoinPair(uint256 _index) external { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.withdraw(msg.sender); } /** * Ability to toggle the UI visibility of a coin-pair * This will not prevent a coin-pair from being able to invest or withdraw */ function setCoinPairVisibility(uint256 _index, bool _isVisible) external onlyOwner { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.setVisibility(_isVisible); } /** * Ability to change the callback gas price in case the network gets congested */ function setCoinPairOraclizeGasPrice(uint256 _index, uint256 _gasPrice) public onlyOwner { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.changeOraclizeGasPrice(_gasPrice); } /** * Utility function to bulk set the callback gas price */ function setAllOraclizeGasPrices(uint256 _gasPrice) external onlyOwner { for (uint256 i = 0; i < getTotalCoinPairs(); i++) { setCoinPairOraclizeGasPrice(i, _gasPrice); } } /** * Retreive the total coin-pairs created by FluxDelta */ function getTotalCoinPairs() public view returns (uint256) { return _coinPairs.length; } /** * Retreive the total visible coin-pairs */ function getTotalVisibleCoinPairs() internal view returns (uint256 count) { count = 0; for (uint256 i = 0; i < _coinPairs.length; i++) { if (_coinPairs[i].isVisible()) { count++; } } } /** * Utility function for returning all of the core information of the coin-pairs */ function getAllCoinPairs(bool _onlyVisible) public view returns (uint256[] indexes, address[] addresses, bytes32[] fromSyms, bytes32[] toSyms, uint256[] totalShares, uint256[] totalPots) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); addresses = new address[](length); fromSyms = new bytes32[](length); toSyms = new bytes32[](length); totalShares = new uint256[](length); totalPots = new uint256[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; addresses[index] = address(coinPair); fromSyms[index] = coinPair.fSym(); toSyms[index] = coinPair.tSym(); totalShares[index] = coinPair.shares(); totalPots[index] = coinPair.getTotalPot(); index++; } } } /** * Utility function for returning all of the shares information of the coin-pairs of a certain user */ function getAllSharesInfoOf(address _user, bool _onlyVisible) public view returns (uint256[] indexes, uint256[] userShares, uint256[] lastPrices, uint256[] lastPriceTimes, uint256[] withdrawables) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); userShares = new uint256[](length); lastPrices = new uint256[](length); lastPriceTimes = new uint256[](length); withdrawables = new uint256[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; userShares[index] = coinPair.sharesOf(_user); lastPrices[index] = coinPair.lastPriceOf(_user); lastPriceTimes[index] = coinPair.lastPriceTimeOf(_user); withdrawables[index] = coinPair.getWithdrawableOf(_user); index++; } } } /** * Utility function for returning all of the cost information of the coin-pairs of a certain user */ function getAllCostsInfoOf(address _user, bool _onlyVisible) public view returns (uint256[] indexes, uint256[] baseCosts, uint256[] myScalars, uint256[] myCosts, bool[] isShorting) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); baseCosts = new uint256[](length); myScalars = new uint256[](length); myCosts = new uint256[](length); isShorting = new bool[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; baseCosts[index] = coinPair.baseCost(); myScalars[index] = coinPair.scalarOf(_user); myCosts[index] = coinPair.baseCost().mul(coinPair.scalarOf(_user)).div(1e18); isShorting[index] = coinPair.isShorting(_user); index++; } } } /** * Because this contract inherits usingP4D it must implement this method * Returning false will not allow this contract to receive P4D (only child * coin-pair contracts are allowed to receive P4D) */ function tokenCallback(address, uint256, bytes) external returns (bool) { return false; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b != 0); return _a % _b; } } /*===========================================================================================* *************************************** https://p4d.io *************************************** *===========================================================================================*/
* Payable function for receiving dividends from the P4D and P3D contracts/ only accept ETH payments from P4D and P3D (subdividends and dividends) as well as allowing the owner or dev to top up this contracts balance all ETH sent through this function will be used in the tokenCallback() function in order to buy more P4D (if there's excess) and pay for Oraclize calls
function () public payable { require(msg.sender == address(tokenContract) || msg.sender == address(_P3D) || msg.sender == _dev || msg.sender == _owner); }
12,922,070
[ 1, 9148, 429, 445, 364, 15847, 3739, 350, 5839, 628, 326, 453, 24, 40, 471, 453, 23, 40, 20092, 19, 1338, 2791, 512, 2455, 25754, 628, 453, 24, 40, 471, 453, 23, 40, 261, 1717, 2892, 350, 5839, 471, 3739, 350, 5839, 13, 487, 5492, 487, 15632, 326, 3410, 578, 4461, 358, 1760, 731, 333, 20092, 11013, 777, 512, 2455, 3271, 3059, 333, 445, 903, 506, 1399, 316, 326, 1147, 2428, 1435, 445, 316, 1353, 358, 30143, 1898, 453, 24, 40, 261, 430, 1915, 1807, 23183, 13, 471, 8843, 364, 531, 354, 830, 554, 4097, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2316, 8924, 13, 747, 1234, 18, 15330, 422, 1758, 24899, 52, 23, 40, 13, 747, 1234, 18, 15330, 422, 389, 5206, 747, 1234, 18, 15330, 422, 389, 8443, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-21 */ 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.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.12; interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.6.6; interface ILendingPool { function addressesProvider() external view returns (address); function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; function redeemUnderlying( address _reserve, address _user, uint256 _amount ) external; function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external; function repay( address _reserve, uint256 _amount, address _onBehalfOf ) external payable; function swapBorrowRateMode(address _reserve) external; function rebalanceFixedBorrowRate(address _reserve, address _user) external; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external; function liquidationCall( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable; function flashLoan( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external; function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive ); function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ); function getUserAccountData(address _user) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentUnderlyingBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ); function getReserves() external view; } pragma solidity ^0.6.6; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ interface ILendingPoolAddressesProvider { function getLendingPoolCore() external view returns (address payable); function getLendingPool() external view returns (address); } interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } pragma solidity >=0.5.0; interface SCErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } pragma solidity >=0.5.0; interface PriceOracle{ function getUnderlyingPrice(address ctoken) external view returns (uint256); } interface SComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function oracle() external view returns (PriceOracle); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, SCErc20I[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); } 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); } } library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } contract DydxFlashloanBase { using SafeMath for uint256; // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } pragma solidity >=0.6.0 <0.7.0; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function apiVersion() external pure returns (string memory); function isActive() external view returns (bool); function delegatedAssets() external virtual view returns (uint256); function name() external view returns (string memory); function vault() external view returns (address); function keeper() external view returns (address); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Comptroller address for compound.finance address private compound; //IRON BANK address private ironBank; address private ironBankToken; //Only three tokens we use address private comp; address private cToken; address private weth; address private uniswapRouter; //Flash Loan Providers address private SOLO; uint256 public maxIronBankLeverage = 4; //max leverage we will take from iron bank uint256 public step = 10; //Operating variables uint256 public collateralTarget = 0.73 ether; // 73% uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13 uint256 public minWant = 0; //Only lend if we have enough want to be worth it. Can be set to non-zero uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest //To deactivate flash loan provider if needed bool public DyDxActive = true; uint256 private dyDxMarketId; constructor( address _vault, address _cToken, address _solo, address _compound, address _ironBank, address _ironBankToken, address _comp, address _uniswapRouter, address _weth ) public BaseStrategy(_vault) { SOLO = _solo; compound = _compound; ironBank = _ironBank; ironBankToken = _ironBankToken; comp = _comp; uniswapRouter = _uniswapRouter; weth = _weth; cToken = _cToken; //pre-set approvals IERC20(_comp).safeApprove(_uniswapRouter, uint256(-1)); want.safeApprove(address(cToken), uint256(-1)); want.safeApprove(_solo, uint256(-1)); want.safeApprove(address(ironBankToken), uint256(-1)); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 15000; // multiple before triggering harvest debtThreshold = 500*1e18; // don't bother borrowing if less than debtThreshold dyDxMarketId = _getMarketIdFromTokenAddress(_solo, address(want)); } function name() external override view returns (string memory){ return "IBLevComp"; } function _isAuthorized() internal view { require(msg.sender == strategist || msg.sender == governance()); } function _isGov() internal view { require(msg.sender == governance()); } /* * Control Functions */ function setIsDyDxActive(bool _isActive) external { _isAuthorized(); DyDxActive = _isActive; } function setMinCompToSell(uint256 _minCompToSell) external { _isAuthorized(); minCompToSell = _minCompToSell; } function setIronBankLeverage(uint256 _multiple) external { _isGov(); maxIronBankLeverage = _multiple; } function setStep(uint256 _step) external { _isGov(); step = _step; } function setMinWant(uint256 _minWant) external { _isAuthorized(); minWant = _minWant; } function updateMarketId() external { _isAuthorized(); dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, address(want)); } function setCollateralTarget(uint256 _collateralTarget) external { _isAuthorized(); (, uint256 collateralFactorMantissa, ) = SComptrollerI(compound).markets(address(cToken)); require(collateralFactorMantissa > _collateralTarget); //, "!dangerous collateral" collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = IERC20(comp).balanceOf(address(this)); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist uint256 ironBankDebt = ironBankOutstandingDebtStored(); return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows).sub(ironBankDebt); } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public override view returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) { return true; } uint256 wantGasCost = priceCheck(weth, address(want), gasCost); //test if we want to change iron bank position (,uint256 _amount)= internalCreditOfficer(); if(profitFactor.mul(wantGasCost) < _amount){ return true; } } /* * Provide a signal to the keeper that `harvest()` should be called. * gasCost is expected_gas_use * gas_price * (keepers are always reimbursed by yEarn) * * NOTE: this call and `tendTrigger` should never return `true` at the same time. */ function harvestTrigger(uint256 gasCost) public override view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if strategy is not activated if (params.activation == 0) return false; uint256 wantGasCost = priceCheck(weth, address(want), gasCost); uint256 compGasCost = priceCheck(weth, comp, gasCost); // after enough comp has accrued we want the bot to run uint256 _claimableComp = predictCompAccrued(); if (_claimableComp > minCompToSell) { // check value of COMP in wei if ( _claimableComp.add(IERC20(comp).balanceOf(address(this))) > compGasCost.mul(profitFactor)) { return true; } } // Should trigger if hadn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; //check if vault wants lots of money back // dont return dust uint256 outstanding = vault.debtOutstanding(); if (outstanding > profitFactor.mul(wantGasCost)) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! uint256 credit = vault.creditAvailable().add(profit); return (profitFactor.mul(wantGasCost) < credit); } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path; if(start == weth){ path = new address[](2); path[0] = weth; path[1] = end; }else{ path = new address[](3); path[0] = start; path[1] = weth; path[2] = end; } uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } /***************** * Iron Bank ******************/ //simple logic. do we get more apr than iron bank charges? //if so, is that still true with increased pos? //if not, should be reduce? //made harder because we can't assume iron bank debt curve. So need to increment function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) { //how much credit we have (, uint256 liquidity, uint256 shortfall) = SComptrollerI(ironBank).getAccountLiquidity(address(this)); uint256 underlyingPrice = SComptrollerI(ironBank).oracle().getUnderlyingPrice(address(ironBankToken)); if(underlyingPrice == 0){ return (false, 0); } liquidity = liquidity.mul(1e18).div(underlyingPrice); shortfall = shortfall.mul(1e18).div(underlyingPrice); uint256 outstandingDebt = ironBankOutstandingDebtStored(); //repay debt if iron bank wants its money back //we need careful to not just repay the bare minimun as it will go over immediately if(shortfall > debtThreshold){ //note we only borrow 1 asset so can assume all our shortfall is from it return(false, Math.min(outstandingDebt, shortfall.mul(2))); //return double our shortfall } uint256 liquidityAvailable = want.balanceOf(address(ironBankToken)); uint256 remainingCredit = Math.min(liquidity, liquidityAvailable); //our current supply rate. //we only calculate once because it is expensive uint256 currentSR = currentSupplyRate(); //iron bank borrow rate uint256 ironBankBR = ironBankBorrowRate(0, true); //we have internal credit limit. it is function on our own assets invested //this means we can always repay our debt from our capital uint256 maxCreditDesired = vault.strategies(address(this)).totalDebt.mul(maxIronBankLeverage); // if we have too much debt we return //overshoot incase of dust if(maxCreditDesired.mul(11).div(10) < outstandingDebt){ borrowMore = false; amount = outstandingDebt - maxCreditDesired; if(amount >= debtThreshold){ return (false, amount); } amount = 0; } //minIncrement must be > 0 if(maxCreditDesired <= step){ return (false, 0); } //we move in 10% increments uint256 minIncrement = maxCreditDesired.div(step); //we start at 1 to save some gas uint256 increment = 1; //if sr is > iron bank we borrow more. else return if(currentSR > ironBankBR){ if(maxCreditDesired < outstandingDebt){ maxCreditDesired = outstandingDebt; } remainingCredit = Math.min(maxCreditDesired.sub(outstandingDebt), remainingCredit); while(minIncrement.mul(increment) <= remainingCredit){ ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false); if(currentSR <= ironBankBR){ break; } increment++; } borrowMore = true; amount = minIncrement.mul(increment-1); }else{ while(minIncrement.mul(increment) <= outstandingDebt){ ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true); //we do increment before the if statement here increment++; if(currentSR > ironBankBR){ break; } } borrowMore = false; //special case to repay all if(increment == 1){ amount = outstandingDebt; }else{ amount = minIncrement.mul(increment - 1); } } //we dont play with dust: if (amount < debtThreshold) { amount = 0; } } function ironBankOutstandingDebtStored() public view returns (uint256 available) { return SCErc20I(ironBankToken).borrowBalanceStored(address(this)); } function ironBankBorrowRate(uint256 amount, bool repay) public view returns (uint256) { uint256 cashPrior = want.balanceOf(address(ironBankToken)); uint256 borrows = SCErc20I(ironBankToken).totalBorrows(); uint256 reserves = SCErc20I(ironBankToken).totalReserves(); InterestRateModel model = SCErc20I(ironBankToken).interestRateModel(); uint256 cashChange; uint256 borrowChange; if(repay){ cashChange = cashPrior.add(amount); borrowChange = borrows.sub(amount); }else{ cashChange = cashPrior.sub(amount); borrowChange = borrows.add(amount); } uint256 borrowRate = model.getBorrowRate(cashChange, borrowChange, reserves); return borrowRate; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = SComptrollerI(compound).markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = SCErc20I(cToken).borrowRatePerBlock(); uint256 supplyRate = SCErc20I(cToken).supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return uint256(-1); } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1 - denom2; //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(compBlockShare()); } function compBlockShare() public view returns (uint256){ (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } //comp speed is amount to borrow or deposit (so half the total distribution for want) uint256 distributionPerBlock = SComptrollerI(compound).compSpeeds(address(cToken)); uint256 totalBorrow = SCErc20I(cToken).totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = SCErc20I(cToken).totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(SCErc20I(cToken).exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0){ blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0){ blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow); } //how much we expect to earn per block return blockShareSupply.add(blockShareBorrow); } function currentSupplyRate() public view returns (uint256 supply) { //first let's do standard borrow and lend uint256 cashPrior = want.balanceOf(address(cToken)); uint256 totalBorrows = SCErc20I(cToken).totalBorrows(); uint256 reserves = SCErc20I(cToken).totalReserves(); uint256 reserverFactor = SCErc20I(cToken).reserveFactorMantissa(); InterestRateModel model = SCErc20I(cToken).interestRateModel(); //the supply rate is derived from the borrow rate, reserve factor and the amount of total borrows. uint256 supplyRate = model.getSupplyRate(cashPrior, totalBorrows, reserves, reserverFactor); uint256 borrowRate = model.getBorrowRate(cashPrior, totalBorrows, reserves); uint256 compPerBlock = compBlockShare(); uint256 estimatedWant = priceCheck(comp, address(want),compPerBlock); uint256 compRate; if(estimatedWant != 0){ compRate = estimatedWant.mul(9).div(10); //10% pessimist //now need to scale. compPerBlock is out total. compRate = compRate.mul(1e18).div(netBalanceLent()); } //our supply rate is: //comp + lend - borrow supplyRate = compRate.add(supplyRate); if(supplyRate > borrowRate){ supply = supplyRate.sub(borrowRate); }else{ supply = 0; } } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { (, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = SCErc20I(cToken).getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() internal returns (uint256 deposits, uint256 borrows) { deposits = SCErc20I(cToken).balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = SCErc20I(cToken).borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity. also reduces bytesize if (SCErc20I(cToken).balanceOf(address(this)) == 0) { uint256 wantBalance = want.balanceOf(address(this)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = want.balanceOf(address(this)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 ibDebt = SCErc20I(ironBankToken).borrowBalanceCurrent(address(this)); uint256 debt = vault.strategies(address(this)).totalDebt.add(ibDebt); //Balance - Total Debt is profit if (balance > debt) { _profit = balance - debt; if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)){ _debtPayment = _debtOutstanding; }else{ _debtPayment = wantBalance - _profit; } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt - balance; _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //start off by borrowing or returning: (bool borrowMore, uint256 amount) = internalCreditOfficer(); //if repaying we use debOutstanding if(!borrowMore){ _debtOutstanding = amount; }else if(amount > 0){ //borrow the amount we want SCErc20I(ironBankToken).borrow(amount); } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = want.balanceOf(address(this)); if(_wantBal < _debtOutstanding){ //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if(SCErc20I(cToken).balanceOf(address(this)) > 1){ _withdrawSome(_debtOutstanding - _wantBal); } if(!borrowMore){ SCErc20I(ironBankToken).repayBorrow(Math.min(_debtOutstanding, want.balanceOf(address(this)))); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if dydx is not active we just try our best with basic leverage uint i = 0; uint256 toBeat = DyDxActive ? want.balanceOf(SOLO) : 0; //if there is huge position to improve we want to do normal leverage. it is quicker while(position > toBeat){ position = position.sub(_noFlashLoan(position, deficit)); i++; if(i > 4){ break; } } //flash loan to position if(DyDxActive && position > 0){ doDyDxFlashLoan(deficit, position); } } // if(!borrowMore){ //now we have debt outstanding lent without being needed: // cToken.redeemUnderlying(_debtOutstanding); // ironBankToken.repayBorrow(Math.min(_debtOutstanding, want.balanceOf(address(this)))); //} } /************* * Very important function * Input: amount we want to withdraw. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false); //If there is no deficit we dont need to adjust position if (deficit) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. if (DyDxActive) { position = position.sub(doDyDxFlashLoan(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > 0) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 AmountNeeded = 0; if(collateralTarget > 0){ AmountNeeded = borrowBalance.mul(1e18).div(collateralTarget); } uint256 redeemable = depositBalance.sub(AmountNeeded); if (redeemable < _amount) { SCErc20I(cToken).redeemUnderlying(redeemable); } else { SCErc20I(cToken).redeemUnderlying(_amount); } //let's sell some comp if we have more than needed //flash loan would have sent us comp if we had some accrued so we don't need to call claim comp _disposeOfComp(); } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if(balance > unwoundDeposit) balance = unwoundDeposit; desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow - 1e5; } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows - desiredBorrow; //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow - borrows; } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if(debtOutstanding > assets){ _loss = debtOutstanding - assets; } if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can (uint256 deposits, uint256 borrows) = getLivePosition(); //1 token causes rounding error with withdrawUnderlying if(SCErc20I(cToken).balanceOf(address(this)) > 1){ _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); }else{ _amountFreed = _amountNeeded; } } } function _claimComp() internal { SCErc20I[] memory tokens = new SCErc20I[](1); tokens[0] = SCErc20I(cToken); SComptrollerI(compound).claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = address(want); IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = SCErc20I(cToken).getAccountSnapshot(address(this)); require(borrowBalance < debtThreshold); //, "DELEVERAGE_FIRST" //return our iron bank deposit: //state changing uint256 ibBorrows = SCErc20I(ironBankToken).borrowBalanceCurrent(address(this)); SCErc20I(ironBankToken).repayBorrow(Math.min(ibBorrows, want.balanceOf(address(this)))); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); IERC20 _comp = IERC20(comp); uint _compB = _comp.balanceOf(address(this)); if(_compB > 0){ _comp.safeTransfer(_newStrategy, _compB); } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = SComptrollerI(compound).markets(address(cToken)); if (deficit) { amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa); } else { amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa); } //emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if(collatRatio != 0){ theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } SCErc20I(cToken).redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage SCErc20I(cToken).repayBorrow(deleveragedAmount); } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } SCErc20I(cToken).borrow(leveragedAmount); SCErc20I(cToken).mint(want.balanceOf(address(this))); } function protectedTokens() internal override view returns (address[] memory) { //want is protected automatically address[] memory protected = new address[](2); protected[0] = comp; protected[1] = address(cToken); return protected; } /****************** * Flash loan stuff ****************/ // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } uint256 repayAmount = amount.add(2); // we need to overcollateralise on way back bytes memory data = abi.encode(deficit, amount, repayAmount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); //emit Leverage(amountDesired, amount, deficit, SOLO); return amount; } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } //DyDx calls this function after doing flash loan function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount, uint256 repayAmount) = abi.decode(data, (bool, uint256, uint256)); require(msg.sender == SOLO); //, "NOT_SOLO" uint256 bal = want.balanceOf(address(this)); require(bal >= amount); //, "FLASH_FAILED" to stop malicious calls //if in deficit we repay amount and then withdraw if (deficit) { SCErc20I(cToken).repayBorrow(amount); //if we are withdrawing we take more to cover fee SCErc20I(cToken).redeemUnderlying(repayAmount); } else { //check if this failed incase we borrow into liquidation require(SCErc20I(cToken).mint(bal) == 0); //dev: "mint error" //borrow more to cover fee // fee is so low for dydx that it does not effect our liquidation risk. //DONT USE FOR AAVE SCErc20I(cToken).borrow(repayAmount); } } }
maxDeleverage is how much we want to increase by
function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } SCErc20I(cToken).borrow(leveragedAmount); SCErc20I(cToken).mint(want.balanceOf(address(this))); }
6,662,166
[ 1, 1896, 2837, 73, 5682, 353, 3661, 9816, 732, 2545, 358, 10929, 635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6130, 1682, 5682, 12, 203, 3639, 2254, 5034, 943, 1682, 5682, 16, 203, 3639, 2254, 5034, 328, 319, 16, 203, 3639, 2254, 5034, 29759, 329, 16, 203, 3639, 2254, 5034, 4508, 270, 8541, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 884, 502, 11349, 6275, 13, 288, 203, 3639, 2254, 5034, 326, 479, 88, 1706, 38, 15318, 273, 328, 319, 18, 16411, 12, 1293, 4801, 8541, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 203, 3639, 884, 502, 11349, 6275, 273, 326, 479, 88, 1706, 38, 15318, 18, 1717, 12, 70, 15318, 329, 1769, 203, 203, 3639, 309, 261, 298, 502, 11349, 6275, 1545, 943, 1682, 5682, 13, 288, 203, 5411, 884, 502, 11349, 6275, 273, 943, 1682, 5682, 31, 203, 3639, 289, 203, 203, 3639, 348, 1441, 1310, 3462, 45, 12, 71, 1345, 2934, 70, 15318, 12, 298, 502, 11349, 6275, 1769, 203, 3639, 348, 1441, 1310, 3462, 45, 12, 71, 1345, 2934, 81, 474, 12, 17369, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x98A992392858d98D2715fb116915bF54cF1A175E/sources/registry/ENSRegistry.sol
* @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. @param _node The node to transfer ownership of. @param _owner The address of the new owner./
function setOwner(bytes32 _node, address _owner) public virtual override authorised(_node) { _setOwner(_node, _owner); emit Transfer(_node, _owner); }
7,167,532
[ 1, 1429, 18881, 23178, 434, 279, 756, 358, 279, 394, 1758, 18, 16734, 1338, 506, 2566, 635, 326, 783, 3410, 434, 326, 756, 18, 225, 389, 2159, 1021, 756, 358, 7412, 23178, 434, 18, 225, 389, 8443, 1021, 1758, 434, 326, 394, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31309, 12, 3890, 1578, 389, 2159, 16, 1758, 389, 8443, 13, 1071, 5024, 3849, 2869, 5918, 24899, 2159, 13, 288, 203, 3639, 389, 542, 5541, 24899, 2159, 16, 389, 8443, 1769, 203, 3639, 3626, 12279, 24899, 2159, 16, 389, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; /* This contract is based on https://github.com/AltCoinExchange/ethatomicswap/blob/master/contracts/AtomicSwap.sol For two ETH-based chains, this contract allows two persons safely exchange assets without trusting each other. All ERC20 and ERC721Value tokens are supported. This contract also allows sending ether to it. The ether will be considered donation to the contract starter. Author: Lin F. Yang Date: 2018/08/18 */ 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 ERC721{ 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); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the /// recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return /// of other than the magic value MUST result in the transaction being reverted. /// @notice The contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } contract AtomicSwap is ERC721TokenReceiver{ /*The state of the swap instance*/ enum State { Empty, Initiator} /*The AssetType of the swap instance*/ enum AssetType { Native, ERC20Value, ERC721Value } struct Swap { uint initTimestamp; uint refundTime; bytes20 hashedSecret; bytes32 secret; address initiator; address participant; address tokenAddress; uint256 value; bool emptied; State state; AssetType assetType; } mapping(bytes20 => Swap) public swaps; //store the total amount of ether locked in this contract uint256 private lockedValue; //allow anyone to look at who is the starter address public contractStarter; event Refunded(uint _refundTime); event Redeemed(uint _redeemTime); event Initiated( uint _initTimestamp, uint _refundTime, bytes20 _hashedSecret, address _participant, address _initiator, AssetType _assetType, uint256 _funds, address _tokenAddress ); modifier isRefundable(bytes20 _hashedSecret) { require(block.timestamp > swaps[_hashedSecret].initTimestamp + swaps[_hashedSecret].refundTime); require(swaps[_hashedSecret].emptied == false); _; } modifier isRedeemable(bytes20 _hashedSecret, bytes32 _secret) { require(ripemd160(_secret) == _hashedSecret); require(block.timestamp < swaps[_hashedSecret].initTimestamp + swaps[_hashedSecret].refundTime); require(swaps[_hashedSecret].emptied == false); _; } modifier isInitiator(bytes20 _hashedSecret) { require(msg.sender == swaps[_hashedSecret].initiator); _; } modifier isNotInitiated(bytes20 _hashedSecret) { require(swaps[_hashedSecret].state == State.Empty); _; } /*the msg sender will be the contract starter*/ constructor() public{ contractStarter = msg.sender; } /*fallback function, used to accept donations*/ function () public payable {} function __initiate (uint _refundTime,bytes20 _hashedSecret,address _participant) private { swaps[_hashedSecret].refundTime = _refundTime; swaps[_hashedSecret].initTimestamp = block.timestamp; swaps[_hashedSecret].hashedSecret = _hashedSecret; swaps[_hashedSecret].participant = _participant; swaps[_hashedSecret].initiator = msg.sender; swaps[_hashedSecret].state = State.Initiator; } /** Initiate the swapper with the native token. */ function initiate (uint _refundTime,bytes20 _hashedSecret,address _participant) public payable isNotInitiated(_hashedSecret) { __initiate(_refundTime, _hashedSecret, _participant); swaps[_hashedSecret].value = msg.value; swaps[_hashedSecret].assetType = AssetType.Native; //add the locked value lockedValue = lockedValue + swaps[_hashedSecret].value; emit Initiated( swaps[_hashedSecret].initTimestamp, _refundTime, _hashedSecret, _participant, msg.sender, AssetType.Native, msg.value, address(0) ); } /** Initiate the swapper with the ERC20Value token. */ function initiateERC20 (uint _refundTime, bytes20 _hashedSecret, address _participant, address _tokenAddress, uint256 _value) public isNotInitiated(_hashedSecret) { __initiate(_refundTime, _hashedSecret, _participant); require(ERC20(_tokenAddress).transferFrom(msg.sender, this, _value) == true); swaps[_hashedSecret].value = _value; swaps[_hashedSecret].assetType = AssetType.ERC20Value; swaps[_hashedSecret].tokenAddress = _tokenAddress; emit Initiated( swaps[_hashedSecret].initTimestamp, _refundTime, _hashedSecret, _participant, msg.sender, AssetType.ERC20Value, _value, _tokenAddress ); } /** Initiate the swapper with the ERC721Value token. */ function initiateERC721 (uint _refundTime, bytes20 _hashedSecret, address _participant, address _tokenAddress, uint256 _tokenId) public isNotInitiated(_hashedSecret) { __initiate(_refundTime, _hashedSecret, _participant); ERC721(_tokenAddress).safeTransferFrom(msg.sender, this, _tokenId); swaps[_hashedSecret].value = _tokenId; swaps[_hashedSecret].assetType = AssetType.ERC721Value; swaps[_hashedSecret].tokenAddress = _tokenAddress; emit Initiated( swaps[_hashedSecret].initTimestamp, _refundTime, _hashedSecret, _participant, msg.sender, AssetType.ERC721Value, _tokenId, _tokenAddress ); } function redeem(bytes32 _secret, bytes20 _hashedSecret) public isRedeemable(_hashedSecret, _secret) { if(swaps[_hashedSecret].state == State.Initiator){ if(swaps[_hashedSecret].assetType == AssetType.Native){ swaps[_hashedSecret].participant.transfer(swaps[_hashedSecret].value); //remove the locked value lockedValue = lockedValue - swaps[_hashedSecret].value; } if(swaps[_hashedSecret].assetType == AssetType.ERC20Value){ ERC20(swaps[_hashedSecret].tokenAddress).transfer(swaps[_hashedSecret].participant, swaps[_hashedSecret].value); } if(swaps[_hashedSecret].assetType == AssetType.ERC721Value){ ERC721(swaps[_hashedSecret].tokenAddress).safeTransferFrom(this, swaps[_hashedSecret].participant, swaps[_hashedSecret].value); } } swaps[_hashedSecret].emptied = true; emit Redeemed(block.timestamp); swaps[_hashedSecret].secret = _secret; } function refund(bytes20 _hashedSecret) public isRefundable(_hashedSecret) { if(swaps[_hashedSecret].state == State.Initiator){ if(swaps[_hashedSecret].assetType == AssetType.Native){ swaps[_hashedSecret].initiator.transfer(swaps[_hashedSecret].value); //remove the locked value lockedValue = lockedValue - swaps[_hashedSecret].value; } if(swaps[_hashedSecret].assetType == AssetType.ERC20Value){ ERC20(swaps[_hashedSecret].tokenAddress).transfer(swaps[_hashedSecret].initiator, swaps[_hashedSecret].value); } if(swaps[_hashedSecret].assetType == AssetType.ERC721Value){ ERC721(swaps[_hashedSecret].tokenAddress).safeTransferFrom(this, swaps[_hashedSecret].initiator, swaps[_hashedSecret].value); } } swaps[_hashedSecret].emptied = true; emit Refunded(block.timestamp); } /*utility functions*/ function getLockedValue() external view returns(uint256){ return lockedValue; } /*get donation amount*/ function getDonationAmount() external view returns(uint256){ return address(this).balance - lockedValue; } /*transfer the donation value to the contractStarter*/ function transferDonation() external{ require(address(this).balance > lockedValue); contractStarter.transfer(address(this).balance - lockedValue); } /*implement ERC721 receiver */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4){ return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
transfer the donation value to the contractStarter*/
function transferDonation() external{ require(address(this).balance > lockedValue); contractStarter.transfer(address(this).balance - lockedValue); }
12,873,068
[ 1, 13866, 326, 2727, 367, 460, 358, 326, 6835, 510, 14153, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 22293, 367, 1435, 3903, 95, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 405, 8586, 620, 1769, 203, 3639, 6835, 510, 14153, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 300, 8586, 620, 1769, 203, 565, 289, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../abstractV2/PendleYieldContractDeployerBaseV2.sol"; import "./PendleCompoundV2YieldTokenHolder.sol"; import "./PendleCompoundV2Forge.sol"; contract PendleCompoundV2YieldContractDeployer is PendleYieldContractDeployerBaseV2 { constructor(address _governanceManager, bytes32 _forgeId) PendleYieldContractDeployerBaseV2(_governanceManager, _forgeId) {} function deployYieldTokenHolder( address _yieldToken, uint256 _expiry, uint256[] calldata ) external override onlyForge returns (address yieldTokenHolder) { yieldTokenHolder = address( new PendleCompoundV2YieldTokenHolder( address(governanceManager), address(forge), _yieldToken, address(PendleCompoundV2Forge(address(forge)).comptroller()), _expiry ) ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../../periphery/PermissionsV2.sol"; import "../../interfaces/IPendleYieldContractDeployerV2.sol"; import "./PendleYieldTokenHolderBaseV2.sol"; import "../../interfaces/IPendleForge.sol"; import "../../tokens/PendleFutureYieldToken.sol"; import "../../tokens/PendleOwnershipToken.sol"; contract PendleYieldContractDeployerBaseV2 is IPendleYieldContractDeployerV2, PermissionsV2 { bytes32 public override forgeId; // no immutable to save bytecode size IPendleForge public forge; modifier onlyForge() { require(msg.sender == address(forge), "ONLY_FORGE"); _; } constructor(address _governanceManager, bytes32 _forgeId) PermissionsV2(_governanceManager) { forgeId = _forgeId; } function initialize(address _forgeAddress) external virtual { require(msg.sender == initializer, "FORBIDDEN"); forge = IPendleForge(_forgeAddress); require(forge.forgeId() == forgeId, "FORGE_ID_MISMATCH"); initializer = address(0); } function forgeFutureYieldToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external virtual override onlyForge returns (address xyt) { xyt = address( new PendleFutureYieldToken( address(forge.router()), address(forge), _underlyingAsset, forge.getYieldBearingToken(_underlyingAsset), _name, _symbol, _decimals, block.timestamp, _expiry ) ); } function forgeOwnershipToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external virtual override onlyForge returns (address ot) { ot = address( new PendleOwnershipToken( address(forge.router()), address(forge), _underlyingAsset, forge.getYieldBearingToken(_underlyingAsset), _name, _symbol, _decimals, block.timestamp, _expiry ) ); } function deployYieldTokenHolder( address _yieldToken, uint256 _expiry, uint256[] calldata ) external virtual override onlyForge returns (address yieldTokenHolder) { yieldTokenHolder = address( new PendleYieldTokenHolderBaseV2( address(governanceManager), address(forge), _yieldToken, _expiry ) ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "../abstractV2/PendleYieldTokenHolderBaseV2.sol"; import "../../interfaces/IComptroller.sol"; contract PendleCompoundV2YieldTokenHolder is PendleYieldTokenHolderBaseV2 { IComptroller private immutable comptroller; constructor( address _governanceManager, address _forge, address _yieldToken, address _comptroller, uint256 _expiry ) PendleYieldTokenHolderBaseV2(_governanceManager, _forge, _yieldToken, _expiry) { require(_comptroller != address(0), "ZERO_ADDRESS"); comptroller = IComptroller(_comptroller); } /** @dev same logic as in V1 */ function redeemRewards() external virtual override { address[] memory cTokens = new address[](1); address[] memory holders = new address[](1); cTokens[0] = yieldToken; holders[0] = address(this); comptroller.claimComp(holders, cTokens, false, true); } } // SPDX-License-Identifier: BUSL-1.1 // solhint-disable ordering pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../interfaces/IPendleGenericForge.sol"; import "../abstractV2/PendleForgeBaseV2.sol"; import "../../interfaces/IComptroller.sol"; import "../../interfaces/ICToken.sol"; /* - For this Forge, the container of each underlyingAsset will contain only the address of its corresponding cToken - Since Compound uses 1e18 scale in their Math, if we want to make 1 cToken = 1 YT, we need to use the same math here. Hence we will use cmul & cdiv instead of rmul & rdiv - For CompoundV2, the container of each underlyingAsset will contain 1 element which is the addr of the corresponding cToken */ contract PendleCompoundV2Forge is PendleForgeBaseV2, IPendleGenericForge { using SafeMath for uint256; using CompoundMath for uint256; IComptroller public immutable comptroller; mapping(address => mapping(uint256 => uint256)) public lastRateBeforeExpiry; mapping(address => mapping(uint256 => mapping(address => uint256))) public lastRate; constructor( address _governanceManager, IPendleRouter _router, IComptroller _comptroller, bytes32 _forgeId, address _rewardToken, address _rewardManager, address _yieldContractDeployer, address _coumpoundEth ) PendleForgeBaseV2( _governanceManager, _router, _forgeId, _rewardToken, _rewardManager, _yieldContractDeployer ) { require(address(_comptroller) != address(0), "ZERO_ADDRESS"); comptroller = _comptroller; // Pre-register for cEther address weth = address(_router.weth()); tokenInfo[weth].registered = true; tokenInfo[weth].container.push(uint256(_coumpoundEth)); } /** @notice verify the validity of a cToken @dev the logic of this function is similar to how Compound verify an address is cToken @dev Same logic as in V1 */ function verifyToken(address _underlyingAsset, uint256[] calldata _tokenInfo) public virtual override { require(_tokenInfo.length == 1, "INVALID_TOKEN_INFO"); address cTokenAddr = address(_tokenInfo[0]); require( comptroller.markets(cTokenAddr).isListed && ICToken(cTokenAddr).isCToken() && ICToken(cTokenAddr).underlying() == _underlyingAsset, "INVALID_TOKEN_INFO" ); } function getExchangeRate(address _underlyingAsset) public override returns (uint256 rate) { address cTokenAddr = address(tokenInfo[_underlyingAsset].container[0]); return ICToken(cTokenAddr).exchangeRateCurrent(); } /// @inheritdoc PendleForgeBaseV2 function getYieldBearingToken(address _underlyingAsset) public view override(IPendleForge, PendleForgeBaseV2) returns (address cTokenAddr) { require(tokenInfo[_underlyingAsset].registered, "INVALID_UNDERLYING_ASSET"); cTokenAddr = address(tokenInfo[_underlyingAsset].container[0]); } /** @dev Same logic as UniswapV2's Forge */ function _calcTotalAfterExpiry( address _underlyingAsset, uint256 _expiry, uint256 _redeemedAmount ) internal view override returns (uint256 totalAfterExpiry) { totalAfterExpiry = _redeemedAmount.cdiv(lastRateBeforeExpiry[_underlyingAsset][_expiry]); } /** @dev this function serves functions that take into account the lastRateBeforeExpiry Else, call getExchangeRate instead */ function getExchangeRateBeforeExpiry(address _underlyingAsset, uint256 _expiry) internal returns (uint256 exchangeRate) { if (block.timestamp > _expiry) { return lastRateBeforeExpiry[_underlyingAsset][_expiry]; } exchangeRate = getExchangeRate(_underlyingAsset); lastRateBeforeExpiry[_underlyingAsset][_expiry] = exchangeRate; } /** @dev Same logic as UniswapV2's Forge */ function _calcUnderlyingToRedeem(address _underlyingAsset, uint256 _amountToRedeem) internal override returns (uint256 underlyingToRedeem) { underlyingToRedeem = _amountToRedeem.cdiv(getExchangeRate(_underlyingAsset)); } /** @dev Same logic as UniswapV2's Forge */ function _calcAmountToMint(address _underlyingAsset, uint256 _amountToTokenize) internal override returns (uint256 amountToMint) { amountToMint = _amountToTokenize.cmul(getExchangeRate(_underlyingAsset)); } /** @dev same logic as UniswapV2's Forge */ function _updateDueInterests( uint256 _principal, address _underlyingAsset, uint256 _expiry, address _user ) internal override { uint256 prevRate = lastRate[_underlyingAsset][_expiry][_user]; uint256 currentRate = getExchangeRateBeforeExpiry(_underlyingAsset, _expiry); lastRate[_underlyingAsset][_expiry][_user] = currentRate; // first time getting XYT, or there is no update in exchangeRate if (prevRate == 0 || prevRate == currentRate) { return; } uint256 interestFromXyt = _principal.mul(currentRate.sub(prevRate)).cdiv( prevRate.mul(currentRate) ); dueInterests[_underlyingAsset][_expiry][_user] = dueInterests[_underlyingAsset][_expiry][ _user ] .add(interestFromXyt); } /** @dev same logic as UniswapV2's Forge */ function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount ) internal override { totalFee[_underlyingAsset][_expiry] = totalFee[_underlyingAsset][_expiry].add(_feeAmount); } } library CompoundMath { uint256 internal constant ONE_E_18 = 1e18; using SafeMath for uint256; function cmul(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(ONE_E_18); } function cdiv(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(ONE_E_18).div(y); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../core/PendleGovernanceManager.sol"; import "../interfaces/IPermissionsV2.sol"; abstract contract PermissionsV2 is IPermissionsV2 { PendleGovernanceManager public immutable override governanceManager; address internal initializer; constructor(address _governanceManager) { require(_governanceManager != address(0), "ZERO_ADDRESS"); initializer = msg.sender; governanceManager = PendleGovernanceManager(_governanceManager); } modifier initialized() { require(initializer == address(0), "NOT_INITIALIZED"); _; } modifier onlyGovernance() { require(msg.sender == _governance(), "ONLY_GOVERNANCE"); _; } function _governance() internal view returns (address) { return governanceManager.governance(); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldContractDeployerV2 { function forgeId() external returns (bytes32); function forgeOwnershipToken( address underlyingAsset, string memory name, string memory symbol, uint8 decimals, uint256 expiry ) external returns (address ot); function forgeFutureYieldToken( address underlyingAsset, string memory name, string memory symbol, uint8 decimals, uint256 expiry ) external returns (address xyt); function deployYieldTokenHolder( address yieldToken, uint256 expiry, uint256[] calldata container ) external returns (address yieldTokenHolder); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../interfaces/IPendleYieldTokenHolderV2.sol"; import "../../interfaces/IPendleForge.sol"; import "../../periphery/WithdrawableV2.sol"; import "../../libraries/MathLib.sol"; contract PendleYieldTokenHolderBaseV2 is IPendleYieldTokenHolderV2, WithdrawableV2 { using SafeERC20 for IERC20; using Math for uint256; using SafeMath for uint256; address public immutable override yieldToken; address public immutable override forge; address public override rewardToken; // no immutable to save bytecode size uint256 public override expiry; // no immutable to save bytecode size modifier onlyForge() { require(msg.sender == address(forge), "ONLY_FORGE"); _; } constructor( address _governanceManager, address _forge, address _yieldToken, uint256 _expiry ) PermissionsV2(_governanceManager) { address _rewardToken = address(IPendleForge(_forge).rewardToken()); address rewardManager = address(IPendleForge(_forge).rewardManager()); yieldToken = _yieldToken; forge = _forge; rewardToken = _rewardToken; expiry = _expiry; IERC20(_rewardToken).safeApprove(rewardManager, type(uint256).max); } /** @dev function has been depreciated but must still be left here to conform with the interface */ function setUpEmergencyMode(address) external pure override { revert("FUNCTION_DEPRECIATED"); } // Only forge can call this function // this will allow a spender to spend the whole balance of the specified tokens // the spender should ideally be a contract with logic for users to withdraw out their funds. function setUpEmergencyModeV2(address spender, bool) external virtual override onlyForge { // by default we store all the tokens inside this contract, so just approve IERC20(yieldToken).safeApprove(spender, type(uint256).max); IERC20(rewardToken).safeApprove(spender, type(uint256).max); } /// @dev by default the token doesn't have any rewards function redeemRewards() external virtual override {} /// @dev by default we will keep all tokens in this contract, so no further actions necessary function afterReceiveTokens(uint256 amount) external virtual override {} function pushYieldTokens( address to, uint256 amount, uint256 minNYieldAfterPush ) external virtual override onlyForge { uint256 yieldTokenBal = IERC20(yieldToken).balanceOf(address(this)); require(yieldTokenBal.sub(amount) >= minNYieldAfterPush, "INVARIANCE_ERROR"); IERC20(yieldToken).safeTransfer(to, amount); } // The governance address will be able to withdraw any tokens except for // the yieldToken and the rewardToken function _allowedToWithdraw(address _token) internal view virtual override returns (bool allowed) { allowed = _token != yieldToken && _token != rewardToken; } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleRewardManager.sol"; import "./IPendleYieldContractDeployer.sol"; import "./IPendleData.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleForge { /** * @dev Emitted when the Forge has minted the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying yield token. * @param expiry The expiry of the XYT token * @param amountToTokenize The amount of yield bearing assets to tokenize * @param amountTokenMinted The amount of OT/XYT minted **/ event MintYieldTokens( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToTokenize, uint256 amountTokenMinted, address indexed user ); /** * @dev Emitted when the Forge has created new yield token contracts. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying asset. * @param expiry The date in epoch time when the contract will expire. * @param ot The address of the ownership token. * @param xyt The address of the new future yield token. **/ event NewYieldContracts( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, address ot, address xyt, address yieldBearingAsset ); /** * @dev Emitted when the Forge has redeemed the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amountToRedeem The amount of OT to be redeemed. * @param redeemedAmount The amount of yield token received **/ event RedeemYieldToken( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToRedeem, uint256 redeemedAmount, address indexed user ); /** * @dev Emitted when interest claim is settled * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param user Interest receiver Address * @param amount The amount of interest claimed **/ event DueInterestsSettled( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount, uint256 forgeFeeAmount, address indexed user ); /** * @dev Emitted when forge fee is withdrawn * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amount The amount of interest claimed **/ event ForgeFeeWithdrawn( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount ); function setUpEmergencyMode( address _underlyingAsset, uint256 _expiry, address spender ) external; function newYieldContracts(address underlyingAsset, uint256 expiry) external returns (address ot, address xyt); function redeemAfterExpiry( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 interests); function updateDueInterests( address underlyingAsset, uint256 expiry, address user ) external; function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function redeemUnderlying( address user, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function mintOtAndXyt( address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); function withdrawForgeFee(address underlyingAsset, uint256 expiry) external; function getYieldBearingToken(address underlyingAsset) external returns (address); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function data() external view returns (IPendleData); function rewardManager() external view returns (IPendleRewardManager); function yieldContractDeployer() external view returns (IPendleYieldContractDeployer); function rewardToken() external view returns (IERC20); /** * @notice Gets the bytes32 ID of the forge. * @return Returns the forge and protocol identifier. **/ function forgeId() external view returns (bytes32); function dueInterests( address _underlyingAsset, uint256 expiry, address _user ) external view returns (uint256); function yieldTokenHolders(address _underlyingAsset, uint256 _expiry) external view returns (address yieldTokenHolder); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./PendleBaseToken.sol"; import "../interfaces/IPendleForge.sol"; import "../interfaces/IPendleYieldTokenCommon.sol"; contract PendleFutureYieldToken is PendleBaseToken, IPendleYieldTokenCommon { address public immutable override forge; address public immutable override underlyingAsset; address public immutable override underlyingYieldToken; constructor( address _router, address _forge, address _underlyingAsset, address _underlyingYieldToken, string memory _name, string memory _symbol, uint8 _underlyingYieldTokenDecimals, uint256 _start, uint256 _expiry ) PendleBaseToken(_router, _name, _symbol, _underlyingYieldTokenDecimals, _start, _expiry) { require( _underlyingAsset != address(0) && _underlyingYieldToken != address(0), "ZERO_ADDRESS" ); require(_forge != address(0), "ZERO_ADDRESS"); forge = _forge; underlyingAsset = _underlyingAsset; underlyingYieldToken = _underlyingYieldToken; } modifier onlyForge() { require(msg.sender == address(forge), "ONLY_FORGE"); _; } /** * @dev Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) public override onlyForge { _burn(user, amount); emit Burn(user, amount); } /** * @dev Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) public override onlyForge { _mint(user, amount); emit Mint(user, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); if (from != address(0)) IPendleForge(forge).updateDueInterests(underlyingAsset, expiry, from); if (to != address(0)) IPendleForge(forge).updateDueInterests(underlyingAsset, expiry, to); } function approveRouter(address user) external { require(msg.sender == address(router), "NOT_ROUTER"); _approve(user, address(router), type(uint256).max); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./PendleBaseToken.sol"; import "../interfaces/IPendleYieldTokenCommon.sol"; import "../interfaces/IPendleForge.sol"; contract PendleOwnershipToken is PendleBaseToken, IPendleYieldTokenCommon { address public immutable override forge; address public immutable override underlyingAsset; address public immutable override underlyingYieldToken; constructor( address _router, address _forge, address _underlyingAsset, address _underlyingYieldToken, string memory _name, string memory _symbol, uint8 _underlyingYieldTokenDecimals, uint256 _start, uint256 _expiry ) PendleBaseToken(_router, _name, _symbol, _underlyingYieldTokenDecimals, _start, _expiry) { require( _underlyingAsset != address(0) && _underlyingYieldToken != address(0), "ZERO_ADDRESS" ); require(_forge != address(0), "ZERO_ADDRESS"); forge = _forge; underlyingAsset = _underlyingAsset; underlyingYieldToken = _underlyingYieldToken; } modifier onlyForge() { require(msg.sender == address(forge), "ONLY_FORGE"); _; } /** * @dev Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) public override onlyForge { _burn(user, amount); emit Burn(user, amount); } /** * @dev Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) public override onlyForge { _mint(user, amount); emit Mint(user, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from != address(0)) IPendleForge(forge).updatePendingRewards(underlyingAsset, expiry, from); if (to != address(0)) IPendleForge(forge).updatePendingRewards(underlyingAsset, expiry, to); } } // 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: BUSL-1.1 pragma solidity 0.7.6; contract PendleGovernanceManager { address public governance; address public pendingGovernance; event GovernanceClaimed(address newGovernance, address previousGovernance); event TransferGovernancePending(address pendingGovernance); constructor(address _governance) { require(_governance != address(0), "ZERO_ADDRESS"); governance = _governance; } modifier onlyGovernance() { require(msg.sender == governance, "ONLY_GOVERNANCE"); _; } /** * @dev Allows the pendingGovernance address to finalize the change governance process. */ function claimGovernance() external { require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE"); emit GovernanceClaimed(pendingGovernance, governance); governance = pendingGovernance; pendingGovernance = address(0); } /** * @dev Allows the current governance to set the pendingGovernance address. * @param _governance The address to transfer ownership to. */ function transferGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "ZERO_ADDRESS"); pendingGovernance = _governance; emit TransferGovernancePending(pendingGovernance); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../core/PendleGovernanceManager.sol"; interface IPermissionsV2 { function governanceManager() external returns (PendleGovernanceManager); } // 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 /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleYieldTokenHolder.sol"; interface IPendleYieldTokenHolderV2 is IPendleYieldTokenHolder { function setUpEmergencyModeV2(address spender, bool extraFlag) external; function pushYieldTokens( address to, uint256 amount, uint256 minNYieldAfterPush ) external; function afterReceiveTokens(uint256 amount) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PermissionsV2.sol"; abstract contract WithdrawableV2 is PermissionsV2 { using SafeERC20 for IERC20; event EtherWithdraw(uint256 amount, address sendTo); event TokenWithdraw(IERC20 token, uint256 amount, address sendTo); /** * @dev Allows governance to withdraw Ether in a Pendle contract * in case of accidental ETH transfer into the contract. * @param amount The amount of Ether to withdraw. * @param sendTo The recipient address. */ function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance { (bool success, ) = sendTo.call{value: amount}(""); require(success, "WITHDRAW_FAILED"); emit EtherWithdraw(amount, sendTo); } /** * @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle * contract in case of accidental token transfer into the contract. * @param token IERC20 The address of the token contract. * @param amount The amount of IERC20 tokens to withdraw. * @param sendTo The recipient address. */ function withdrawToken( IERC20 token, uint256 amount, address sendTo ) external onlyGovernance { require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED"); token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } // must be overridden by the sub contracts, so we must consider explicitly // in each and every contract which tokens are allowed to be withdrawn function _allowedToWithdraw(address) internal view virtual returns (bool allowed); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint256; uint256 internal constant BIG_NUMBER = (uint256(1) << uint256(200)); uint256 internal constant PRECISION_BITS = 40; uint256 internal constant RONE = uint256(1) << PRECISION_BITS; uint256 internal constant PI = (314 * RONE) / 10**2; uint256 internal constant PI_PLUSONE = (414 * RONE) / 10**2; uint256 internal constant PRECISION_POW = 1e2; function checkMultOverflow(uint256 _x, uint256 _y) internal pure returns (bool) { if (_y == 0) return false; return (((_x * _y) / _y) != _x); } /** @notice find the integer part of log2(p/q) => find largest x s.t p >= q * 2^x => find largest x s.t 2^x <= p / q */ function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 res = 0; uint256 remain = _p / _q; while (remain > 0) { res++; remain /= 2; } return res - 1; } /** @notice log2 for a number that it in [1,2) @dev _x is FP, return a FP @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two) to avoid the case where x = 2 may lead to incorrect result */ function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) { uint256 res = 0; uint256 one = (uint256(1) << PRECISION_BITS); uint256 two = 2 * one; uint256 addition = one; require((_x >= one) && (_x < two), "MATH_ERROR"); require(PRECISION_BITS < 125, "MATH_ERROR"); for (uint256 i = PRECISION_BITS; i > 0; i--) { _x = (_x * _x) / one; addition = addition / 2; if (_x >= two) { _x = _x / 2; res += addition; } } return res; } /** @notice log2 of (p/q). returns result in FP form @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 n = 0; if (_p > _q) { n = log2Int(_p, _q); } require(n * RONE <= BIG_NUMBER, "MATH_ERROR"); require(!checkMultOverflow(_p, RONE), "MATH_ERROR"); require(!checkMultOverflow(n, RONE), "MATH_ERROR"); require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR"); uint256 y = (_p * RONE) / (_q * (uint256(1) << n)); uint256 log2Small = log2ForSmallNumber(y); assert(log2Small <= BIG_NUMBER); return n * RONE + log2Small; } /** @notice calculate ln(p/q). returned result >= 0 @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function ln(uint256 p, uint256 q) internal pure returns (uint256) { uint256 ln2Numerator = 6931471805599453094172; uint256 ln2Denomerator = 10000000000000000000000; uint256 log2x = logBase2(p, q); require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR"); return (ln2Numerator * log2x) / ln2Denomerator; } /** @notice extract the fractional part of a FP @dev value is a FP, return a FP */ function fpart(uint256 value) internal pure returns (uint256) { return value % RONE; } /** @notice convert a FP to an Int @dev value is a FP, return an Int */ function toInt(uint256 value) internal pure returns (uint256) { return value / RONE; } /** @notice convert an Int to a FP @dev value is an Int, return a FP */ function toFP(uint256 value) internal pure returns (uint256) { return value * RONE; } /** @notice return e^exp in FP form @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html the function is based on exp function of: https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol @dev the function is expected to converge quite fast, after about 20 iteration @dev exp is a FP, return a FP */ function rpowe(uint256 exp) internal pure returns (uint256) { uint256 res = 0; uint256 curTerm = RONE; for (uint256 n = 0; ; n++) { res += curTerm; curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1))); if (curTerm == 0) { break; } if (n == 500) { /* testing shows that in the most extreme case, it will take 430 turns to converge. however, it's expected that the numbers will not exceed 2^120 in normal situation the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9)) */ revert("RPOWE_SLOW_CONVERGE"); } } return res; } /** @notice calculate base^exp with base and exp being FP int @dev to improve accuracy, base^exp = base^(int(exp)+frac(exp)) = base^int(exp) * base^frac @dev base & exp are FP, return a FP */ function rpow(uint256 base, uint256 exp) internal pure returns (uint256) { if (exp == 0) { // Anything to the 0 is 1 return RONE; } if (base == 0) { // 0 to anything except 0 is 0 return 0; } uint256 frac = fpart(exp); // get the fractional part uint256 whole = exp - frac; uint256 wholePow = rpowi(base, toInt(whole)); // whole is a FP, convert to Int uint256 fracPow; // instead of calculating base ^ frac, we will calculate e ^ (frac*ln(base)) if (base < RONE) { /* since the base is smaller than 1.0, ln(base) < 0. Since 1 / (e^(frac*ln(1/base))) = e ^ (frac*ln(base)), we will calculate 1 / (e^(frac*ln(1/base))) instead. */ uint256 newExp = rmul(frac, ln(rdiv(RONE, base), RONE)); fracPow = rdiv(RONE, rpowe(newExp)); } else { /* base is greater than 1, calculate normally */ uint256 newExp = rmul(frac, ln(base, RONE)); fracPow = rpowe(newExp); } return rmul(wholePow, fracPow); } /** @notice return base^exp with base in FP form and exp in Int @dev this function use a technique called: exponentiating by squaring complexity O(log(q)) @dev function is from Kyber. @dev base is a FP, exp is an Int, return a FP */ function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) { uint256 res = exp % 2 != 0 ? base : RONE; for (exp /= 2; exp != 0; exp /= 2) { base = rmul(base, base); if (exp % 2 != 0) { res = rmul(res, base); } } return res; } /** @dev y is an Int, returns an Int @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) @dev from Uniswap */ function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } /** @notice divide 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rdiv(uint256 x, uint256 y) internal pure returns (uint256) { return (y / 2).add(x.mul(RONE)).div(y); } /** @notice multiply 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rmul(uint256 x, uint256 y) internal pure returns (uint256) { return (RONE / 2).add(x.mul(y)).div(RONE); } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function subMax0(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a - b : 0; } } // 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.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 /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldTokenHolder { function redeemRewards() external; function setUpEmergencyMode(address spender) external; function yieldToken() external returns (address); function forge() external returns (address); function rewardToken() external returns (address); function expiry() external returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../interfaces/IWETH.sol"; import "./IPendleData.sol"; import "../libraries/PendleStructs.sol"; import "./IPendleMarketFactory.sol"; interface IPendleRouter { /** * @notice Emitted when a market for a future yield token and an ERC20 token is created. * @param marketFactoryId Forge identifier. * @param xyt The address of the tokenized future yield token as the base asset. * @param token The address of an ERC20 token as the quote asset. * @param market The address of the newly created market. **/ event MarketCreated( bytes32 marketFactoryId, address indexed xyt, address indexed token, address indexed market ); /** * @notice Emitted when a swap happens on the market. * @param trader The address of msg.sender. * @param inToken The input token. * @param outToken The output token. * @param exactIn The exact amount being traded. * @param exactOut The exact amount received. * @param market The market address. **/ event SwapEvent( address indexed trader, address inToken, address outToken, uint256 exactIn, uint256 exactOut, address market ); /** * @dev Emitted when user adds liquidity * @param sender The user who added liquidity. * @param token0Amount the amount of token0 (xyt) provided by user * @param token1Amount the amount of token1 provided by user * @param market The market address. * @param exactOutLp The exact LP minted */ event Join( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactOutLp ); /** * @dev Emitted when user removes liquidity * @param sender The user who removed liquidity. * @param token0Amount the amount of token0 (xyt) given to user * @param token1Amount the amount of token1 given to user * @param market The market address. * @param exactInLp The exact Lp to remove */ event Exit( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactInLp ); /** * @notice Gets a reference to the PendleData contract. * @return Returns the data contract reference. **/ function data() external view returns (IPendleData); /** * @notice Gets a reference of the WETH9 token contract address. * @return WETH token reference. **/ function weth() external view returns (IWETH); /*********** * FORGE * ***********/ function newYieldContracts( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (address ot, address xyt); function redeemAfterExpiry( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( bytes32 forgeId, address underlyingAsset, uint256 expiry, address user ) external returns (uint256 interests); function redeemUnderlying( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function renewYield( bytes32 forgeId, uint256 oldExpiry, address underlyingAsset, uint256 newExpiry, uint256 renewalRate ) external returns ( uint256 redeemedAmount, uint256 amountRenewed, address ot, address xyt, uint256 amountTokenMinted ); function tokenizeYield( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); /*********** * MARKET * ***********/ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external payable returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ); function addMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInAsset, uint256 minOutLp ) external payable returns (uint256 exactOutLp); function removeMarketLiquidityDual( bytes32 marketFactoryId, address xyt, address token, uint256 exactInLp, uint256 minOutXyt, uint256 minOutToken ) external returns (uint256 exactOutXyt, uint256 exactOutToken); function removeMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInLp, uint256 minOutAsset ) external returns (uint256 exactOutXyt, uint256 exactOutToken); /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param marketFactoryId Market Factory identifier. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket( bytes32 marketFactoryId, address xyt, address token ) external returns (address market); function bootstrapMarket( bytes32 marketFactoryId, address xyt, address token, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external payable; function swapExactIn( address tokenIn, address tokenOut, uint256 inTotalAmount, uint256 minOutTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 outTotalAmount); function swapExactOut( address tokenIn, address tokenOut, uint256 outTotalAmount, uint256 maxInTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 inTotalAmount); function redeemLpInterests(address market, address user) external returns (uint256 interests); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleRewardManager { event UpdateFrequencySet(address[], uint256[]); event SkippingRewardsSet(bool); event DueRewardsSettled( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountOut, address user ); function redeemRewards( address _underlyingAsset, uint256 _expiry, address _user ) external returns (uint256 dueRewards); function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function updateParamLManual(address _underlyingAsset, uint256 _expiry) external; function setUpdateFrequency( address[] calldata underlyingAssets, uint256[] calldata frequencies ) external; function setSkippingRewards(bool skippingRewards) external; function forgeId() external returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldContractDeployer { function forgeId() external returns (bytes32); function forgeOwnershipToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address ot); function forgeFutureYieldToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address xyt); function deployYieldTokenHolder(address yieldToken, uint256 expiry) external returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleYieldToken.sol"; import "./IPendlePausingManager.sol"; import "./IPendleMarket.sol"; interface IPendleData { /** * @notice Emitted when validity of a forge-factory pair is updated * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid); /** * @notice Emitted when Pendle and PendleFactory addresses have been updated. * @param treasury The address of the new treasury contract. **/ event TreasurySet(address treasury); /** * @notice Emitted when LockParams is changed **/ event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator); /** * @notice Emitted when ExpiryDivisor is changed **/ event ExpiryDivisorSet(uint256 expiryDivisor); /** * @notice Emitted when forge fee is changed **/ event ForgeFeeSet(uint256 forgeFee); /** * @notice Emitted when interestUpdateRateDeltaForMarket is changed * @param interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting **/ event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket); /** * @notice Emitted when market fees are changed * @param _swapFee new swapFee setting * @param _protocolSwapFee new protocolSwapFee setting **/ event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee); /** * @notice Emitted when the curve shift block delta is changed * @param _blockDelta new block delta setting **/ event CurveShiftBlockDeltaSet(uint256 _blockDelta); /** * @dev Emitted when new forge is added * @param marketFactoryId Human Readable Market Factory ID in Bytes * @param marketFactoryAddress The Market Factory Address */ event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress); /** * @notice Set/update validity of a forge-factory pair * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ function setForgeFactoryValidity( bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid ) external; /** * @notice Sets the PendleTreasury contract addresses. * @param newTreasury Address of new treasury contract. **/ function setTreasury(address newTreasury) external; /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function pausingManager() external view returns (IPendlePausingManager); /** * @notice Gets the treasury contract address where fees are being sent to. * @return Address of the treasury contract. **/ function treasury() external view returns (address); /*********** * FORGE * ***********/ /** * @notice Emitted when a forge for a protocol is added. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress); /** * @notice Adds a new forge for a protocol. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ function addForge(bytes32 forgeId, address forgeAddress) external; /** * @notice Store new OT and XYT details. * @param forgeId Forge and protocol identifier. * @param ot The address of the new XYT. * @param xyt The address of the new XYT. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. **/ function storeTokens( bytes32 forgeId, address ot, address xyt, address underlyingAsset, uint256 expiry ) external; /** * @notice Set a new forge fee * @param _forgeFee new forge fee **/ function setForgeFee(uint256 _forgeFee) external; /** * @notice Gets the OT and XYT tokens. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot The OT token references. * @return xyt The XYT token references. **/ function getPendleYieldTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt); /** * @notice Gets a forge given the identifier. * @param forgeId Forge and protocol identifier. * @return forgeAddress Returns the forge address. **/ function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress); /** * @notice Checks if an XYT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidXYT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); /** * @notice Checks if an OT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidOT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId) external view returns (bool); /** * @notice Gets a reference to a specific OT. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot Returns the reference to an OT. **/ function otTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot); /** * @notice Gets a reference to a specific XYT. * @param forgeId Forge and protocol identifier. * @param underlyingAsset Token address of the underlying asset * @param expiry Yield contract expiry in epoch time. * @return xyt Returns the reference to an XYT. **/ function xytTokens( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (IPendleYieldToken xyt); /*********** * MARKET * ***********/ event MarketPairAdded(address indexed market, address indexed xyt, address indexed token); function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external; function isMarket(address _addr) external view returns (bool result); function isXyt(address _addr) external view returns (bool result); function addMarket( bytes32 marketFactoryId, address xyt, address token, address market ) external; function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external; function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket) external; function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external; function setExpiryDivisor(uint256 _expiryDivisor) external; function setCurveShiftBlockDelta(uint256 _blockDelta) external; /** * @notice Displays the number of markets currently existing. * @return Returns markets length, **/ function allMarketsLength() external view returns (uint256); function forgeFee() external view returns (uint256); function interestUpdateRateDeltaForMarket() external view returns (uint256); function expiryDivisor() external view returns (uint256); function lockNumerator() external view returns (uint256); function lockDenominator() external view returns (uint256); function swapFee() external view returns (uint256); function protocolSwapFee() external view returns (uint256); function curveShiftBlockDelta() external view returns (uint256); function getMarketByIndex(uint256 index) external view returns (address market); /** * @notice Gets a market given a future yield token and an ERC20 token. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the market address. **/ function getMarket( bytes32 marketFactoryId, address xyt, address token ) external view returns (address market); /** * @notice Gets a market factory given the identifier. * @param marketFactoryId MarketFactory identifier. * @return marketFactoryAddress Returns the factory address. **/ function getMarketFactoryAddress(bytes32 marketFactoryId) external view returns (address marketFactoryAddress); function getMarketFromKey( address xyt, address token, bytes32 marketFactoryId ) external view returns (address market); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; struct TokenReserve { uint256 weight; uint256 balance; } struct PendingTransfer { uint256 amount; bool isOut; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; interface IPendleMarketFactory { /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param xyt Token address of the futuonlyCorere yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket(address xyt, address token) external returns (address market); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function marketFactoryId() external view returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IPendleBaseToken.sol"; import "./IPendleForge.sol"; interface IPendleYieldToken is IERC20, IPendleBaseToken { /** * @notice Emitted when burning OT or XYT tokens. * @param user The address performing the burn. * @param amount The amount to be burned. **/ event Burn(address indexed user, uint256 amount); /** * @notice Emitted when minting OT or XYT tokens. * @param user The address performing the mint. * @param amount The amount to be minted. **/ event Mint(address indexed user, uint256 amount); /** * @notice Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) external; /** * @notice Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) external; /** * @notice Gets the forge address of the PendleForge contract for this yield token. * @return Retuns the forge address. **/ function forge() external view returns (IPendleForge); /** * @notice Returns the address of the underlying asset. * @return Returns the underlying asset address. **/ function underlyingAsset() external view returns (address); /** * @notice Returns the address of the underlying yield token. * @return Returns the underlying yield token address. **/ function underlyingYieldToken() external view returns (address); /** * @notice let the router approve itself to spend OT/XYT/LP from any wallet * @param user user to approve **/ function approveRouter(address user) external; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "./IPendleRouter.sol"; import "./IPendleBaseToken.sol"; import "../libraries/PendleStructs.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleMarket is IERC20 { /** * @notice Emitted when reserves pool has been updated * @param reserve0 The XYT reserves. * @param weight0 The XYT weight * @param reserve1 The generic token reserves. * For the generic Token weight it can be inferred by (2^40) - weight0 **/ event Sync(uint256 reserve0, uint256 weight0, uint256 reserve1); function setUpEmergencyMode(address spender) external; function bootstrap( address user, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquiditySingle( address user, address inToken, uint256 inAmount, uint256 minOutLp ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquidityDual( address user, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external returns (PendingTransfer[2] memory transfers, uint256 lpOut); function removeMarketLiquidityDual( address user, uint256 inLp, uint256 minOutXyt, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function removeMarketLiquiditySingle( address user, address outToken, uint256 exactInLp, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function swapExactIn( address inToken, uint256 inAmount, address outToken, uint256 minOutAmount ) external returns (uint256 outAmount, PendingTransfer[2] memory transfers); function swapExactOut( address inToken, uint256 maxInAmount, address outToken, uint256 outAmount ) external returns (uint256 inAmount, PendingTransfer[2] memory transfers); function redeemLpInterests(address user) external returns (uint256 interests); function getReserves() external view returns ( uint256 xytBalance, uint256 xytWeight, uint256 tokenBalance, uint256 tokenWeight, uint256 currentBlock ); function factoryId() external view returns (bytes32); function token() external view returns (address); function xyt() external view returns (address); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleBaseToken is IERC20 { /** * @notice Decreases the allowance granted to spender by the caller. * @param spender The address to reduce the allowance from. * @param subtractedValue The amount allowance to subtract. * @return Returns true if allowance has decreased, otherwise false. **/ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @notice The yield contract start in epoch time. * @return Returns the yield start date. **/ function start() external view returns (uint256); /** * @notice The yield contract expiry in epoch time. * @return Returns the yield expiry date. **/ function expiry() external view returns (uint256); /** * @notice Increases the allowance granted to spender by the caller. * @param spender The address to increase the allowance from. * @param addedValue The amount allowance to add. * @return Returns true if allowance has increased, otherwise false **/ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @notice Returns the number of decimals the token uses. * @return Returns the token's decimals. **/ function decimals() external view returns (uint8); /** * @notice Returns the name of the token. * @return Returns the token's name. **/ function name() external view returns (string memory); /** * @notice Returns the symbol of the token. * @return Returns the token's symbol. **/ function symbol() external view returns (string memory); /** * @notice approve using the owner's signature **/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../interfaces/IPendleBaseToken.sol"; import "../interfaces/IPendleRouter.sol"; /** * @title PendleBaseToken * @dev The contract implements the standard ERC20 functions, plus some * Pendle specific fields and functions, namely: * - expiry * * This abstract contract is inherited by PendleFutureYieldToken * and PendleOwnershipToken contracts. **/ abstract contract PendleBaseToken is ERC20 { using SafeMath for uint256; uint256 public immutable start; uint256 public immutable expiry; IPendleRouter public immutable router; //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol bytes32 public immutable DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; //// End of EIP-2612 related part constructor( address _router, string memory _name, string memory _symbol, uint8 _decimals, uint256 _start, uint256 _expiry ) ERC20(_name, _symbol) { _setupDecimals(_decimals); start = _start; expiry = _expiry; router = IPendleRouter(_router); //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol, except for the noted parts below uint256 chainId; assembly { chainId := chainid() // chainid() is a function in assembly in this solidity version } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(_name)), // use our own _name here keccak256(bytes("1")), chainId, address(this) ) ); //// End of EIP-2612 related part } //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "PERMIT_EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNATURE"); _approve(owner, spender, value); } //// End of EIP-2612 related part function _beforeTokenTransfer( address from, address to, uint256 ) internal virtual override { require(to != address(this), "SEND_TO_TOKEN_CONTRACT"); require(to != from, "SEND_TO_SELF"); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldTokenCommon { /** * @notice Emitted when burning OT or XYT tokens. * @param user The address performing the burn. * @param amount The amount to be burned. **/ event Burn(address indexed user, uint256 amount); /** * @notice Emitted when minting OT or XYT tokens. * @param user The address performing the mint. * @param amount The amount to be minted. **/ event Mint(address indexed user, uint256 amount); /** * @notice Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) external; /** * @notice Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) external; /** * @notice Gets the forge address of the PendleForge contract for this yield token. * @return Retuns the forge address. **/ function forge() external view returns (address); /** * @notice Returns the address of the underlying asset. * @return Returns the underlying asset address. **/ function underlyingAsset() external view returns (address); /** * @notice Returns the address of the underlying yield token. * @return Returns the underlying yield token address. **/ function underlyingYieldToken() external view returns (address); } // 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; interface IComptroller { struct Market { bool isListed; uint256 collateralFactorMantissa; } function markets(address) external view returns (Market memory); function claimComp( address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers ) external; function getAccountLiquidity(address account) external view returns ( uint256 error, uint256 liquidity, uint256 shortfall ); function getAssetsIn(address account) external view returns (address[] memory); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleCompoundForge.sol"; // Forges should implement this Interface to guarantee compatibility with GenericMarket & Liq interface IPendleGenericForge is IPendleCompoundForge { } // SPDX-License-Identifier: BUSL-1.1 // solhint-disable ordering pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../libraries/ExpiryUtilsLib.sol"; import "../../interfaces/IPendleBaseToken.sol"; import "../../interfaces/IPendleData.sol"; import "../../interfaces/IPendleForgeV2.sol"; import "../../interfaces/IPendleRewardManager.sol"; import "../../interfaces/IPendleYieldContractDeployer.sol"; import "../../interfaces/IPendleYieldContractDeployerV2.sol"; import "../../interfaces/IPendleYieldTokenHolderV2.sol"; import "../../periphery/WithdrawableV2.sol"; import "../../libraries/MathLib.sol"; import "../../libraries/TokenUtilsLib.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /// @notice Common contract base for a forge implementation. /// @dev Each specific forge implementation will need to override necessary virtual functions abstract contract PendleForgeBaseV2 is IPendleForgeV2, WithdrawableV2, ReentrancyGuard { using ExpiryUtils for string; using SafeMath for uint256; using Math for uint256; using SafeERC20 for IERC20; struct PendleTokens { IPendleYieldToken xyt; IPendleYieldToken ot; } // the container here will contain any data needed by tokens. Fields of type that are not // uin256 will be upcasted to uint256 and downcasted when use struct TokenInfo { bool registered; uint256[] container; } IPendleRouter public immutable override router; IPendleData public immutable override data; bytes32 public immutable override forgeId; IERC20 public immutable override rewardToken; IPendleRewardManager public immutable override rewardManager; IPendleYieldContractDeployer public immutable override yieldContractDeployer; IPendlePausingManager public immutable pausingManager; mapping(address => mapping(uint256 => mapping(address => uint256))) public override dueInterests; mapping(address => mapping(uint256 => uint256)) public totalFee; mapping(address => mapping(uint256 => address)) public override yieldTokenHolders; // yieldTokenHolders[underlyingAsset][expiry] mapping(address => TokenInfo) public tokenInfo; string private constant OT = "OT"; string private constant XYT = "YT"; event RegisterTokens(bytes32 forgeId, address underlyingAsset, uint256[] container); modifier onlyXYT(address _underlyingAsset, uint256 _expiry) { require( msg.sender == address(data.xytTokens(forgeId, _underlyingAsset, _expiry)), "ONLY_YT" ); _; } modifier onlyOT(address _underlyingAsset, uint256 _expiry) { require( msg.sender == address(data.otTokens(forgeId, _underlyingAsset, _expiry)), "ONLY_OT" ); _; } modifier onlyRouter() { require(msg.sender == address(router), "ONLY_ROUTER"); _; } constructor( address _governanceManager, IPendleRouter _router, bytes32 _forgeId, address _rewardToken, address _rewardManager, address _yieldContractDeployer ) PermissionsV2(_governanceManager) { require(address(_router) != address(0), "ZERO_ADDRESS"); require(_forgeId != 0x0, "ZERO_BYTES"); // In the case there is no rewardToken, a valid ERC20 token must still be passed in for // compatibility reasons TokenUtils.requireERC20(_rewardToken); router = _router; forgeId = _forgeId; IPendleData _dataTemp = IPendleRouter(_router).data(); data = _dataTemp; rewardToken = IERC20(_rewardToken); rewardManager = IPendleRewardManager(_rewardManager); yieldContractDeployer = IPendleYieldContractDeployer(_yieldContractDeployer); pausingManager = _dataTemp.pausingManager(); } /** @dev INVARIANT: All write functions must go through this check. All XYT/OT transfers must go through this check as well. As such, XYT/OT transfers are also paused */ function checkNotPaused(address _underlyingAsset, uint256 _expiry) internal virtual { (bool paused, ) = pausingManager.checkYieldContractStatus( forgeId, _underlyingAsset, _expiry ); require(!paused, "YIELD_CONTRACT_PAUSED"); } /** @dev function has been depreciated but must still be left here to conform with the interface */ function setUpEmergencyMode( address, uint256, address ) external pure override { revert("FUNCTION_DEPRECIATED"); } /** @dev Only the forgeEmergencyHandler can call this function, when its in emergencyMode this will allow a spender to spend the whole balance of the specified tokens of the yieldTokenHolder contract @dev the spender should ideally be a contract with logic for users to withdraw out their funds @param extraFlag an optional flag for any forges which need an additional flag (like SushiComplex which allows either normal withdraw or emergencyWithdraw) */ function setUpEmergencyModeV2( address _underlyingAsset, uint256 _expiry, address spender, bool extraFlag ) external virtual override { (, bool emergencyMode) = pausingManager.checkYieldContractStatus( forgeId, _underlyingAsset, _expiry ); require(emergencyMode, "NOT_EMERGENCY"); (address forgeEmergencyHandler, , ) = pausingManager.forgeEmergencyHandler(); require(msg.sender == forgeEmergencyHandler, "NOT_EMERGENCY_HANDLER"); IPendleYieldTokenHolderV2(yieldTokenHolders[_underlyingAsset][_expiry]) .setUpEmergencyModeV2(spender, extraFlag); } /** @dev each element in the _underlyingAssets array will have one auxillary array in _tokenInfos to store necessary data. @dev only governance can call this. In V2 we no longer allow users to self-register new tokens */ function registerTokens(address[] calldata _underlyingAssets, uint256[][] calldata _tokenInfos) external virtual onlyGovernance { require(_underlyingAssets.length == _tokenInfos.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < _underlyingAssets.length; ++i) { TokenInfo storage info = tokenInfo[_underlyingAssets[i]]; require(!info.registered, "EXISTED_TOKENS"); verifyToken(_underlyingAssets[i], _tokenInfos[i]); info.registered = true; info.container = _tokenInfos[i]; emit RegisterTokens(forgeId, _underlyingAssets[i], _tokenInfos[i]); } } /** @dev this function should be implemented on a best effort basis, since we only call from governance anyway */ function verifyToken(address _underlyingAsset, uint256[] calldata _tokenInfo) public virtual; /** @notice to create a newYieldContract @dev Conditions: * only call by Router * the yield contract for this pair of _underlyingAsset & _expiry must not exist yet (checked on Router) */ function newYieldContracts(address _underlyingAsset, uint256 _expiry) external virtual override onlyRouter returns (address ot, address xyt) { checkNotPaused(_underlyingAsset, _expiry); address yieldToken = getYieldBearingToken(_underlyingAsset); uint8 underlyingAssetDecimals = IPendleYieldToken(_underlyingAsset).decimals(); // Deploy the OT contract -> XYT contract -> yieldTokenHolder ot = yieldContractDeployer.forgeOwnershipToken( _underlyingAsset, OT.concat(IPendleBaseToken(yieldToken).name(), _expiry, " "), OT.concat(IPendleBaseToken(yieldToken).symbol(), _expiry, "-"), underlyingAssetDecimals, _expiry ); xyt = yieldContractDeployer.forgeFutureYieldToken( _underlyingAsset, XYT.concat(IPendleBaseToken(yieldToken).name(), _expiry, " "), XYT.concat(IPendleBaseToken(yieldToken).symbol(), _expiry, "-"), underlyingAssetDecimals, _expiry ); // Because we have to conform with the IPendleForge interface, we must store // YieldContractDeployerV2 as V1, then upcast here yieldTokenHolders[_underlyingAsset][_expiry] = IPendleYieldContractDeployerV2( address(yieldContractDeployer) ).deployYieldTokenHolder(yieldToken, _expiry, tokenInfo[_underlyingAsset].container); data.storeTokens(forgeId, ot, xyt, _underlyingAsset, _expiry); emit NewYieldContracts(forgeId, _underlyingAsset, _expiry, ot, xyt, yieldToken); } /** @notice To redeem the underlying asset & due interests after the XYT has expired @dev Conditions: * only be called by Router * only callable after XYT has expired (checked on Router) */ function redeemAfterExpiry( address _user, address _underlyingAsset, uint256 _expiry ) external virtual override onlyRouter returns (uint256 redeemedAmount) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); uint256 expiredOTamount = tokens.ot.balanceOf(_user); require(expiredOTamount > 0, "NOTHING_TO_REDEEM"); // burn ot only, since users don't need xyt to redeem this tokens.ot.burn(_user, expiredOTamount); // calc the value of the OT after since it expired (total of its underlying value + dueInterests since expiry) // no forge fee is charged on redeeming OT. Forge fee is only charged on redeeming XYT redeemedAmount = _calcTotalAfterExpiry(_underlyingAsset, _expiry, expiredOTamount); // redeem the interest of any XYT (of the same underlyingAsset+expiry) that the user is having redeemedAmount = redeemedAmount.add( _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, false) ); // transfer back to the user _pushYieldToken(_underlyingAsset, _expiry, _user, redeemedAmount); // Notice for anyone taking values from this event: // The redeemedAmount includes the interest due to any XYT held // to get the exact yieldToken redeemed from OT, we need to deduct the (amount +forgeFeeAmount) of interests // settled that was emitted in the DueInterestsSettled event emitted earlier in this same transaction emit RedeemYieldToken( forgeId, _underlyingAsset, _expiry, expiredOTamount, redeemedAmount, _user ); } /** @notice To redeem the underlying asset & due interests before the expiry of the XYT. In this case, for each OT used to redeem, there must be an XYT (of the same yield contract) @dev Conditions: * only be called by Router * only callable if the XYT hasn't expired */ function redeemUnderlying( address _user, address _underlyingAsset, uint256 _expiry, uint256 _amountToRedeem ) external virtual override onlyRouter returns (uint256 redeemedAmount) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); tokens.ot.burn(_user, _amountToRedeem); tokens.xyt.burn(_user, _amountToRedeem); /* * calc the amount of underlying asset for OT + the amount of dueInterests for XYT * dueInterests for XYT has been updated during the process of burning XYT, so we skip updating dueInterests in the _beforeTransferDueInterests function */ redeemedAmount = _calcUnderlyingToRedeem(_underlyingAsset, _amountToRedeem).add( _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, true) ); // transfer back to the user _pushYieldToken(_underlyingAsset, _expiry, _user, redeemedAmount); // Notice for anyone taking values from this event: // The redeemedAmount includes the interest due to the XYT held // to get the exact yieldToken redeemed from OT+XYT, we need to deduct the // (amount +forgeFeeAmount) of interests settled that was emitted in the // DueInterestsSettled event emitted earlier in this same transaction emit RedeemYieldToken( forgeId, _underlyingAsset, _expiry, _amountToRedeem, redeemedAmount, _user ); return redeemedAmount; } /** @notice To redeem the due interests. This function can always be called regardless of whether the XYT has expired or not @dev Conditions: * only be called by Router */ function redeemDueInterests( address _user, address _underlyingAsset, uint256 _expiry ) external virtual override onlyRouter returns (uint256 amountOut) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); // update the dueInterests of the user before we transfer out amountOut = _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, false); _pushYieldToken(_underlyingAsset, _expiry, _user, amountOut); } /** @notice To update the dueInterests for users(before their balances of XYT changes) @dev This must be called before any transfer / mint/ burn action of XYT (and this has been implemented in the beforeTokenTransfer of the PendleFutureYieldToken) @dev Conditions: * Can only be called by the respective XYT contract, before transferring XYTs */ function updateDueInterests( address _underlyingAsset, uint256 _expiry, address _user ) external virtual override onlyXYT(_underlyingAsset, _expiry) nonReentrant { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); uint256 principal = tokens.xyt.balanceOf(_user); _updateDueInterests(principal, _underlyingAsset, _expiry, _user); } /** @notice To redeem the rewards (COMP, StkAAVE, SUSHI,...) for users(before their balances of OT changes) @dev This must be called before any transfer / mint/ burn action of OT (and this has been implemented in the beforeTokenTransfer of the PendleOwnershipToken) @dev Conditions: * Can only be called by the respective OT contract, before transferring OTs Note: This function is just a proxy to call to rewardManager */ function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external virtual override onlyOT(_underlyingAsset, _expiry) nonReentrant { checkNotPaused(_underlyingAsset, _expiry); rewardManager.updatePendingRewards(_underlyingAsset, _expiry, _user); } /** @notice To mint OT & XYT given that the user has transferred in _amountToTokenize of yieldToken @dev The newly minted OT & XYT can be minted to somebody else different from the user who transfer the aToken/cToken in @dev Conditions: * Should only be called by Router * The yield contract (OT & XYT) must not be expired yet (checked at Router) */ function mintOtAndXyt( address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) external virtual override onlyRouter returns ( address ot, address xyt, uint256 amountTokenMinted ) { checkNotPaused(_underlyingAsset, _expiry); // surely if any users call tokenizeYield, they will have to call this function IPendleYieldTokenHolderV2(yieldTokenHolders[_underlyingAsset][_expiry]).afterReceiveTokens( _amountToTokenize ); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); amountTokenMinted = _calcAmountToMint(_underlyingAsset, _amountToTokenize); // updatePendingRewards will be called in mint tokens.ot.mint(_to, amountTokenMinted); // updateDueInterests will be called in mint tokens.xyt.mint(_to, amountTokenMinted); emit MintYieldTokens( forgeId, _underlyingAsset, _expiry, _amountToTokenize, amountTokenMinted, _to ); return (address(tokens.ot), address(tokens.xyt), amountTokenMinted); } /** @notice To withdraw the forgeFee @dev Conditions: * Should only be called by Governance * This function must be the only way to withdrawForgeFee */ function withdrawForgeFee(address _underlyingAsset, uint256 _expiry) external virtual override onlyGovernance { checkNotPaused(_underlyingAsset, _expiry); //ping to update interest up to now _updateForgeFee(_underlyingAsset, _expiry, 0); uint256 _totalFee = totalFee[_underlyingAsset][_expiry]; totalFee[_underlyingAsset][_expiry] = 0; address treasuryAddress = data.treasury(); _pushYieldToken(_underlyingAsset, _expiry, treasuryAddress, _totalFee); emit ForgeFeeWithdrawn(forgeId, _underlyingAsset, _expiry, _totalFee); } function getYieldBearingToken(address _underlyingAsset) public virtual override returns (address); /** @notice To be called before the dueInterest of any users is redeemed. @param _skipUpdateDueInterests: this is set to true, if there was already a call to _updateDueInterests() in this transaction INVARIANT: there must be a transfer of the interests (amountOut) to the user after this function is called */ function _beforeTransferDueInterests( PendleTokens memory _tokens, address _underlyingAsset, uint256 _expiry, address _user, bool _skipUpdateDueInterests ) internal virtual returns (uint256 amountOut) { uint256 principal = _tokens.xyt.balanceOf(_user); if (!_skipUpdateDueInterests) { _updateDueInterests(principal, _underlyingAsset, _expiry, _user); } amountOut = dueInterests[_underlyingAsset][_expiry][_user]; dueInterests[_underlyingAsset][_expiry][_user] = 0; uint256 forgeFee = data.forgeFee(); uint256 forgeFeeAmount; /* * Collect the forgeFee * INVARIANT: all XYT interest payout must go through this line */ if (forgeFee > 0) { forgeFeeAmount = amountOut.rmul(forgeFee); amountOut = amountOut.sub(forgeFeeAmount); _updateForgeFee(_underlyingAsset, _expiry, forgeFeeAmount); } emit DueInterestsSettled( forgeId, _underlyingAsset, _expiry, amountOut, forgeFeeAmount, _user ); } /** @dev Must be the only way to transfer yieldToken out @dev summary of invariance logic: - This is the only function where the underlying yield tokens are transfered out - After this function executes (at the end of the .pushYieldTokens() function), we require that there must be enough yield tokens left to entertain all OT holders redeeming - As such, protocol users are always assured that they can redeem back their underlying yield tokens - Further note: this pushYieldTokens function relies on the same calc functions (_calcUnderlyingToRedeem and _calcTotalAfterExpiry) as the functions that called pushYieldTokens. Why it is safe to do that? Because to drain funds, hackers need to compromise the calc functions to return a very large result (hence large _amount in this function) but in the same transaction, they also need to compromise the very same calc function to return a very small result (to fool the contract that all the underlyingAsset of OTs are still intact). Doing these 2 compromises in one single transaction is much harder than doing just one */ function _pushYieldToken( address _underlyingAsset, uint256 _expiry, address _user, uint256 _amount ) internal virtual { if (_amount == 0) return; PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); uint256 otBalance = tokens.ot.totalSupply(); uint256 minNYieldAfterPush = block.timestamp < _expiry ? _calcUnderlyingToRedeem(_underlyingAsset, otBalance) : _calcTotalAfterExpiry(_underlyingAsset, _expiry, otBalance); IPendleYieldTokenHolderV2(yieldTokenHolders[_underlyingAsset][_expiry]).pushYieldTokens( _user, _amount, minNYieldAfterPush ); } function _getTokens(address _underlyingAsset, uint256 _expiry) internal view virtual returns (PendleTokens memory _tokens) { (_tokens.ot, _tokens.xyt) = data.getPendleYieldTokens(forgeId, _underlyingAsset, _expiry); } // There shouldn't be any fund in here // hence governance is allowed to withdraw anything from here. function _allowedToWithdraw(address) internal pure virtual override returns (bool allowed) { allowed = true; } /// INVARIANT: after _updateDueInterests is called, dueInterests[][][] must already be /// updated with all the due interest for the user, until exactly the current timestamp (no caching whatsoever) /// Refer to updateDueInterests function for more info function _updateDueInterests( uint256 _principal, address _underlyingAsset, uint256 _expiry, address _user ) internal virtual; /** @notice To update the amount of forgeFee (taking into account the compound interest effect) @dev To be called whenever the forge collect fees, or before withdrawing the fee @param _feeAmount the new fee that this forge just collected */ function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount ) internal virtual; /// calculate the (principal + interest) from the last action before expiry to now. function _calcTotalAfterExpiry( address _underlyingAsset, uint256 _expiry, uint256 redeemedAmount ) internal virtual returns (uint256 totalAfterExpiry); function _calcUnderlyingToRedeem(address, uint256 _amountToRedeem) internal virtual returns (uint256 underlyingToRedeem); function _calcAmountToMint(address, uint256 _amountToTokenize) internal virtual returns (uint256 amountToMint); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Compound ERC20 CToken * * @dev Implementation of the interest bearing token for the DLP protocol. * @author Compound */ interface ICToken is IERC20 { /*** User Interface ***/ function balanceOfUnderlying(address owner) external returns (uint256); function isCToken() external returns (bool); function underlying() external returns (address); function mint(uint256 mintAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256 error, uint256 balance, uint256 borrowed, uint256 exchangeRate ); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleForge.sol"; interface IPendleCompoundForge is IPendleForge { /** @dev directly get the exchangeRate from Compound */ function getExchangeRate(address _underlyingAsset) external returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library ExpiryUtils { struct Date { uint16 year; uint8 month; uint8 day; } uint256 private constant DAY_IN_SECONDS = 86400; uint256 private constant YEAR_IN_SECONDS = 31536000; uint256 private constant LEAP_YEAR_IN_SECONDS = 31622400; uint16 private constant ORIGIN_YEAR = 1970; /** * @notice Concatenates a Pendle token name/symbol, a yield token name/symbol, * and an expiry, using a delimiter (usually "-" or " "). * @param _bt The Pendle token name/symbol. * @param _yt The yield token name/symbol. * @param _expiry The expiry in epoch time. * @param _delimiter Can be any delimiter, but usually "-" or " ". * @return result Returns the concatenated string. **/ function concat( string memory _bt, string memory _yt, uint256 _expiry, string memory _delimiter ) internal pure returns (string memory result) { result = string( abi.encodePacked(_bt, _delimiter, _yt, _delimiter, toRFC2822String(_expiry)) ); } function toRFC2822String(uint256 _timestamp) internal pure returns (string memory s) { Date memory d = parseTimestamp(_timestamp); string memory day = uintToString(d.day); string memory month = monthName(d); string memory year = uintToString(d.year); s = string(abi.encodePacked(day, month, year)); } function getDaysInMonth(uint8 _month, uint16 _year) private pure returns (uint8) { if ( _month == 1 || _month == 3 || _month == 5 || _month == 7 || _month == 8 || _month == 10 || _month == 12 ) { return 31; } else if (_month == 4 || _month == 6 || _month == 9 || _month == 11) { return 30; } else if (isLeapYear(_year)) { return 29; } else { return 28; } } function getYear(uint256 _timestamp) private pure returns (uint16) { uint256 secondsAccountedFor = 0; uint16 year; uint256 numLeapYears; // Year year = uint16(ORIGIN_YEAR + _timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > _timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function isLeapYear(uint16 _year) private pure returns (bool) { return ((_year % 4 == 0) && (_year % 100 != 0)) || (_year % 400 == 0); } function leapYearsBefore(uint256 _year) private pure returns (uint256) { _year -= 1; return _year / 4 - _year / 100 + _year / 400; } function monthName(Date memory d) private pure returns (string memory) { string[12] memory months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; return months[d.month - 1]; } function parseTimestamp(uint256 _timestamp) private pure returns (Date memory d) { uint256 secondsAccountedFor = 0; uint256 buf; uint8 i; // Year d.year = getYear(_timestamp); buf = leapYearsBefore(d.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (d.year - ORIGIN_YEAR - buf); // Month uint256 secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, d.year); if (secondsInMonth + secondsAccountedFor > _timestamp) { d.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(d.month, d.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > _timestamp) { d.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } } function uintToString(uint256 _i) private pure returns (string memory) { 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 - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleForge.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleForgeV2 is IPendleForge { function setUpEmergencyModeV2( address _underlyingAsset, uint256 _expiry, address spender, bool extraFlag ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library TokenUtils { function requireERC20(address tokenAddr) internal view { require(IERC20(tokenAddr).totalSupply() > 0, "INVALID_ERC20"); } function requireERC20(IERC20 token) internal view { require(token.totalSupply() > 0, "INVALID_ERC20"); } } // 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; } }
*/ Collect the forgeFee INVARIANT: all XYT interest payout must go through this line/
function getYieldBearingToken(address _underlyingAsset) public virtual override returns (address); @notice To be called before the dueInterest of any users is redeemed. @param _skipUpdateDueInterests: this is set to true, if there was already a call to _updateDueInterests() in this transaction INVARIANT: there must be a transfer of the interests (amountOut) to the user after this function is called function _beforeTransferDueInterests( PendleTokens memory _tokens, address _underlyingAsset, uint256 _expiry, address _user, bool _skipUpdateDueInterests ) internal virtual returns (uint256 amountOut) { uint256 principal = _tokens.xyt.balanceOf(_user); if (!_skipUpdateDueInterests) { _updateDueInterests(principal, _underlyingAsset, _expiry, _user); } amountOut = dueInterests[_underlyingAsset][_expiry][_user]; dueInterests[_underlyingAsset][_expiry][_user] = 0; uint256 forgeFee = data.forgeFee(); uint256 forgeFeeAmount; if (forgeFee > 0) { forgeFeeAmount = amountOut.rmul(forgeFee); amountOut = amountOut.sub(forgeFeeAmount); _updateForgeFee(_underlyingAsset, _expiry, forgeFeeAmount); } emit DueInterestsSettled( forgeId, _underlyingAsset, _expiry, amountOut, forgeFeeAmount, _user ); } @dev summary of invariance logic:
1,396,701
[ 1, 19, 9302, 326, 21388, 14667, 2120, 29744, 6856, 30, 777, 18774, 56, 16513, 293, 2012, 1297, 1960, 3059, 333, 980, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10448, 491, 1919, 5968, 1345, 12, 2867, 389, 9341, 6291, 6672, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 2867, 1769, 203, 203, 565, 632, 20392, 2974, 506, 2566, 1865, 326, 6541, 29281, 434, 1281, 3677, 353, 283, 24903, 329, 18, 203, 565, 632, 891, 389, 7457, 1891, 30023, 2465, 25563, 30, 333, 353, 444, 358, 638, 16, 309, 1915, 1703, 1818, 279, 745, 358, 389, 2725, 30023, 2465, 25563, 1435, 316, 333, 2492, 203, 565, 2120, 29744, 6856, 30, 1915, 1297, 506, 279, 7412, 434, 326, 16513, 87, 261, 8949, 1182, 13, 358, 326, 729, 1839, 333, 445, 353, 2566, 203, 565, 445, 389, 5771, 5912, 30023, 2465, 25563, 12, 203, 3639, 453, 409, 298, 5157, 3778, 389, 7860, 16, 203, 3639, 1758, 389, 9341, 6291, 6672, 16, 203, 3639, 2254, 5034, 389, 22409, 16, 203, 3639, 1758, 389, 1355, 16, 203, 3639, 1426, 389, 7457, 1891, 30023, 2465, 25563, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 5034, 3844, 1182, 13, 288, 203, 3639, 2254, 5034, 8897, 273, 389, 7860, 18, 1698, 88, 18, 12296, 951, 24899, 1355, 1769, 203, 203, 3639, 309, 16051, 67, 7457, 1891, 30023, 2465, 25563, 13, 288, 203, 5411, 389, 2725, 30023, 2465, 25563, 12, 26138, 16, 389, 9341, 6291, 6672, 16, 389, 22409, 16, 389, 1355, 1769, 203, 3639, 289, 203, 203, 3639, 3844, 1182, 273, 6541, 2465, 25563, 63, 67, 9341, 6291, 6672, 6362, 67, 22409, 6362, 67, 1355, 15533, 203, 3639, 6541, 2465, 25563, 63, 67, 2 ]
pragma solidity ^0.4.18; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function () public payable { revert(); } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event SaleAgentUpdated(address currentSaleAgent); bool public mintingFinished = false; address public saleAgent; modifier notLocked() { require(msg.sender == owner || msg.sender == saleAgent || mintingFinished); _; } function setSaleAgent(address newSaleAgnet) public { require(msg.sender == saleAgent || msg.sender == owner); saleAgent = newSaleAgnet; SaleAgentUpdated(saleAgent); } function mint(address _to, uint256 _amount) public returns (bool) { require(msg.sender == saleAgent && !mintingFinished); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public returns (bool) { require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished); mintingFinished = true; MintFinished(); return true; } function transfer(address _to, uint256 _value) public notLocked returns (bool) { return super.transfer(_to, _value); } function transferFrom(address from, address to, uint256 value) public notLocked returns (bool) { return super.transferFrom(from, to, value); } } contract StagedCrowdsale is Pausable { using SafeMath for uint; //Structure of stage information struct Stage { uint hardcap; uint price; uint invested; uint closed; } //start date of sale uint public start; //period in days of sale uint public period; //sale's hardcap uint public totalHardcap; //total invested so far in the sale in wei uint public totalInvested; //sale's softcap uint public softcap; //sale's stages Stage[] public stages; event MilestoneAdded(uint hardcap, uint price); modifier saleIsOn() { require(stages.length > 0 && now >= start && now < lastSaleDate()); _; } modifier saleIsFinished() { require(totalInvested >= softcap || now > lastSaleDate()); _; } modifier isUnderHardcap() { require(totalInvested <= totalHardcap); _; } modifier saleIsUnsuccessful() { require(totalInvested < softcap || now > lastSaleDate()); _; } /** * counts current sale's stages */ function stagesCount() public constant returns(uint) { return stages.length; } /** * sets softcap * @param newSoftcap new softcap */ function setSoftcap(uint newSoftcap) public onlyOwner { require(newSoftcap > 0); softcap = newSoftcap.mul(1 ether); } /** * sets start date * @param newStart new softcap */ function setStart(uint newStart) public onlyOwner { start = newStart; } /** * sets period of sale * @param newPeriod new period of sale */ function setPeriod(uint newPeriod) public onlyOwner { period = newPeriod; } /** * adds stage to sale * @param hardcap stage's hardcap in ethers * @param price stage's price */ function addStage(uint hardcap, uint price) public onlyOwner { require(hardcap > 0 && price > 0); Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0); stages.push(stage); totalHardcap = totalHardcap.add(stage.hardcap); MilestoneAdded(hardcap, price); } /** * removes stage from sale * @param number index of item to delete */ function removeStage(uint8 number) public onlyOwner { require(number >= 0 && number < stages.length); Stage storage stage = stages[number]; totalHardcap = totalHardcap.sub(stage.hardcap); delete stages[number]; for (uint i = number; i < stages.length - 1; i++) { stages[i] = stages[i+1]; } stages.length--; } /** * updates stage * @param number index of item to update * @param hardcap stage's hardcap in ethers * @param price stage's price */ function changeStage(uint8 number, uint hardcap, uint price) public onlyOwner { require(number >= 0 && number < stages.length); Stage storage stage = stages[number]; totalHardcap = totalHardcap.sub(stage.hardcap); stage.hardcap = hardcap.mul(1 ether); stage.price = price; totalHardcap = totalHardcap.add(stage.hardcap); } /** * inserts stage * @param numberAfter index to insert * @param hardcap stage's hardcap in ethers * @param price stage's price */ function insertStage(uint8 numberAfter, uint hardcap, uint price) public onlyOwner { require(numberAfter < stages.length); Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0); totalHardcap = totalHardcap.add(stage.hardcap); stages.length++; for (uint i = stages.length - 2; i > numberAfter; i--) { stages[i + 1] = stages[i]; } stages[numberAfter + 1] = stage; } /** * deletes all stages */ function clearStages() public onlyOwner { for (uint i = 0; i < stages.length; i++) { delete stages[i]; } stages.length -= stages.length; totalHardcap = 0; } /** * calculates last sale date */ function lastSaleDate() public constant returns(uint) { return start + period * 1 days; } /** * returns index of current stage */ function currentStage() public saleIsOn isUnderHardcap constant returns(uint) { for(uint i = 0; i < stages.length; i++) { if(stages[i].closed == 0) { return i; } } revert(); } } contract CommonSale is StagedCrowdsale { //Our MYTC token MYTCToken public token; //slave wallet percentage uint public slaveWalletPercent = 50; //total percent rate uint public percentRate = 100; //min investment value in wei uint public minInvestment; //bool to check if wallet is initialized bool public slaveWalletInitialized; //bool to check if wallet percentage is initialized bool public slaveWalletPercentInitialized; //master wallet address address public masterWallet; //slave wallet address address public slaveWallet; //Agent for direct minting address public directMintAgent; // How much ETH each address has invested in crowdsale mapping (address => uint256) public investedAmountOf; // How much tokens crowdsale has credited for each investor address mapping (address => uint256) public tokenAmountOf; // Crowdsale contributors mapping (uint => address) public contributors; // Crowdsale unique contributors number uint public uniqueContributors; /** * event for token purchases logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param purchaseDate time of log */ event TokenPurchased(address indexed purchaser, uint256 value, uint256 purchaseDate); /** * event for token mint logging * @param to tokens destination * @param tokens minted * @param mintedDate time of log */ event TokenMinted(address to, uint tokens, uint256 mintedDate); /** * event for token refund * @param investor refunded account address * @param amount weis refunded * @param returnDate time of log */ event InvestmentReturned(address indexed investor, uint256 amount, uint256 returnDate); modifier onlyDirectMintAgentOrOwner() { require(directMintAgent == msg.sender || owner == msg.sender); _; } /** * sets MYTC token * @param newToken new token */ function setToken(address newToken) public onlyOwner { token = MYTCToken(newToken); } /** * sets minimum investement threshold * @param newMinInvestment new minimum investement threshold */ function setMinInvestment(uint newMinInvestment) public onlyOwner { minInvestment = newMinInvestment; } /** * sets master wallet address * @param newMasterWallet new master wallet address */ function setMasterWallet(address newMasterWallet) public onlyOwner { masterWallet = newMasterWallet; } /** * sets slave wallet address * @param newSlaveWallet new slave wallet address */ function setSlaveWallet(address newSlaveWallet) public onlyOwner { require(!slaveWalletInitialized); slaveWallet = newSlaveWallet; slaveWalletInitialized = true; } /** * sets slave wallet percentage * @param newSlaveWalletPercent new wallet percentage */ function setSlaveWalletPercent(uint newSlaveWalletPercent) public onlyOwner { require(!slaveWalletPercentInitialized); slaveWalletPercent = newSlaveWalletPercent; slaveWalletPercentInitialized = true; } /** * sets direct mint agent * @param newDirectMintAgent new agent */ function setDirectMintAgent(address newDirectMintAgent) public onlyOwner { directMintAgent = newDirectMintAgent; } /** * mints directly from network * @param to invesyor's adress to transfer the minted tokens to * @param investedWei number of wei invested */ function directMint(address to, uint investedWei) public onlyDirectMintAgentOrOwner saleIsOn { calculateAndMintTokens(to, investedWei); TokenPurchased(to, investedWei, now); } /** * splits investment into master and slave wallets for security reasons */ function createTokens() public whenNotPaused payable { require(msg.value >= minInvestment); uint masterValue = msg.value.mul(percentRate.sub(slaveWalletPercent)).div(percentRate); uint slaveValue = msg.value.sub(masterValue); masterWallet.transfer(masterValue); slaveWallet.transfer(slaveValue); calculateAndMintTokens(msg.sender, msg.value); TokenPurchased(msg.sender, msg.value, now); } /** * Calculates and records contributions * @param to invesyor's adress to transfer the minted tokens to * @param weiInvested number of wei invested */ function calculateAndMintTokens(address to, uint weiInvested) internal { //calculate number of tokens uint stageIndex = currentStage(); Stage storage stage = stages[stageIndex]; uint tokens = weiInvested.mul(stage.price); //if we have a new contributor if(investedAmountOf[msg.sender] == 0) { contributors[uniqueContributors] = msg.sender; uniqueContributors += 1; } //record contribution and tokens assigned investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(weiInvested); tokenAmountOf[msg.sender] = tokenAmountOf[msg.sender].add(tokens); //mint and update invested values mintTokens(to, tokens); totalInvested = totalInvested.add(weiInvested); stage.invested = stage.invested.add(weiInvested); //check if cap of staged is reached if(stage.invested >= stage.hardcap) { stage.closed = now; } } /** * Mint tokens * @param to adress destination to transfer the tokens to * @param tokens number of tokens to mint and transfer */ function mintTokens(address to, uint tokens) internal { token.mint(this, tokens); token.transfer(to, tokens); TokenMinted(to, tokens, now); } /** * Payable function */ function() external payable { createTokens(); } /** * Function to retrieve and transfer back external tokens * @param anotherToken external token received * @param to address destination to transfer the token to */ function retrieveExternalTokens(address anotherToken, address to) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(to, alienToken.balanceOf(this)); } /** * Function to refund funds if softcap is not reached and sale period is over */ function refund() public saleIsUnsuccessful { uint value = investedAmountOf[msg.sender]; investedAmountOf[msg.sender] = 0; msg.sender.transfer(value); InvestmentReturned(msg.sender, value, now); } } contract WhiteListToken is CommonSale { mapping(address => bool) public whiteList; modifier onlyIfWhitelisted() { require(whiteList[msg.sender]); _; } function addToWhiteList(address _address) public onlyDirectMintAgentOrOwner { whiteList[_address] = true; } function addAddressesToWhitelist(address[] _addresses) public onlyDirectMintAgentOrOwner { for (uint256 i = 0; i < _addresses.length; i++) { addToWhiteList(_addresses[i]); } } function deleteFromWhiteList(address _address) public onlyDirectMintAgentOrOwner { whiteList[_address] = false; } function deleteAddressesFromWhitelist(address[] _addresses) public onlyDirectMintAgentOrOwner { for (uint256 i = 0; i < _addresses.length; i++) { deleteFromWhiteList(_addresses[i]); } } } contract MYTCToken is MintableToken { //Token name string public constant name = "MYTC"; //Token symbol string public constant symbol = "MYTC"; //Token's number of decimals uint32 public constant decimals = 18; //Dictionary with locked accounts mapping (address => uint) public locked; /** * transfer for unlocked accounts */ function transfer(address _to, uint256 _value) public returns (bool) { require(locked[msg.sender] < now); return super.transfer(_to, _value); } /** * transfer from for unlocked accounts */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(locked[_from] < now); return super.transferFrom(_from, _to, _value); } /** * locks an account for given a number of days * @param addr account address to be locked * @param periodInDays days to be locked */ function lock(address addr, uint periodInDays) public { require(locked[addr] < now && (msg.sender == saleAgent || msg.sender == addr)); locked[addr] = now + periodInDays * 1 days; } } contract PreTge is CommonSale { //TGE Tge public tge; /** * event for PreTGE finalization logging * @param finalizer account who trigger finalization * @param saleEnded time of log */ event PreTgeFinalized(address indexed finalizer, uint256 saleEnded); /** * sets TGE to pass agent when sale is finished * @param newMainsale adress of TGE contract */ function setMainsale(address newMainsale) public onlyOwner { tge = Tge(newMainsale); } /** * sets TGE as new sale agent when sale is finished */ function setTgeAsSaleAgent() public whenNotPaused saleIsFinished onlyOwner { token.setSaleAgent(tge); PreTgeFinalized(msg.sender, now); } } contract Tge is WhiteListToken { //Team wallet address address public teamTokensWallet; //Bounty and advisors wallet address address public bountyTokensWallet; //Reserved tokens wallet address address public reservedTokensWallet; //Team percentage uint public teamTokensPercent; //Bounty and advisors percentage uint public bountyTokensPercent; //Reserved tokens percentage uint public reservedTokensPercent; //Lock period in days for team's wallet uint public lockPeriod; //maximum amount of tokens ever minted uint public totalTokenSupply; /** * event for TGE finalization logging * @param finalizer account who trigger finalization * @param saleEnded time of log */ event TgeFinalized(address indexed finalizer, uint256 saleEnded); /** * sets lock period in days for team's wallet * @param newLockPeriod new lock period in days */ function setLockPeriod(uint newLockPeriod) public onlyOwner { lockPeriod = newLockPeriod; } /** * sets percentage for team's wallet * @param newTeamTokensPercent new percentage for team's wallet */ function setTeamTokensPercent(uint newTeamTokensPercent) public onlyOwner { teamTokensPercent = newTeamTokensPercent; } /** * sets percentage for bounty's wallet * @param newBountyTokensPercent new percentage for bounty's wallet */ function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner { bountyTokensPercent = newBountyTokensPercent; } /** * sets percentage for reserved wallet * @param newReservedTokensPercent new percentage for reserved wallet */ function setReservedTokensPercent(uint newReservedTokensPercent) public onlyOwner { reservedTokensPercent = newReservedTokensPercent; } /** * sets max number of tokens to ever mint * @param newTotalTokenSupply max number of tokens (incl. 18 dec points) */ function setTotalTokenSupply(uint newTotalTokenSupply) public onlyOwner { totalTokenSupply = newTotalTokenSupply; } /** * sets address for team's wallet * @param newTeamTokensWallet new address for team's wallet */ function setTeamTokensWallet(address newTeamTokensWallet) public onlyOwner { teamTokensWallet = newTeamTokensWallet; } /** * sets address for bountys's wallet * @param newBountyTokensWallet new address for bountys's wallet */ function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner { bountyTokensWallet = newBountyTokensWallet; } /** * sets address for reserved wallet * @param newReservedTokensWallet new address for reserved wallet */ function setReservedTokensWallet(address newReservedTokensWallet) public onlyOwner { reservedTokensWallet = newReservedTokensWallet; } /** * Mints remaining tokens and finishes minting when sale is successful * No further tokens will be minted ever */ function endSale() public whenNotPaused saleIsFinished onlyOwner { // uint remainingPercentage = bountyTokensPercent.add(teamTokensPercent).add(reservedTokensPercent); // uint tokensGenerated = token.totalSupply(); uint foundersTokens = totalTokenSupply.mul(teamTokensPercent).div(percentRate); uint reservedTokens = totalTokenSupply.mul(reservedTokensPercent).div(percentRate); uint bountyTokens = totalTokenSupply.mul(bountyTokensPercent).div(percentRate); mintTokens(reservedTokensWallet, reservedTokens); mintTokens(teamTokensWallet, foundersTokens); mintTokens(bountyTokensWallet, bountyTokens); uint currentSupply = token.totalSupply(); if (currentSupply < totalTokenSupply) { // send remaining tokens to reserved wallet mintTokens(reservedTokensWallet, totalTokenSupply.sub(currentSupply)); } token.lock(teamTokensWallet, lockPeriod); token.finishMinting(); TgeFinalized(msg.sender, now); } /** * Payable function */ function() external onlyIfWhitelisted payable { require(now >= start && now < lastSaleDate()); createTokens(); } }
* Mint tokens @param to adress destination to transfer the tokens to @param tokens number of tokens to mint and transfer/
function mintTokens(address to, uint tokens) internal { token.mint(this, tokens); token.transfer(to, tokens); TokenMinted(to, tokens, now); }
5,930,155
[ 1, 49, 474, 2430, 225, 358, 1261, 663, 2929, 358, 7412, 326, 2430, 358, 225, 2430, 1300, 434, 2430, 358, 312, 474, 471, 7412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 5157, 12, 2867, 358, 16, 2254, 2430, 13, 2713, 288, 203, 565, 1147, 18, 81, 474, 12, 2211, 16, 2430, 1769, 203, 565, 1147, 18, 13866, 12, 869, 16, 2430, 1769, 203, 565, 3155, 49, 474, 329, 12, 869, 16, 2430, 16, 2037, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interface/ikswap.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"; // MasterChef is the master of RIT. He can make RIT 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 RIT is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract ReInvestPool is Third { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Router02 router; // Info of each uRIT. struct URITInfo { uint256 amount; // How many LP tokens the uRIT has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLpDebt; // 已经分的lp利息. uint256 lockTime; // // We do some fancy math here. Basically, any point in time, the amount of RITs // entitled to a uRIT but is pending to be distributed is: // // pending reward = (uRIT.amount * pool.accRITPerShare) - uRIT.rewardDebt // // Whenever a uRIT deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRITPerShare` (and `lastRewardBlock`) gets updated. // 2. URIT receives the pending reward sent to his/her address. // 3. URIT's `amount` gets updated. // 4. URIT'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. RITs to distribute per block. uint256 lastRewardBlock; // Last block number that RITs distribution occurs. uint256 accRITPerShare; // Accumulated RITs per share, times 1e12. See below. uint256 minAMount; uint256 maxAMount; ERC20 rewardToken; uint256 pid; uint256 lpSupply; uint256 deposit_fee; // 1/10000 uint256 withdraw_fee; // 1/10000 uint256 allWithdrawReward; } uint256 public baseReward = 100000000; IKswap public thirdPool; // The RIT TOKEN! Common public rit; // Dev address. address public devaddr; // Fee address. address public feeaddr; // RIT tokens created per block. uint256 public RITPerBlock; // Bonus muliplier for early RIT makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each uRIT that stakes LP tokens. mapping (uint256 => mapping (address => URITInfo)) public uRITInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; uint256 public fee = 50; // 30% of profit uint256 public feeBase = 100; // 1% of profit event Deposit(address indexed uRIT, uint256 indexed pid, uint256 amount); event Withdraw(address indexed uRIT, uint256 indexed pid, uint256 amount); event ReInvest(uint256 indexed pid); event SetDev(address indexed devAddress); event SetFee(address indexed feeAddress); event SetRITPerBlock(uint256 _RITPerBlock); event SetPool(uint256 pid ,address lpaddr,uint256 point,uint256 min,uint256 max); constructor( Common _rit, address _feeaddr, address _devaddr, uint256 _RITPerBlock, IUniswapV2Router02 _router, IKswap _pool ) public { rit = _rit; feeaddr = _feeaddr; devaddr = _devaddr; RITPerBlock = _RITPerBlock; router = _router; thirdPool = _pool; initRouters(); } function poolLength() external view returns (uint256) { return poolInfo.length; } function setBaseReward(uint256 _base) public onlyOwner { baseReward = _base; } function setRITPerBlock(uint256 _RITPerBlock) public onlyOwner { RITPerBlock = _RITPerBlock; emit SetRITPerBlock(_RITPerBlock); } function setFeebase(uint256 _feeBase) public onlyOwner { feeBase = _feeBase; } function setFee(uint256 _fee) public onlyOwner { fee = _fee; } function GetPoolInfo(uint256 id) external view returns (PoolInfo memory) { return poolInfo[id]; } function GetURITInfo(uint256 id,address addr) external view returns (URITInfo memory) { return uRITInfo[id][addr]; } // 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 _pid,uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate,uint256 _min,uint256 _max,uint256 _deposit_fee,uint256 _withdraw_fee,ERC20 _rewardToken) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRITPerShare: 0, minAMount:_min, maxAMount:_max, rewardToken:_rewardToken, pid:_pid, lpSupply:0, deposit_fee:_deposit_fee, withdraw_fee:_withdraw_fee, allWithdrawReward:0 })); approve(poolInfo[poolInfo.length-1]); emit SetPool(poolInfo.length-1 , address(_lpToken), _allocPoint, _min, _max); } // Update the given pool's RIT 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) 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; 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); } // View function to see pending RITs on frontend. function pending(uint256 _pid, address _uRIT) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; URITInfo storage uRIT = uRITInfo[_pid][_uRIT]; uint256 accRITPerShare = pool.accRITPerShare; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 RITReward = multiplier.mul(RITPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRITPerShare = accRITPerShare.add(RITReward.mul(1e12).div(lpSupply)); } return uRIT.amount.mul(accRITPerShare).div(1e12).sub(uRIT.rewardDebt); } // View function to see pending RITs on frontend. function rewardLp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; URITInfo storage uRIT = uRITInfo[_pid][_user]; if(thirdPool.userInfo(pool.pid, address(this)).amount <= 0){ return 0; } uint256 ba = getWithdrawBalance(_pid, userShares[_pid][_user], thirdPool.userInfo(pool.pid, address(this)).amount); if(ba > uRIT.amount){ return ba.sub(uRIT.amount); } return 0; } // View function to see pending RITs on frontend. // View function to see pending RITs on frontend. function allRewardLp(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; if(thirdPool.userInfo(pool.pid, address(this)).amount<=pool.lpSupply){ return 0; } return pool.allWithdrawReward.add(thirdPool.userInfo(pool.pid, address(this)).amount.sub(pool.lpSupply)); } // 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 RITReward = multiplier.mul(RITPerBlock).mul(pool.allocPoint).div(totalAllocPoint); rit.mint(address(this), RITReward); // Liquidity reward pool.accRITPerShare = pool.accRITPerShare.add(RITReward.mul(1e12).div(pool.lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for RIT allocation. function deposit(uint256 _pid, uint256 _amount) public { require(pause==0,'can not execute'); PoolInfo storage pool = poolInfo[_pid]; URITInfo storage uRIT = uRITInfo[_pid][msg.sender]; updatePool(_pid, 0, true); harvest(_pid);// 剩余利息进行复投 uint256 pendingT = uRIT.amount.mul(pool.accRITPerShare).div(1e12).sub(uRIT.rewardDebt); if(pendingT > 0) { safeRITTransfer(msg.sender, pendingT); } 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); } uint256 _before = thirdPool.userInfo(pool.pid,address(this)).amount; pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); thirdPool.deposit(pool.pid, _amount); uRIT.amount = uRIT.amount.add(_amount); if (pool.minAMount > 0 && uRIT.amount < pool.minAMount){ revert("amount is too low"); } if (pool.maxAMount > 0 && uRIT.amount > pool.maxAMount){ revert("amount is too high"); } uint256 _after = thirdPool.userInfo(pool.pid,address(this)).amount; pool.lpSupply = pool.lpSupply.add(_amount); _mint(_pid, _after.sub(_before), msg.sender, _before); } uRIT.rewardDebt = uRIT.amount.mul(pool.accRITPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // execute when only bug occur function safeWithdraw(uint256 _pid) public onlyOwner{ require(pause==1,'can not execute'); PoolInfo storage pool = poolInfo[_pid]; thirdPool.withdraw(pool.pid, pool.lpSupply); pool.lpToken.safeTransfer(address(msg.sender), pool.lpSupply); uint256 ba = pool.rewardToken.balanceOf(address(this)); // if(ba<=0){ return; } pool.rewardToken.transfer(devaddr,ba); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require(pause==0,'can not execute'); PoolInfo storage pool = poolInfo[_pid]; URITInfo storage uRIT = uRITInfo[_pid][msg.sender]; require(uRIT.amount >= _amount, "withdraw: not good"); updatePool(_pid, 0, false); uint256 pendingT = uRIT.amount.mul(pool.accRITPerShare).div(1e12).sub(uRIT.rewardDebt); if(pendingT > 0) { safeRITTransfer(msg.sender, pendingT); } if(_amount > 0) { uint256 fene = thirdPool.userInfo(pool.pid,address(this)).amount; uint256 _shares = getWithdrawShares(_pid, _amount, msg.sender, uRIT.amount); uint256 should_withdraw = getWithdrawBalance(_pid, _shares, fene); pool.lpSupply = pool.lpSupply.sub(_amount); uRIT.amount = uRIT.amount.sub(_amount); thirdPool.withdraw(pool.pid, should_withdraw); // if(pool.withdraw_fee>0){ uint256 needFee = _amount.mul(pool.withdraw_fee).div(10000); _amount = _amount.sub(needFee); pool.lpToken.safeTransfer(devaddr, needFee); } // safeLpTransfer(_pid,address(msg.sender),_amount); _burn(_pid, _shares, msg.sender); } harvest(_pid); // uRIT.rewardDebt = uRIT.amount.mul(pool.accRITPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Safe RIT transfer function, just in case if rounding error causes pool to not have enough RITs. function safeLpTransfer(uint256 _pid,address _to, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 RITBal = pool.lpToken.balanceOf(address(this)); if(RITBal>_amount){ pool.allWithdrawReward = pool.allWithdrawReward.add(RITBal.sub(_amount)); } pool.lpToken.transfer(_to, RITBal); } function approve(PoolInfo memory pool) private { pool.rewardToken.approve(address(router),uint256(-1)); address token0 = IUniswapV2Pair(address(pool.lpToken)).token0(); address token1 = IUniswapV2Pair(address(pool.lpToken)).token1(); IERC20(token0).approve(address(router),uint256(-1)); IERC20(token1).approve(address(router),uint256(-1)); pool.lpToken.approve(address(thirdPool), uint256(-1)); } // function calcProfit(uint256 _pid) private{ PoolInfo storage pool = poolInfo[_pid]; thirdPool.deposit(pool.pid, 0); // uint256 ba = pool.rewardToken.balanceOf(address(this)); if(ba<baseReward){ return; } // pool.rewardToken.transfer(devaddr,ba); uint256 profitFee = ba.mul(fee).div(feeBase); pool.rewardToken.transfer(feeaddr,profitFee); ba = ba.sub(profitFee); uint256 half = ba.div(2); ba = ba.sub(half); if(half<=0 || ba<=0){ return; } address token0 = IUniswapV2Pair(address(pool.lpToken)).token0(); if(token0 != address(pool.rewardToken)){ // swap(router,address(pool.rewardToken),token0,half); } address token1 = IUniswapV2Pair(address(pool.lpToken)).token1(); if(token1 != address(pool.rewardToken)){ // swap(router,address(pool.rewardToken),token1,ba); } uint256 token0Ba = IERC20(token0).balanceOf(address(this)); uint256 token1Ba = IERC20(token1).balanceOf(address(this)); if( token0Ba <= 0 || token1Ba <= 0 ){ // 没有余额 return; } // IERC20(token0).transfer(devaddr,IERC20(token0).balanceOf(address(this))); // IERC20(token1).transfer(devaddr,IERC20(token1).balanceOf(address(this))); // return; (uint256 t0,uint256 t1,) = IUniswapV2Pair(address(pool.lpToken)).getReserves(); if( t0<=0 || t1<=0 ){ // 没有流动性 return; } uint256 out=0; uint256 liqui=0; if (t0.mul(token1Ba)>token0Ba.mul(t1)){ out = token0Ba.mul(t1).div(t0); if(out <= 0){ return; } (,,liqui) = router.addLiquidity(token0, token1, token0Ba, out, 0, 0, address(this), now.add(1800)); // if(autoi){ // token1Ba = token1Ba.sub(out); // if (token1Ba>0){ // path[0] = token1; // path[1] = address(pool.rewardToken); // router.swapExactTokensForTokens(token1Ba, 0, path, address(this), block.timestamp.add(1800)); // } // } } else{ // out = token1Ba.mul(t0).div(t1); if(out <= 0){ return; } (,,liqui) = router.addLiquidity(token0, token1, out, token1Ba, 0, 0, address(this), now.add(1800)); // if(autoi){ // token0Ba = token0Ba.sub(out); // if (token0Ba>0){ // path[0] = token0; // path[1] = address(pool.rewardToken); // router.swapExactTokensForTokens(token0Ba, 0, path, address(this), block.timestamp.add(10)); // } // } // pool.lpToken.transfer(devaddr,liqui); // return; } futou(pool); // } function futou(PoolInfo memory pool) private { uint256 ba = pool.lpToken.balanceOf(address(this)); if(ba<=0){ return; } if(pool.lpSupply<=0){ pool.lpToken.transfer(feeaddr,ba); return; } // pool.lpToken.transfer(devaddr,ba); thirdPool.deposit(pool.pid,ba); } // auto reinvest function harvest(uint256 _pid) public { calcProfit(_pid); // emit ReInvest(_pid); } // Safe RIT transfer function, just in case if rounding error causes pool to not have enough RITs. function safeRITTransfer(address _to, uint256 _amount) internal { uint256 RITBal = rit.balanceOf(address(this)); if(RITBal<=0){ return; } if (_amount > RITBal) { rit.transfer(_to, RITBal); } else { rit.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 fee address by the previous dev. function setFeeAddr(address _feeaddr) public { require(msg.sender == feeaddr, "fee: wut?"); require(_feeaddr != address(0), "_feeaddr is address(0)"); feeaddr = _feeaddr; emit SetFee(_feeaddr); } }
IERC20(token0).transfer(devaddr,IERC20(token0).balanceOf(address(this))); IERC20(token1).transfer(devaddr,IERC20(token1).balanceOf(address(this))); return;
(uint256 t0,uint256 t1,) = IUniswapV2Pair(address(pool.lpToken)).getReserves();
986,024
[ 1, 45, 654, 39, 3462, 12, 2316, 20, 2934, 13866, 12, 5206, 4793, 16, 45, 654, 39, 3462, 12, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 467, 654, 39, 3462, 12, 2316, 21, 2934, 13866, 12, 5206, 4793, 16, 45, 654, 39, 3462, 12, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 327, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 261, 11890, 5034, 268, 20, 16, 11890, 5034, 268, 21, 16, 13, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 2867, 12, 6011, 18, 9953, 1345, 13, 2934, 588, 607, 264, 3324, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract SmartChefMarket is Ownable { using SafeERC20 for IERC20; uint public totalTokensPlaced; uint public lastRewardBlock; address[] public listRewardTokens; address market; struct RewardToken { uint rewardPerBlock; uint startBlock; uint accTokenPerShare; // Accumulated Tokens per share, times 1e12. uint rewardsForWithdrawal; bool enabled; // true - enable; false - disable } mapping (address => uint) public userNFTPlaced; //How many tokens placed in market by user mapping (address => mapping(address => uint)) public rewardDebt; //user => (rewardToken => rewardDebt); mapping (address => RewardToken) public rewardTokens; event AddNewTokenReward(address token); event DisableTokenReward(address token); event ChangeTokenReward(address indexed token, uint rewardPerBlock); // event StakeTokens(address indexed user, uint amountRB, uint[] tokensId); // event UnstakeToken(address indexed user, uint amountRB, uint[] tokensId); event EmergencyWithdraw(address indexed user, uint tokenCount); modifier onlyMarket(){ require(msg.sender == market, "Only market"); _; } function isTokenInList(address _token) internal view returns(bool){ address[] memory _listRewardTokens = listRewardTokens; bool thereIs = false; for(uint i = 0; i < _listRewardTokens.length; i++){ if(_listRewardTokens[i] == _token){ thereIs = true; break; } } return thereIs; } function getListRewardTokens() public view returns(address[] memory){ address[] memory list = new address[](listRewardTokens.length); list = listRewardTokens; return list; } function addNewTokenReward(address _newToken, uint _startBlock, uint _rewardPerBlock) public onlyOwner { require(_newToken != address(0), "Address shouldn't be 0"); require(isTokenInList(_newToken) == false, "Token is already in the list"); listRewardTokens.push(_newToken); if(_startBlock == 0){ rewardTokens[_newToken].startBlock = block.number + 1; } else { rewardTokens[_newToken].startBlock = _startBlock; } rewardTokens[_newToken].rewardPerBlock = _rewardPerBlock; if(IERC20(_newToken).balanceOf(address(this)) > rewardTokens[_newToken].rewardsForWithdrawal){ rewardTokens[_newToken].enabled = true; } else { rewardTokens[_newToken].enabled = false; } emit AddNewTokenReward(_newToken); } function disableTokenReward(address _token) public onlyOwner { require(isTokenInList(_token), "Token not in the list"); rewardTokens[_token].enabled = false; emit DisableTokenReward(_token); } function enableTokenReward(address _token, uint _startBlock, uint _rewardPerBlock) public onlyOwner { require(isTokenInList(_token), "Token not in the list"); require(_startBlock >= block.number, "Start block Must be later than current"); if(IERC20(_token).balanceOf(address(this)) > rewardTokens[_token].rewardsForWithdrawal){ rewardTokens[_token].enabled = true; rewardTokens[_token].startBlock = _startBlock; rewardTokens[_token].rewardPerBlock = _rewardPerBlock; emit ChangeTokenReward(_token, _rewardPerBlock); } else { revert("Not enough balance of token"); } updatePool(); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint _from, uint _to) public pure returns (uint) { if(_to > _from){ return _to - _from; } else { return 0; } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (address[] memory, uint[] memory) { uint nftPlaced = userNFTPlaced[_user]; uint[] memory rewards = new uint[](listRewardTokens.length); if(nftPlaced == 0){ return (listRewardTokens, rewards); } uint _totalTokensPlaced = totalTokensPlaced; uint _multiplier = getMultiplier(lastRewardBlock, block.number); uint _accTokenPerShare = 0; for(uint i = 0; i < listRewardTokens.length; i++){ address curToken = listRewardTokens[i]; RewardToken memory curRewardToken = rewardTokens[curToken]; if (_multiplier != 0 && _totalTokensPlaced != 0) { _accTokenPerShare = curRewardToken.accTokenPerShare + (_multiplier * curRewardToken.rewardPerBlock * 1e12 / _totalTokensPlaced); } else { _accTokenPerShare = curRewardToken.accTokenPerShare; } rewards[i] = (nftPlaced * _accTokenPerShare / 1e12) - rewardDebt[_user][curToken]; } return (listRewardTokens, rewards); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { uint multiplier = getMultiplier(lastRewardBlock, block.number); uint _totalTokenPlaced = totalTokensPlaced; //Gas safe if(multiplier == 0){ return; } lastRewardBlock = block.number; if(_totalTokenPlaced == 0){ return; } for(uint i = 0; i < listRewardTokens.length; i++){ address curToken = listRewardTokens[i]; RewardToken memory curRewardToken = rewardTokens[curToken]; if(curRewardToken.enabled == false || curRewardToken.startBlock >= block.number){ continue; } else { uint curMultiplier; if(getMultiplier(curRewardToken.startBlock, block.number) < multiplier){ curMultiplier = getMultiplier(curRewardToken.startBlock, block.number); } else { curMultiplier = multiplier; } uint tokenReward = curRewardToken.rewardPerBlock * curMultiplier; rewardTokens[curToken].rewardsForWithdrawal += tokenReward; rewardTokens[curToken].accTokenPerShare += (tokenReward * 1e12) / _totalTokenPlaced; } } } function withdrawReward() public { _withdrawReward(msg.sender); } function _updateRewardDebt(address _user) internal { for(uint i = 0; i < listRewardTokens.length; i++){ rewardDebt[_user][listRewardTokens[i]] = userNFTPlaced[_user] * rewardTokens[listRewardTokens[i]].accTokenPerShare / 1e12; } } function _withdrawReward(address _user) internal { updatePool(); uint nftPlaced = userNFTPlaced[_user]; address[] memory _listRewardTokens = listRewardTokens; if(nftPlaced == 0){ return; } for(uint i = 0; i < _listRewardTokens.length; i++){ RewardToken storage curRewardToken = rewardTokens[_listRewardTokens[i]]; uint pending = nftPlaced * curRewardToken.accTokenPerShare / 1e12 - rewardDebt[_user][_listRewardTokens[i]]; if(pending > 0){ curRewardToken.rewardsForWithdrawal -= pending; rewardDebt[_user][_listRewardTokens[i]] = nftPlaced * curRewardToken.accTokenPerShare / 1e12; IERC20(_listRewardTokens[i]).safeTransfer(address(_user), pending); } } } function updateStakedTokens(address _user, uint amount) public onlyMarket { _withdrawReward(_user); totalTokensPlaced -= userNFTPlaced[_user]; userNFTPlaced[_user] = amount; totalTokensPlaced += amount; _updateRewardDebt(_user); } // Withdraw reward token. EMERGENCY ONLY. function emergencyRewardTokenWithdraw(address _token, uint256 _amount) public onlyOwner { require(IERC20(_token).balanceOf(address(this)) >= _amount, "Not enough balance"); IERC20(_token).safeTransfer(msg.sender, _amount); } function setMarket(address _market) public onlyOwner { market = _market; } }
event StakeTokens(address indexed user, uint amountRB, uint[] tokensId); event UnstakeToken(address indexed user, uint amountRB, uint[] tokensId);
event EmergencyWithdraw(address indexed user, uint tokenCount);
13,016,425
[ 1, 2575, 934, 911, 5157, 12, 2867, 8808, 729, 16, 2254, 3844, 19437, 16, 2254, 8526, 2430, 548, 1769, 565, 871, 1351, 334, 911, 1345, 12, 2867, 8808, 729, 16, 2254, 3844, 19437, 16, 2254, 8526, 2430, 548, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 1147, 1380, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xcBba3dc6457C94285258F591Fd67A9588c812df7/sources/project_/contracts/STokenV1.sol
@notice Revokes Financial Manager role from `_address` @dev If `_address` had been revoked Financial Manager role, emits a {RoleRevoked} event Requirements:the caller must have SuperAdmin role Revokes allowance to transfer tokens from Treasury for `_address` @param _address address to revoke Manager role from it
function removeFinancialManager(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { _revokeRole(FINANCIAL_MANAGER_ROLE, _address); _approve(_corporateTreasury, _address, 0); }
851,958
[ 1, 10070, 601, 281, 9458, 19292, 649, 8558, 2478, 628, 1375, 67, 2867, 68, 225, 971, 1375, 67, 2867, 68, 9323, 2118, 22919, 9458, 19292, 649, 8558, 2478, 16, 24169, 279, 288, 2996, 10070, 14276, 97, 871, 1377, 29076, 30, 5787, 4894, 1297, 1240, 14845, 4446, 2478, 1377, 14477, 601, 281, 1699, 1359, 358, 7412, 2430, 628, 399, 266, 345, 22498, 364, 1375, 67, 2867, 68, 225, 389, 2867, 1758, 358, 18007, 8558, 2478, 628, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 6187, 19292, 649, 1318, 12, 2867, 389, 2867, 13, 203, 3639, 3903, 203, 3639, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 203, 565, 288, 203, 3639, 389, 9083, 3056, 2996, 12, 7263, 1258, 39, 6365, 67, 19402, 67, 16256, 16, 389, 2867, 1769, 203, 3639, 389, 12908, 537, 24899, 3850, 3831, 340, 56, 266, 345, 22498, 16, 389, 2867, 16, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ・ * ★ ・ 。  ・ ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ ​ ` .-:::::-.` `-::---...``` `-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo: .--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy `-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy `------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy .--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy `-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy .------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy .--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy `----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy .------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy `.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy .--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo .------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo ````` *  ・ 。     ・  ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ *  ゚。·*・。 ゚*    ☆゚・。°*. ゚   ・ ゚*。・゚★。   ・ *゚。   *  ・゚*。★・ ☆∴。 * ・ 。 */ // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; pragma abicoder v2; // solhint-disable-line import "./mixins/FoundationTreasuryNode.sol"; import "./mixins/roles/FoundationAdminRole.sol"; import "./mixins/NFTMarketCore.sol"; import "./mixins/SendValueWithFallbackWithdraw.sol"; import "./mixins/NFTMarketCreators.sol"; import "./mixins/NFTMarketFees.sol"; import "./mixins/NFTMarketAuction.sol"; import "./mixins/NFTMarketReserveAuction.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @title A market for NFTs on Foundation. * @dev This top level file holds no data directly to ease future upgrades. */ contract FNDNFTMarket is FoundationTreasuryNode, FoundationAdminRole, NFTMarketCore, ReentrancyGuardUpgradeable, NFTMarketCreators, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction, NFTMarketReserveAuction { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ function initialize(address payable treasury) public initializer { FoundationTreasuryNode._initializeFoundationTreasuryNode(treasury); NFTMarketAuction._initializeNFTMarketAuction(); NFTMarketReserveAuction._initializeNFTMarketReserveAuction(); } /** * @notice Allows Foundation to update the market configuration. */ function adminUpdateConfig( uint256 minPercentIncrementInBasisPoints, uint256 duration, uint256 primaryF8nFeeBasisPoints, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) public onlyFoundationAdmin { _updateReserveAuctionConfig(minPercentIncrementInBasisPoints, duration); _updateMarketFees(primaryF8nFeeBasisPoints, secondaryF8nFeeBasisPoints, secondaryCreatorFeeBasisPoints); } /** * @dev Checks who the seller for an NFT is, this will check escrow or return the current owner if not in escrow. * This is a no-op function required to avoid compile errors. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override(NFTMarketCore, NFTMarketReserveAuction) returns (address) { return super._getSellerFor(nftContract, tokenId); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Foundation treasury contract. */ abstract contract FoundationTreasuryNode is Initializable { using AddressUpgradeable for address payable; address payable private treasury; /** * @dev Called once after the initial deployment to set the Foundation treasury address. */ function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract"); treasury = _treasury; } /** * @notice Returns the address of the Foundation treasury. */ function getFoundationTreasury() public view returns (address payable) { return treasury; } // `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way. uint256[2000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "../../interfaces/IAdminRole.sol"; import "../FoundationTreasuryNode.sol"; /** * @notice Allows a contract to leverage an admin role defined by the Foundation contract. */ abstract contract FoundationAdminRole is FoundationTreasuryNode { // This file uses 0 data slots (other than what's included via FoundationTreasuryNode) modifier onlyFoundationAdmin() { require( IAdminRole(getFoundationTreasury()).isAdmin(msg.sender), "FoundationAdminRole: caller does not have the Admin role" ); _; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; /** * @notice A place for common modifiers and functions used by various NFTMarket mixins, if any. * @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree. */ abstract contract NFTMarketCore { /** * @dev If the auction did not have an escrowed seller to return, this falls back to return the current owner. * This allows functions to calculate the correct fees before the NFT has been listed in auction. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual returns (address) { return IERC721Upgradeable(nftContract).ownerOf(tokenId); } // 50 slots were consumed by adding ReentrancyGuardUpgradeable uint256[950] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance * for future withdrawal instead. */ abstract contract SendValueWithFallbackWithdraw is ReentrancyGuardUpgradeable { using AddressUpgradeable for address payable; using SafeMathUpgradeable for uint256; mapping(address => uint256) private pendingWithdrawals; event WithdrawPending(address indexed user, uint256 amount); event Withdrawal(address indexed user, uint256 amount); /** * @notice Returns how much funds are available for manual withdraw due to failed transfers. */ function getPendingWithdrawal(address user) public view returns (uint256) { return pendingWithdrawals[user]; } /** * @notice Allows a user to manually withdraw funds which originally failed to transfer. */ function withdraw() public nonReentrant { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "No funds are pending withdrawal"); pendingWithdrawals[msg.sender] = 0; msg.sender.sendValue(amount); emit Withdrawal(msg.sender, amount); } function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal { if (amount == 0) { return; } // Cap the gas to prevent consuming all available gas to block a tx from completing successfully // solhint-disable-next-line avoid-low-level-calls (bool success, ) = user.call{ value: amount, gas: 20000 }(""); if (!success) { // Record failed sends for a withdrawal later // Transfers could fail if sent to a multisig with non-trivial receiver logic // solhint-disable-next-line reentrancy pendingWithdrawals[user] = pendingWithdrawals[user].add(amount); emit WithdrawPending(user, amount); } } uint256[499] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "../interfaces/IFNDNFT721.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @notice A mixin for associating creators to NFTs. * @dev In the future this may store creators directly in order to support NFTs created on a different platform. */ abstract contract NFTMarketCreators is ReentrancyGuardUpgradeable // Adding this unused mixin to help with linearization { /** * @dev If the creator is not available then 0x0 is returned. Downstream this indicates that the creator * fee should be sent to the current seller instead. * This may apply when selling NFTs that were not minted on Foundation. */ function getCreator(address nftContract, uint256 tokenId) internal view returns (address payable) { try IFNDNFT721(nftContract).tokenCreator(tokenId) returns (address payable creator) { return creator; } catch { return address(0); } } // 500 slots were added via the new SendValueWithFallbackWithdraw mixin uint256[500] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "./FoundationTreasuryNode.sol"; import "./Constants.sol"; import "./NFTMarketCore.sol"; import "./NFTMarketCreators.sol"; import "./SendValueWithFallbackWithdraw.sol"; /** * @notice A mixin to distribute funds when an NFT is sold. */ abstract contract NFTMarketFees is Constants, Initializable, FoundationTreasuryNode, NFTMarketCore, NFTMarketCreators, SendValueWithFallbackWithdraw { using SafeMathUpgradeable for uint256; event MarketFeesUpdated( uint256 primaryFoundationFeeBasisPoints, uint256 secondaryFoundationFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ); uint256 private _primaryFoundationFeeBasisPoints; uint256 private _secondaryFoundationFeeBasisPoints; uint256 private _secondaryCreatorFeeBasisPoints; mapping(address => mapping(uint256 => bool)) private nftContractToTokenIdToFirstSaleCompleted; /** * @notice Returns true if the given NFT has not been sold in this market previously and is being sold by the creator. */ function getIsPrimary(address nftContract, uint256 tokenId) public view returns (bool) { return _getIsPrimary(nftContract, tokenId, _getSellerFor(nftContract, tokenId)); } /** * @dev A helper that determines if this is a primary sale given the current seller. * This is a minor optimization to use the seller if already known instead of making a redundant lookup call. */ function _getIsPrimary( address nftContract, uint256 tokenId, address seller ) private view returns (bool) { // By checking if the first sale has been completed first we can short circuit getCreator which is an external call. return !nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] && getCreator(nftContract, tokenId) == seller; } /** * @notice Returns the current fee configuration in basis points. */ function getFeeConfig() public view returns ( uint256 primaryFoundationFeeBasisPoints, uint256 secondaryFoundationFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) { return (_primaryFoundationFeeBasisPoints, _secondaryFoundationFeeBasisPoints, _secondaryCreatorFeeBasisPoints); } /** * @notice Returns how funds will be distributed for a sale at the given price point. * @dev This could be used to present exact fee distributing on listing or before a bid is placed. */ function getFees( address nftContract, uint256 tokenId, uint256 price ) public view returns ( uint256 foundationFee, uint256 creatorSecondaryFee, uint256 ownerRev ) { return _getFees(nftContract, tokenId, _getSellerFor(nftContract, tokenId), price); } /** * @dev Calculates how funds should be distributed for the given sale details. * If this is a primary sale, the creator revenue will appear as `ownerRev`. */ function _getFees( address nftContract, uint256 tokenId, address seller, uint256 price ) public view returns ( uint256 foundationFee, uint256 creatorSecondaryFee, uint256 ownerRev ) { uint256 foundationFeeBasisPoints; if (_getIsPrimary(nftContract, tokenId, seller)) { foundationFeeBasisPoints = _primaryFoundationFeeBasisPoints; // On a primary sale, the creator is paid the remainder via `ownerRev`. } else { foundationFeeBasisPoints = _secondaryFoundationFeeBasisPoints; // SafeMath is not required when dividing by a constant value > 0. creatorSecondaryFee = price.mul(_secondaryCreatorFeeBasisPoints) / BASIS_POINTS; } // SafeMath is not required when dividing by a constant value > 0. foundationFee = price.mul(foundationFeeBasisPoints) / BASIS_POINTS; ownerRev = price.sub(foundationFee).sub(creatorSecondaryFee); } /** * @dev Distributes funds to foundation, creator, and NFT owner after a sale. */ function _distributeFunds( address nftContract, uint256 tokenId, address payable seller, uint256 price ) internal returns ( uint256 foundationFee, uint256 creatorFee, uint256 ownerRev ) { (foundationFee, creatorFee, ownerRev) = _getFees(nftContract, tokenId, seller, price); // Anytime fees are distributed that indicates the first sale is complete, // which will not change state during a secondary sale. // This must come after the `_getFees` call above as this state is considered in the function. nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true; _sendValueWithFallbackWithdraw(getFoundationTreasury(), foundationFee); if (creatorFee > 0) { address payable creator = getCreator(nftContract, tokenId); if (creator == address(0)) { // If the creator is unknown, send all revenue to the current seller instead. ownerRev = ownerRev.add(creatorFee); creatorFee = 0; } else { _sendValueWithFallbackWithdraw(creator, creatorFee); } } _sendValueWithFallbackWithdraw(seller, ownerRev); } /** * @notice Allows Foundation to change the market fees. */ function _updateMarketFees( uint256 primaryFoundationFeeBasisPoints, uint256 secondaryFoundationFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) internal { require(primaryFoundationFeeBasisPoints < BASIS_POINTS, "NFTMarketFees: Fees >= 100%"); require( secondaryFoundationFeeBasisPoints.add(secondaryCreatorFeeBasisPoints) < BASIS_POINTS, "NFTMarketFees: Fees >= 100%" ); _primaryFoundationFeeBasisPoints = primaryFoundationFeeBasisPoints; _secondaryFoundationFeeBasisPoints = secondaryFoundationFeeBasisPoints; _secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints; emit MarketFeesUpdated( primaryFoundationFeeBasisPoints, secondaryFoundationFeeBasisPoints, secondaryCreatorFeeBasisPoints ); } uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; /** * @notice An abstraction layer for auctions. * @dev This contract can be expanded with reusable calls and data as more auction types are added. */ abstract contract NFTMarketAuction { /** * @dev A global id for auctions of any type. */ uint256 private nextAuctionId; function _initializeNFTMarketAuction() internal { nextAuctionId = 1; } function _getNextAndIncrementAuctionId() internal returns (uint256) { return nextAuctionId++; } uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./Constants.sol"; import "./NFTMarketCore.sol"; import "./NFTMarketFees.sol"; import "./SendValueWithFallbackWithdraw.sol"; import "./NFTMarketAuction.sol"; /** * @notice Manages a reserve price auction for NFTs. */ abstract contract NFTMarketReserveAuction is Constants, NFTMarketCore, ReentrancyGuardUpgradeable, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction { using SafeMathUpgradeable for uint256; struct ReserveAuction { address nftContract; uint256 tokenId; address payable seller; uint256 duration; uint256 extensionDuration; uint256 endTime; address payable bidder; uint256 amount; } mapping(address => mapping(uint256 => uint256)) private nftContractToTokenIdToAuctionId; mapping(uint256 => ReserveAuction) private auctionIdToAuction; uint256 private _minPercentIncrementInBasisPoints; // This variable was used in an older version of the contract, left here as a gap to ensure upgrade compatibility uint256 private ______gap_was_maxBidIncrementRequirement; uint256 private _duration; // These variables were used in an older version of the contract, left here as gaps to ensure upgrade compatibility uint256 private ______gap_was_extensionDuration; uint256 private ______gap_was_goLiveDate; // Cap the max duration so that overflows will not occur uint256 private constant MAX_MAX_DURATION = 1000 days; uint256 private constant EXTENSION_DURATION = 15 minutes; event ReserveAuctionConfigUpdated( uint256 minPercentIncrementInBasisPoints, uint256 maxBidIncrementRequirement, uint256 duration, uint256 extensionDuration, uint256 goLiveDate ); event ReserveAuctionCreated( address indexed seller, address indexed nftContract, uint256 indexed tokenId, uint256 duration, uint256 extensionDuration, uint256 reservePrice, uint256 auctionId ); event ReserveAuctionUpdated(uint256 indexed auctionId, uint256 reservePrice); event ReserveAuctionCanceled(uint256 indexed auctionId); event ReserveAuctionBidPlaced(uint256 indexed auctionId, address indexed bidder, uint256 amount, uint256 endTime); event ReserveAuctionFinalized( uint256 indexed auctionId, address indexed seller, address indexed bidder, uint256 f8nFee, uint256 creatorFee, uint256 ownerRev ); modifier onlyValidAuctionConfig(uint256 reservePrice) { require(reservePrice > 0, "NFTMarketReserveAuction: Reserve price must be at least 1 wei"); _; } /** * @notice Returns auction details for a given auctionId. */ function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; } /** * @notice Returns the auctionId for a given NFT, or 0 if no auction is found. * @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization. */ function getReserveAuctionIdFor(address nftContract, uint256 tokenId) public view returns (uint256) { return nftContractToTokenIdToAuctionId[nftContract][tokenId]; } /** * @dev Returns the seller that put a given NFT into escrow, * or bubbles the call up to check the current owner if the NFT is not currently in escrow. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override returns (address) { address seller = auctionIdToAuction[nftContractToTokenIdToAuctionId[nftContract][tokenId]].seller; if (seller == address(0)) { return super._getSellerFor(nftContract, tokenId); } return seller; } /** * @notice Returns the current configuration for reserve auctions. */ function getReserveAuctionConfig() public view returns (uint256 minPercentIncrementInBasisPoints, uint256 duration) { minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints; duration = _duration; } function _initializeNFTMarketReserveAuction() internal { _duration = 24 hours; // A sensible default value } function _updateReserveAuctionConfig(uint256 minPercentIncrementInBasisPoints, uint256 duration) internal { require(minPercentIncrementInBasisPoints <= BASIS_POINTS, "NFTMarketReserveAuction: Min increment must be <= 100%"); // Cap the max duration so that overflows will not occur require(duration <= MAX_MAX_DURATION, "NFTMarketReserveAuction: Duration must be <= 1000 days"); require(duration >= EXTENSION_DURATION, "NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION"); _minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints; _duration = duration; // We continue to emit unused configuration variables to simplify the subgraph integration. emit ReserveAuctionConfigUpdated(minPercentIncrementInBasisPoints, 0, duration, EXTENSION_DURATION, 0); } /** * @notice Creates an auction for the given NFT. * The NFT is held in escrow until the auction is finalized or canceled. */ function createReserveAuction( address nftContract, uint256 tokenId, uint256 reservePrice ) public onlyValidAuctionConfig(reservePrice) nonReentrant { // If an auction is already in progress then the NFT would be in escrow and the modifier would have failed uint256 auctionId = _getNextAndIncrementAuctionId(); nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId; auctionIdToAuction[auctionId] = ReserveAuction( nftContract, tokenId, msg.sender, _duration, EXTENSION_DURATION, 0, // endTime is only known once the reserve price is met address(0), // bidder is only known once a bid has been placed reservePrice ); IERC721Upgradeable(nftContract).transferFrom(msg.sender, address(this), tokenId); emit ReserveAuctionCreated( msg.sender, nftContract, tokenId, _duration, EXTENSION_DURATION, reservePrice, auctionId ); } /** * @notice If an auction has been created but has not yet received bids, the configuration * such as the reservePrice may be changed by the seller. */ function updateReserveAuction(uint256 auctionId, uint256 reservePrice) public onlyValidAuctionConfig(reservePrice) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); auction.amount = reservePrice; emit ReserveAuctionUpdated(auctionId, reservePrice); } /** * @notice If an auction has been created but has not yet received bids, it may be canceled by the seller. * The NFT is returned to the seller from escrow. */ function cancelReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId]; delete auctionIdToAuction[auctionId]; IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.seller, auction.tokenId); emit ReserveAuctionCanceled(auctionId); } /** * @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`. * If this is the first bid on the auction, the countdown will begin. * If there is already an outstanding bid, the previous bidder will be refunded at this time * and if the bid is placed in the final moments of the auction, the countdown may be extended. */ function placeBid(uint256 auctionId) public payable nonReentrant { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.amount != 0, "NFTMarketReserveAuction: Auction not found"); if (auction.endTime == 0) { // If this is the first bid, ensure it's >= the reserve price require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price"); } else { // If this bid outbids another, confirm that the bid is at least x% greater than the last require(auction.endTime >= block.timestamp, "NFTMarketReserveAuction: Auction is over"); require(auction.bidder != msg.sender, "NFTMarketReserveAuction: You already have an outstanding bid"); uint256 minAmount = _getMinBidAmountForReserveAuction(auction.amount); require(msg.value >= minAmount, "NFTMarketReserveAuction: Bid amount too low"); } if (auction.endTime == 0) { auction.amount = msg.value; auction.bidder = msg.sender; // On the first bid, the endTime is now + duration auction.endTime = block.timestamp + auction.duration; } else { // Cache and update bidder state before a possible reentrancy (via the value transfer) uint256 originalAmount = auction.amount; address payable originalBidder = auction.bidder; auction.amount = msg.value; auction.bidder = msg.sender; // When a bid outbids another, check to see if a time extension should apply. if (auction.endTime - block.timestamp < auction.extensionDuration) { auction.endTime = block.timestamp + auction.extensionDuration; } // Refund the previous bidder _sendValueWithFallbackWithdraw(originalBidder, originalAmount); } emit ReserveAuctionBidPlaced(auctionId, msg.sender, msg.value, auction.endTime); } /** * @notice Once the countdown has expired for an auction, anyone can settle the auction. * This will send the NFT to the highest bidder and distribute funds. */ function finalizeReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.endTime > 0, "NFTMarketReserveAuction: Auction has not started"); require(auction.endTime < block.timestamp, "NFTMarketReserveAuction: Auction still in progress"); delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId]; delete auctionIdToAuction[auctionId]; IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.bidder, auction.tokenId); (uint256 f8nFee, uint256 creatorFee, uint256 ownerRev) = _distributeFunds(auction.nftContract, auction.tokenId, auction.seller, auction.amount); emit ReserveAuctionFinalized(auctionId, auction.seller, auction.bidder, f8nFee, creatorFee, ownerRev); } /** * @notice Returns the minimum amount a bidder must spend to participate in an auction. */ function getMinBidAmount(uint256 auctionId) public view returns (uint256) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; if (auction.endTime == 0) { return auction.amount; } return _getMinBidAmountForReserveAuction(auction.amount); } /** * @dev Determines the minimum bid amount when outbidding another user. */ function _getMinBidAmountForReserveAuction(uint256 currentBidAmount) private view returns (uint256) { uint256 minIncrement = currentBidAmount.mul(_minPercentIncrementInBasisPoints) / BASIS_POINTS; if (minIncrement == 0) { // The next bid must be at least 1 wei greater than the current. return currentBidAmount.add(1); } return minIncrement.add(currentBidAmount); } uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 // 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.7.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 OR Apache-2.0 pragma solidity ^0.7.0; /** * @notice Interface for AdminRole which wraps the default admin role from * OpenZeppelin's AccessControl for easy integration. */ interface IAdminRole { function isAdmin(address account) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable pragma solidity ^0.7.0; interface IFNDNFT721 { function tokenCreator(uint256 tokenId) external view returns (address payable); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; /** * @dev Constant values shared across mixins. */ abstract contract Constants { uint256 internal constant BASIS_POINTS = 10000; }
* @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance for future withdrawal instead./
abstract contract SendValueWithFallbackWithdraw is ReentrancyGuardUpgradeable { using AddressUpgradeable for address payable; using SafeMathUpgradeable for uint256; mapping(address => uint256) private pendingWithdrawals; event WithdrawPending(address indexed user, uint256 amount); event Withdrawal(address indexed user, uint256 amount); function getPendingWithdrawal(address user) public view returns (uint256) { return pendingWithdrawals[user]; } function withdraw() public nonReentrant { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "No funds are pending withdrawal"); pendingWithdrawals[msg.sender] = 0; msg.sender.sendValue(amount); emit Withdrawal(msg.sender, amount); } function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal { if (amount == 0) { return; } if (!success) { pendingWithdrawals[user] = pendingWithdrawals[user].add(amount); emit WithdrawPending(user, amount); } } uint256[499] private ______gap; function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal { if (amount == 0) { return; } if (!success) { pendingWithdrawals[user] = pendingWithdrawals[user].add(amount); emit WithdrawPending(user, amount); } } uint256[499] private ______gap; (bool success, ) = user.call{ value: amount, gas: 20000 }(""); function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal { if (amount == 0) { return; } if (!success) { pendingWithdrawals[user] = pendingWithdrawals[user].add(amount); emit WithdrawPending(user, amount); } } uint256[499] private ______gap; }
12,224,186
[ 1, 7744, 358, 1366, 512, 2455, 471, 309, 326, 7412, 6684, 578, 7597, 596, 434, 16189, 16, 1707, 326, 11013, 364, 3563, 598, 9446, 287, 3560, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 2479, 620, 1190, 12355, 1190, 9446, 353, 868, 8230, 12514, 16709, 10784, 429, 288, 203, 225, 1450, 5267, 10784, 429, 364, 1758, 8843, 429, 31, 203, 225, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 4634, 1190, 9446, 1031, 31, 203, 203, 225, 871, 3423, 9446, 8579, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 3423, 9446, 287, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 225, 445, 1689, 2846, 1190, 9446, 287, 12, 2867, 729, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 4634, 1190, 9446, 1031, 63, 1355, 15533, 203, 225, 289, 203, 203, 225, 445, 598, 9446, 1435, 1071, 1661, 426, 8230, 970, 288, 203, 565, 2254, 5034, 3844, 273, 4634, 1190, 9446, 1031, 63, 3576, 18, 15330, 15533, 203, 565, 2583, 12, 8949, 405, 374, 16, 315, 2279, 284, 19156, 854, 4634, 598, 9446, 287, 8863, 203, 565, 4634, 1190, 9446, 1031, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 1234, 18, 15330, 18, 4661, 620, 12, 8949, 1769, 203, 565, 3626, 3423, 9446, 287, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 4661, 620, 1190, 12355, 1190, 9446, 12, 2867, 8843, 429, 729, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 565, 309, 261, 8949, 422, 374, 13, 288, 203, 1377, 327, 31, 203, 565, 289, 203, 565, 309, 16051, 4768, 13, 288, 203, 2 ]
// SPDX-License-Identifier: MIT //File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/WENFarm.sol pragma solidity 0.6.12; contract WENFarm is ERC20("WENFarm", "WEN"), Ownable { using SafeMath for uint256; uint8 public FeeRate = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 feeAmount = amount.mul(FeeRate).div(100); _burn(msg.sender, feeAmount); return super.transfer(recipient, amount.sub(feeAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 feeAmount = amount.mul(FeeRate).div(100); _burn(sender, feeAmount); return super.transferFrom(sender, recipient, amount.sub(feeAmount)); } /** * @dev Chef distributes newly generated WENFarm to each farmmers * "onlyOwner" :: for the one who worries about the function, this distribute process is only done by MasterChef contract for farming process */ function distribute(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token for deflanationary features */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeFeeRate(uint8 _feerate) public onlyOwner { FeeRate = _feerate; } mapping (address => address) internal _delegates; 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), "WENFarm::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "WENFarm::delegateBySig: invalid nonce"); require(now <= expiry, "WENFarm::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, "WENFarm::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "WENFarm::_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/WENchef.sol pragma solidity 0.6.12; interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } contract WENchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap uint256 lastDepositTime; // Last LP deposit time uint256 timelock; // Does the user has LP timelock 0: no, certain number: timelock period } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that Burn distribution occurs. uint256 accWENPerShare; // Accumulated token per share, times 1e12. See below. uint256 isFreezone; // LP without Burn = 1, LP with Burn = 0 } // WENFarm WENFarm public wen; // Dev, burn, and Buyback address. address public devaddr; address public burnaddr; address public buybackaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public wenPerBlock; uint256 public BONUS_MULTIPLIER = 2; // Defining diminish and vault fee. uint256 public diminish = 10 days; uint256 public vaultfee = 200; uint256 public locktime = 2 days; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // 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; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event DepositWithLPlock(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( WENFarm _wen, address _devaddr, address _buybackaddr, address _burnaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { wen = _wen; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; wenPerBlock = 100000000000000000; // 0.1 /Block bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _wenPerBlock) public onlyOwner { wenPerBlock = _wenPerBlock; } function changeStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; } function changeBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function changeBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner { BONUS_MULTIPLIER = _bonusMultiplier; } function changeDiminishRate(uint256 _diminish) public onlyOwner { diminish = _diminish; } function changeVaultfee(uint256 _vaultfee) public onlyOwner { vaultfee = _vaultfee; } // Affective to the timelock after this change occurs function changeLocktime(uint256 _locktime) public onlyOwner { locktime = _locktime; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _isFreezone, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accWENPerShare: 0, isFreezone: _isFreezone })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending Burn on frontend. function pendingWEN(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accWENPerShare = pool.accWENPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 wenReward = multiplier.mul(wenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accWENPerShare = accWENPerShare.add(wenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accWENPerShare).div(1e12).sub(user.rewardDebt); } // View function to see estimated harvest after burnt WEN on frontend. function estimatedWEN(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 depositduration = 0; uint256 subrate = 1; uint256 pending = 0; if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } uint256 accWENPerShare = pool.accWENPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 wenReward = multiplier.mul(wenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accWENPerShare = accWENPerShare.add(wenReward.mul(1e12).div(lpSupply)); } pending = user.amount.mul(accWENPerShare).div(1e12).sub(user.rewardDebt); return pending.mul(subrate); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 wenReward = multiplier.mul(wenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); wen.distribute(devaddr, wenReward.div(20)); wen.distribute(address(this), wenReward); pool.accWENPerShare = pool.accWENPerShare.add(wenReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 depositduration = 0; uint256 subrate = 1; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accWENPerShare).div(1e12).sub(user.rewardDebt); uint256 wenpending = 0; depositduration = now.sub(user.lastDepositTime); if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } if(pending > 0) { wenpending = pending.sub(pending.mul(subrate)); safeWENTransfer(msg.sender, pending.mul(subrate)); safeWENTransfer(burnaddr, wenpending); } } if(_amount > 0) { if(pool.isFreezone > 0) { vaultamount = _amount.div(vaultfee); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); } if(pool.isFreezone < 1) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.amount = user.amount.add(_amount.sub(vaultamount)); user.lastDepositTime = now; user.timelock = 0; } user.rewardDebt = user.amount.mul(pool.accWENPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } /** Locks lpToken for certain period. Locked LP depotied through this method only can be withdrawed after timelock period * */ function depositWithLPlock(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 depositduration = 0; uint256 subrate = 1; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accWENPerShare).div(1e12).sub(user.rewardDebt); uint256 wenpending = 0; depositduration = now.sub(user.lastDepositTime); if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } if(pending > 0) { wenpending = pending.sub(pending.mul(subrate)); safeWENTransfer(msg.sender, pending.mul(subrate)); safeWENTransfer(burnaddr, wenpending); } } if(_amount > 0) { if(pool.isFreezone > 0) { vaultamount = _amount.div(vaultfee); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); } if(pool.isFreezone < 1) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.amount = user.amount.add(_amount.sub(vaultamount)); user.lastDepositTime = now; user.timelock = locktime; } user.rewardDebt = user.amount.mul(pool.accWENPerShare).div(1e12); emit DepositWithLPlock(msg.sender, _pid, _amount); } // Withdraw LP tokens. // Only non-locked LP and Locked LP after lock period can be withdrawed 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"); require(now > user.lastDepositTime + user.timelock, "Your LP is LOCKed for the moment"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accWENPerShare).div(1e12).sub(user.rewardDebt); uint256 depositduration = 0; uint256 subrate = 1; depositduration = now.sub(user.lastDepositTime); if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } if(pending > 0) { safeWENTransfer(msg.sender, pending.mul(subrate)); safeWENTransfer(burnaddr, pending.sub(pending.mul(subrate))); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.lastDepositTime = now.sub(depositduration.div(2)); user.rewardDebt = user.amount.mul(pool.accWENPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Update buyback address. function bbto(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } // 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 WEN transfer function, just in case if rounding error causes pool to not have enough WEN. function safeWENTransfer(address _to, uint256 _amount) internal { uint256 wenBal = wen.balanceOf(address(this)); if (_amount > wenBal) { wen.transfer(_to, wenBal); } else { wen.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Update burn-event address. function burnto(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } }
Safe WEN transfer function, just in case if rounding error causes pool to not have enough WEN.
function safeWENTransfer(address _to, uint256 _amount) internal { uint256 wenBal = wen.balanceOf(address(this)); if (_amount > wenBal) { wen.transfer(_to, wenBal); wen.transfer(_to, _amount); } }
14,416,097
[ 1, 9890, 678, 1157, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 678, 1157, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 59, 1157, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 341, 275, 38, 287, 273, 341, 275, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 341, 275, 38, 287, 13, 288, 203, 5411, 341, 275, 18, 13866, 24899, 869, 16, 341, 275, 38, 287, 1769, 203, 5411, 341, 275, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x97775663518F3E12A4891CcC9EDCd5194671B7b3/sources/hash.sol
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
function splitSignature(bytes memory sig) public pure returns (bytes32, bytes32, uint8) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (r, s, v); }
747,719
[ 1, 3645, 3847, 1731, 16, 1839, 326, 769, 1633, 2205, 3847, 1731, 727, 1160, 261, 3645, 1160, 434, 326, 1024, 3847, 1731, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1416, 5374, 12, 3890, 3778, 3553, 13, 203, 4202, 1071, 203, 4202, 16618, 203, 4202, 1135, 261, 3890, 1578, 16, 1731, 1578, 16, 2254, 28, 13, 203, 282, 288, 203, 4202, 2583, 12, 7340, 18, 2469, 422, 15892, 1769, 203, 203, 4202, 1731, 1578, 436, 31, 203, 4202, 1731, 1578, 272, 31, 203, 4202, 2254, 28, 331, 31, 203, 203, 4202, 19931, 288, 203, 6647, 436, 519, 312, 945, 12, 1289, 12, 7340, 16, 3847, 3719, 203, 6647, 272, 519, 312, 945, 12, 1289, 12, 7340, 16, 5178, 3719, 203, 6647, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 7340, 16, 19332, 20349, 203, 4202, 289, 203, 1377, 203, 4202, 327, 261, 86, 16, 272, 16, 331, 1769, 203, 282, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. * * Modified from OpenZeppelin's TokenVesting.sol draft */ contract TokenVesting { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; event TokensReleased(uint256 amount); event TokenVestingRevoked(); // beneficiary of tokens after they are released address private _beneficiary; // owner (grantor) of the tokens address private _owner; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; address public _FXS_contract_address; ERC20 FXS; address public _timelock_address; bool public _revocable; uint256 private _released; bool public _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor ( address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable ) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; _owner = msg.sender; } function setFXSAddress(address FXS_address) public { require(msg.sender == _owner, "must be set by the owner"); _FXS_contract_address = FXS_address; FXS = ERC20(FXS_address); } function setTimelockAddress(address timelock_address) public { require(msg.sender == _owner, "must be set by the owner"); _timelock_address = timelock_address; } /** * @return the beneficiary of the tokens. */ function getBeneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function getCliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function getStart() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function getDuration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function getRevocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function getReleased() public view returns (uint256) { return _released; } /** * @return true if the token is revoked. */ function getRevoked() public view returns (bool) { return _revoked; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { require(msg.sender == _beneficiary, "must be the beneficiary to release tokens"); uint256 unreleased = _releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released = _released.add(unreleased); FXS.transfer(_beneficiary, unreleased); emit TokensReleased(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. */ function revoke() public { require(msg.sender == _timelock_address, "Must be called by the timelock contract"); require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked, "TokenVesting: token already revoked"); uint256 balance = FXS.balanceOf(address(this)); uint256 unreleased = _releasableAmount(); uint256 refund = balance.sub(unreleased); _revoked = true; FXS.transfer(_owner, refund); emit TokenVestingRevoked(); } // Added to support recovering possible airdrops function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(msg.sender == _beneficiary, "Must be called by the beneficiary"); // Cannot recover the staking token or the rewards token require(tokenAddress != _FXS_contract_address, "Cannot withdraw the FXS through this function"); ERC20(tokenAddress).transfer(_beneficiary, tokenAmount); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function _releasableAmount() private view returns (uint256) { return _vestedAmount().sub(_released); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount() private view returns (uint256) { uint256 currentBalance = FXS.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } uint256[44] private __gap; }
Added to support recovering possible airdrops Cannot recover the staking token or the rewards token
function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(msg.sender == _beneficiary, "Must be called by the beneficiary"); require(tokenAddress != _FXS_contract_address, "Cannot withdraw the FXS through this function"); ERC20(tokenAddress).transfer(_beneficiary, tokenAmount); }
15,868,152
[ 1, 8602, 358, 2865, 5910, 310, 3323, 279, 6909, 16703, 14143, 5910, 326, 384, 6159, 1147, 578, 326, 283, 6397, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 654, 39, 3462, 12, 2867, 1147, 1887, 16, 2254, 5034, 1147, 6275, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 70, 4009, 74, 14463, 814, 16, 315, 10136, 506, 2566, 635, 326, 27641, 74, 14463, 814, 8863, 203, 203, 3639, 2583, 12, 2316, 1887, 480, 389, 25172, 55, 67, 16351, 67, 2867, 16, 315, 4515, 598, 9446, 326, 478, 60, 55, 3059, 333, 445, 8863, 203, 3639, 4232, 39, 3462, 12, 2316, 1887, 2934, 13866, 24899, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 Mint(address indexed sender, uint256 amount0, uint256 amount1); 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 mint(address to) external returns (uint256 liquidity); 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 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 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 * transacgtion 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 IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 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 {} } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); //_owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } 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 PoodleInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // 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; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Poodle Inu", "Poodle") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e12 * 1e18; //maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn maxTransactionAmount = totalSupply; maxWallet = totalSupply; // .5% maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= 0, "Cannot set maxTransactionAmount lower than 0%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } 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; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // 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[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if (canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } if (!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{ value: ethAmount }( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{ value: ethForDev }(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; }
1,324,797
[ 1, 3427, 326, 5224, 3844, 434, 2430, 358, 357, 80, 628, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1089, 12521, 5157, 861, 6275, 12, 11890, 5034, 394, 6275, 13, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 202, 202, 6528, 12, 2704, 6275, 1545, 261, 4963, 3088, 1283, 1435, 380, 404, 13, 342, 25259, 16, 315, 12521, 3844, 2780, 506, 2612, 2353, 374, 18, 11664, 9, 2078, 14467, 1199, 1769, 203, 202, 202, 6528, 12, 2704, 6275, 1648, 261, 4963, 3088, 1283, 1435, 380, 1381, 13, 342, 4336, 16, 315, 12521, 3844, 2780, 506, 10478, 2353, 374, 18, 25, 9, 2078, 14467, 1199, 1769, 203, 202, 202, 22270, 5157, 861, 6275, 273, 394, 6275, 31, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xfe18d6364D83D21fC0ce4fEaD6653cCBCF903835/sources/OXMasterFarmer.sol
Safe ox transfer function, just in case if rounding error causes pool to not have enough OXs.
function safeOXTransfer(address _to, uint256 _amount) internal { uint256 oxBal = ox.balanceOf(address(this)); if (_amount > oxBal) { ox.transfer(_to, oxBal); ox.transfer(_to, _amount); } }
11,063,570
[ 1, 9890, 6965, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 531, 60, 87, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 22550, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 6965, 38, 287, 273, 6965, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 6965, 38, 287, 13, 288, 203, 5411, 6965, 18, 13866, 24899, 869, 16, 6965, 38, 287, 1769, 203, 5411, 6965, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.9; // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /// @title Crypto Heroes Contract /// @notice Crypto Heroes is a limited-edition ECR-1155 crypto token collection that depicts /// a world full of hidden plans, conspiracy theories, predictions, and the heroes & /// personalities around them. The cards were created by J35, an anonymous figure who travelled /// back in time to reveal the plans of the global power elite—and honor the heroes fighting /// against it. We chose to deliver his message through a censorship-resistant 32-card set, /// forever stored in the Ethereum blockchain /// @author Qrypto Labs LLC contract CryptoHeroes is Initializable, ERC1155Upgradeable, OwnableUpgradeable, UUPSUpgradeable { error SaleNotActive(); error InvalidNumOfPacks(uint8 numPacks); error NotEnoughEth(uint256 valueWei); error NotOwnerOf(uint8 numPacks); error QuantityNotAvailable(uint256 numPacks); // Settings uint8 constant DECK_SIZE = 32; uint8 constant NUM_CARDS_PER_PACK = 2; uint256 constant PACK_PRICE = 0.06 ether; uint256 constant MAX_PACKS = 10000; uint8 constant MAX_PACKS_PER_TX = 20; uint8 constant RESERVED_PACKS = 16; // Token ID uint8 constant PACK_ID = 0; // Card classes uint16 constant COMMON = 770; uint16 constant RARE = 300; uint16 constant SECRET = 150; uint16 constant ULTRA = 10; // Contract state uint16[DECK_SIZE] private availableCards; address private proxyRegistry; uint256 private seed; uint256 public availablePacks; string private contractMetadataUri; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /// Initializes contract state function initialize(string memory _uri, string memory _contractMetadataUri, address _proxyRegistry) public initializer { __ERC1155_init(_uri); __Ownable_init(); __UUPSUpgradeable_init(); contractMetadataUri = _contractMetadataUri; proxyRegistry = _proxyRegistry; availableCards = [ COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, RARE - 1, RARE - 1, RARE - 1, RARE - 1, SECRET - 1, SECRET - 1, ULTRA - 1, ULTRA - 1 ]; availablePacks = MAX_PACKS - RESERVED_PACKS; } /// returns the contract-level metadata URI function contractURI() public view returns (string memory) { return contractMetadataUri; } /// Sets the URI for the contract-level metadata URI /// @param _newUri the new URI function setContractURI(string memory _newUri) public onlyOwner { contractMetadataUri = _newUri; } /// Sets the URI for the ECR-1155 Metadata JSON Schema /// @param _newUri the new URI function setURI(string memory _newUri) public onlyOwner { _setURI(_newUri); } /// Only the owner can upgrade the contract implementation function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} /// Avoids an additional authorization step (and gas fee) from OpenSea users /// @param _account the user account address /// @param _operator the OpenSea's proxy registry address function isApprovedForAll(address _account, address _operator) public view virtual override returns (bool) { ProxyRegistry _proxyRegistry = ProxyRegistry(proxyRegistry); if (address(_proxyRegistry.proxies(_account)) == _operator) { return true; } return super.isApprovedForAll(_account, _operator); } /// Ensures limit on number of packs modifier checkAvailablePacks(uint256 _numPacks) { if (availablePacks < _numPacks) { // sold out or not enough packs left revert QuantityNotAvailable(_numPacks); } _; } /// Mints a tradable pack. The packs can be "opened" once the sale is active /// @param _to the recipients' addresses /// @param _numPacks the number of packs to give away to each recipient function mintGiveAwayPacks(address[] memory _to, uint8 _numPacks) external onlyOwner checkAvailablePacks(_to.length * _numPacks) { availablePacks -= _to.length * _numPacks; for (uint256 i = 0; i < _to.length; i++) { _mint(_to[i], PACK_ID, _numPacks, ''); } } /// Mints two pseudo-randomly selected cards for each pack that /// the sender wants to "open", as long as he/she owns them. "Opened" /// packs are burned. /// @param _numPacks the number of packs to "open" function mintFromExistingPacks(uint8 _numPacks) public { if (_numPacks > balanceOf(msg.sender, PACK_ID)) { revert NotOwnerOf(_numPacks); } _burn(msg.sender, PACK_ID, _numPacks); _mint(_numPacks); } /// Mints two pseudo-randomly selected cards for each pack /// @param _numPacks the number of packs to "open" function mintFromNewPacks(uint8 _numPacks) public payable checkAvailablePacks(_numPacks) { if (msg.value < (uint256(_numPacks) * PACK_PRICE)) { revert NotEnoughEth(msg.value); } if (_numPacks == 0 || _numPacks > MAX_PACKS_PER_TX) { revert InvalidNumOfPacks(_numPacks); } availablePacks -= _numPacks; _mint(_numPacks); } /// One copy of each card is reserved for the team so we can share the /// collection's copyright function mintDeckForTeam() public onlyOwner { uint256[] memory _ids = new uint256[](DECK_SIZE); uint256[] memory _amounts = new uint256[](DECK_SIZE); for (uint256 i = 0; i < DECK_SIZE; i++) { _ids[i] = i + 1; _amounts[i] = 1; } _mintBatch(msg.sender, _ids, _amounts, ''); } /// Main minting function: it mints two pseudo-randomly cards per pack. There /// are pre-defined probabilities for each card, which are based on each card's /// rarity. A seed, which is dependant with each card selection, the previous /// block hash, and the transaction sender is used to add a source of additional /// pseudo-randomness /// @param _numPacks the number of packs to "open" function _mint(uint8 _numPacks) internal virtual { if (seed == 0) { revert SaleNotActive(); } uint256 _randomNumber = _random(seed); uint256[] memory _ids = new uint256[](_numPacks*2); uint256[] memory _amounts = new uint256[](_numPacks*2); uint16[DECK_SIZE] memory _cardsProbabilities = [ 20000, 19230, 18460, 17690, 16920, 16150, 15380, 14610, 13840, 13070, 12300, 11530, 10760, 9990, 9220, 8450, 7680, 6910, 6140, 5370, 4600, 3830, 3060, 2290, 1520, 1220, 920, 620, 320, 170, 20, 10 ]; uint256 _counter = 0; for (uint256 i = 0; i < _numPacks * NUM_CARDS_PER_PACK; i++) { bool _selected; uint16 _value = uint16(_randomNumber % (MAX_PACKS * NUM_CARDS_PER_PACK)); for (uint256 j = _cardsProbabilities.length - 1; j > 0; j--) { uint16 _probability = _cardsProbabilities[j]; if (_value < _probability && availableCards[j] > 0) { _ids[_counter] = j + 1; _amounts[_counter]++; availableCards[j]--; _selected = true; _counter++; break; } } if (!_selected) { // if there are no cards left with a given (or lower) rarity, // mint the first available card with the next lowest rarity for (uint256 j = 0; j < _cardsProbabilities.length; j++) { if (availableCards[j] > 0) { _ids[_counter] = j + 1; _amounts[_counter]++; availableCards[j]--; _counter++; break; } } } _randomNumber = _random(_randomNumber); } seed = _randomNumber; _mintBatch(msg.sender, _ids, _amounts, ''); } /// Withdraws the contract's balance function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /// Returns a pseudorandom number /// @param _seed additional source of pseudo-randomness /// @return the pseudorandom number function _random(uint256 _seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, _seed))); } /// A non-zero value activates the sale and improves the pseudorandom /// number generator /// @param _newSeed the seed to use for the next transaction function setSeed(uint256 _newSeed) public onlyOwner { seed = _newSeed; } /// Returns true if the sale is active; false otherwise function isSaleActive() public view returns (bool) { return seed != 0; } /// Returns the available quantity for each card function getAllAvailableCards() public view returns (uint16[DECK_SIZE] memory) { return availableCards; } }
Mints two pseudo-randomly selected cards for each pack @param _numPacks the number of packs to "open"
function mintFromNewPacks(uint8 _numPacks) public payable checkAvailablePacks(_numPacks) { if (msg.value < (uint256(_numPacks) * PACK_PRICE)) { revert NotEnoughEth(msg.value); } if (_numPacks == 0 || _numPacks > MAX_PACKS_PER_TX) { revert InvalidNumOfPacks(_numPacks); } availablePacks -= _numPacks; _mint(_numPacks); }
12,181,932
[ 1, 49, 28142, 2795, 12454, 17, 9188, 715, 3170, 18122, 364, 1517, 2298, 225, 389, 2107, 4420, 87, 326, 1300, 434, 2298, 87, 358, 315, 3190, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 1265, 1908, 4420, 87, 12, 11890, 28, 389, 2107, 4420, 87, 13, 1071, 8843, 429, 866, 5268, 4420, 87, 24899, 2107, 4420, 87, 13, 288, 203, 565, 309, 261, 3576, 18, 1132, 411, 261, 11890, 5034, 24899, 2107, 4420, 87, 13, 380, 21558, 67, 7698, 1441, 3719, 288, 203, 1377, 15226, 2288, 664, 4966, 41, 451, 12, 3576, 18, 1132, 1769, 203, 565, 289, 203, 565, 309, 261, 67, 2107, 4420, 87, 422, 374, 747, 389, 2107, 4420, 87, 405, 4552, 67, 12231, 55, 67, 3194, 67, 16556, 13, 288, 203, 1377, 15226, 1962, 2578, 951, 4420, 87, 24899, 2107, 4420, 87, 1769, 203, 565, 289, 203, 565, 2319, 4420, 87, 3947, 389, 2107, 4420, 87, 31, 203, 565, 389, 81, 474, 24899, 2107, 4420, 87, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x826c83cB9f9238546c6e823cf1a696E42Ae880B2/sources/contracts/MasterChef.sol
Return reward multiplier over the given _from to _to second.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_from >= allEndTime) { return 0; } if (_to < startTime) { return 0; } uint from = _from; uint to = _to; if (from < startTime) { from = startTime; } if (to > allEndTime) { to = allEndTime; } return to.sub(from); }
13,244,579
[ 1, 990, 19890, 15027, 1879, 326, 864, 389, 2080, 358, 389, 869, 2205, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31863, 5742, 12, 11890, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 2080, 1545, 777, 25255, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 869, 411, 8657, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 628, 273, 389, 2080, 31, 203, 3639, 2254, 358, 273, 389, 869, 31, 203, 203, 3639, 309, 261, 2080, 411, 8657, 13, 288, 203, 5411, 628, 273, 8657, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 869, 405, 777, 25255, 13, 288, 203, 5411, 358, 273, 777, 25255, 31, 203, 3639, 289, 203, 203, 3639, 327, 358, 18, 1717, 12, 2080, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
///File: giveth-common-contracts/contracts/ERC20.sol pragma solidity ^0.4.19; /** * @title ERC20 * @dev A standard interface for tokens. * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20 { /// @dev Returns the total token supply function totalSupply() public constant returns (uint256 supply); /// @dev Returns the account balance of the account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); /// @dev Transfers _value number of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); /// @dev Transfers _value number of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount function approve(address _spender, uint256 _value) public returns (bool success); /// @dev Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } ///File: giveth-common-contracts/contracts/Owned.sol pragma solidity ^0.4.19; /// @title Owned /// @author Adrià Massanet <[email protected]> /// @notice The Owned contract has an owner address, and provides basic /// authorization control functions, this simplifies & the implementation of /// user permissions; this contract has three work flows for a change in /// ownership, the first requires the new owner to validate that they have the /// ability to accept ownership, the second allows the ownership to be /// directly transfered without requiring acceptance, and the third allows for /// the ownership to be removed to allow for decentralization contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract function Owned() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public { require(msg.sender == newOwnerCandidate); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac); owner = 0x0; newOwnerCandidate = 0x0; OwnershipRemoved(); } } ///File: giveth-common-contracts/contracts/Escapable.sol pragma solidity ^0.4.19; /* Copyright 2016, Jordi Baylina Contributor: Adrià Massanet <[email protected]> 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/>. */ /// @dev `Escapable` is a base level contract built off of the `Owned` /// contract; it creates an escape hatch function that can be called in an /// emergency that will allow designated addresses to send any ether or tokens /// held in the contract to an `escapeHatchDestination` as long as they were /// not blacklisted contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; mapping (address=>bool) private escapeBlacklist; // Token contract addresses /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchCaller The address of a trusted account or contract /// to call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract; if a neutral address /// is required, the WHG Multisig is an option: /// 0x8Ff920020c8AD673661c8117f2855C384758C572 function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned as `escapeHatchCaller` or `owner` /// are the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { require ((msg.sender == escapeHatchCaller)||(msg.sender == owner)); _; } /// @notice Creates the blacklist of tokens that are not able to be taken /// out of the contract; can only be done at the deployment, and the logic /// to add to the blacklist will be in the constructor of a child contract /// @param _token the token contract address that is to be blacklisted function blacklistEscapeToken(address _token) internal { escapeBlacklist[_token] = true; EscapeHatchBlackistedToken(_token); } /// @notice Checks to see if `_token` is in the blacklist of tokens /// @param _token the token address being queried /// @return False if `_token` is in the blacklist and can't be taken out of /// the contract via the `escapeHatch()` function isTokenEscapable(address _token) view public returns (bool) { return !escapeBlacklist[_token]; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false); uint256 balance; /// @dev Logic for ether if (_token == 0x0) { balance = this.balance; escapeHatchDestination.transfer(balance); EscapeHatchCalled(_token, balance); return; } /// @dev Logic for tokens ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance)); EscapeHatchCalled(_token, balance); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or /// contract to call `escapeHatch()` to send the value in this contract to /// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchBlackistedToken(address token); event EscapeHatchCalled(address token, uint amount); } ///File: ./contracts/lib/Pausable.sol pragma solidity ^0.4.21; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Owned { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } ///File: ./contracts/lib/Vault.sol pragma solidity ^0.4.21; /* Copyright 2018, Jordi Baylina, RJ Ewing This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title Vault Contract /// @author Jordi Baylina, RJ Ewing /// @notice This contract holds funds for Campaigns and automates payments. For /// this iteration the funds will come straight from the Giveth Multisig as a /// safety precaution, but once fully tested and optimized this contract will /// be a safe place to store funds equipped with optional variable time delays /// to allow for an optional escape hatch /// @dev `Vault` is a higher level contract built off of the `Escapable` /// contract that holds funds for Campaigns and automates payments. contract Vault is Escapable, Pausable { /// @dev `Payment` is a public structure that describes the details of /// each payment making it easy to track the movement of funds /// transparently struct Payment { string name; // What is the purpose of this payment bytes32 reference; // Reference of the payment. address spender; // Who is sending the funds uint earliestPayTime; // The earliest a payment can be made (Unix Time) bool canceled; // If True then the payment has been canceled bool paid; // If True then the payment has been paid address recipient; // Who is receiving the funds address token; // Token this payment represents uint amount; // The amount of wei sent in the payment uint securityGuardDelay; // The seconds `securityGuard` can delay payment } Payment[] public authorizedPayments; address public securityGuard; uint public absoluteMinTimeLock; uint public timeLock; uint public maxSecurityGuardDelay; bool public allowDisbursePaymentWhenPaused; /// @dev The white list of approved addresses allowed to set up && receive /// payments from this vault mapping (address => bool) public allowedSpenders; // @dev Events to make the payment movements easy to find on the blockchain event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount, address token, bytes32 reference); event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount, address token); event PaymentCanceled(uint indexed idPayment); event SpenderAuthorization(address indexed spender, bool authorized); /// @dev The address assigned the role of `securityGuard` is the only /// addresses that can call a function with this modifier modifier onlySecurityGuard { require(msg.sender == securityGuard); _; } /// By default, we dis-allow payment disburements if the contract is paused. /// However, to facilitate a migration of the bridge, we can allow /// disbursements when paused if explicitly set modifier disbursementsAllowed { require(!paused || allowDisbursePaymentWhenPaused); _; } /// @notice The Constructor creates the Vault on the blockchain /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract in an emergency /// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can /// be set to, if set to 0 the `owner` can remove the `timeLock` completely /// @param _timeLock Initial number of seconds that payments are delayed /// after they are authorized (a security precaution) /// @param _securityGuard Address that will be able to delay the payments /// beyond the initial timelock requirements; can be set to 0x0 to remove /// the `securityGuard` functionality /// @param _maxSecurityGuardDelay The maximum number of seconds in total /// that `securityGuard` can delay a payment so that the owner can cancel /// the payment if needed function Vault( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay ) Escapable(_escapeHatchCaller, _escapeHatchDestination) public { absoluteMinTimeLock = _absoluteMinTimeLock; timeLock = _timeLock; securityGuard = _securityGuard; maxSecurityGuardDelay = _maxSecurityGuardDelay; } ///////// // Helper functions ///////// /// @notice States the total number of authorized payments in this contract /// @return The number of payments ever authorized even if they were canceled function numberOfAuthorizedPayments() public view returns (uint) { return authorizedPayments.length; } //////// // Spender Interface //////// /// @notice only `allowedSpenders[]` Creates a new `Payment` /// @param _name Brief description of the payment that is authorized /// @param _reference External reference of the payment /// @param _recipient Destination of the payment /// @param _amount Amount to be paid in wei /// @param _paymentDelay Number of seconds the payment is to be delayed, if /// this value is below `timeLock` then the `timeLock` determines the delay /// @return The Payment ID number for the new authorized payment function authorizePayment( string _name, bytes32 _reference, address _recipient, address _token, uint _amount, uint _paymentDelay ) whenNotPaused external returns(uint) { // Fail if you arent on the `allowedSpenders` white list require(allowedSpenders[msg.sender]); uint idPayment = authorizedPayments.length; // Unique Payment ID authorizedPayments.length++; // The following lines fill out the payment struct Payment storage p = authorizedPayments[idPayment]; p.spender = msg.sender; // Overflow protection require(_paymentDelay <= 10**18); // Determines the earliest the recipient can receive payment (Unix time) p.earliestPayTime = _paymentDelay >= timeLock ? _getTime() + _paymentDelay : _getTime() + timeLock; p.recipient = _recipient; p.amount = _amount; p.name = _name; p.reference = _reference; p.token = _token; emit PaymentAuthorized(idPayment, p.recipient, p.amount, p.token, p.reference); return idPayment; } /// Anyone can call this function to disburse the payment to /// the recipient after `earliestPayTime` has passed /// @param _idPayment The payment ID to be executed function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public { // Check that the `_idPayment` has been added to the payments struct require(_idPayment < authorizedPayments.length); Payment storage p = authorizedPayments[_idPayment]; // Checking for reasons not to execute the payment require(allowedSpenders[p.spender]); require(_getTime() >= p.earliestPayTime); require(!p.canceled); require(!p.paid); p.paid = true; // Set the payment to being paid // Make the payment if (p.token == 0) { p.recipient.transfer(p.amount); } else { require(ERC20(p.token).transfer(p.recipient, p.amount)); } emit PaymentExecuted(_idPayment, p.recipient, p.amount, p.token); } /// convience function to disburse multiple payments in a single tx function disburseAuthorizedPayments(uint[] _idPayments) public { for (uint i = 0; i < _idPayments.length; i++) { uint _idPayment = _idPayments[i]; disburseAuthorizedPayment(_idPayment); } } ///////// // SecurityGuard Interface ///////// /// @notice `onlySecurityGuard` Delays a payment for a set number of seconds /// @param _idPayment ID of the payment to be delayed /// @param _delay The number of seconds to delay the payment function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard external { require(_idPayment < authorizedPayments.length); // Overflow test require(_delay <= 10**18); Payment storage p = authorizedPayments[_idPayment]; require(p.securityGuardDelay + _delay <= maxSecurityGuardDelay); require(!p.paid); require(!p.canceled); p.securityGuardDelay += _delay; p.earliestPayTime += _delay; } //////// // Owner Interface /////// /// @notice `onlyOwner` Cancel a payment all together /// @param _idPayment ID of the payment to be canceled. function cancelPayment(uint _idPayment) onlyOwner external { require(_idPayment < authorizedPayments.length); Payment storage p = authorizedPayments[_idPayment]; require(!p.canceled); require(!p.paid); p.canceled = true; emit PaymentCanceled(_idPayment); } /// @notice `onlyOwner` Adds a spender to the `allowedSpenders[]` white list /// @param _spender The address of the contract being authorized/unauthorized /// @param _authorize `true` if authorizing and `false` if unauthorizing function authorizeSpender(address _spender, bool _authorize) onlyOwner external { allowedSpenders[_spender] = _authorize; emit SpenderAuthorization(_spender, _authorize); } /// @notice `onlyOwner` Sets the address of `securityGuard` /// @param _newSecurityGuard Address of the new security guard function setSecurityGuard(address _newSecurityGuard) onlyOwner external { securityGuard = _newSecurityGuard; } /// @notice `onlyOwner` Changes `timeLock`; the new `timeLock` cannot be /// lower than `absoluteMinTimeLock` /// @param _newTimeLock Sets the new minimum default `timeLock` in seconds; /// pending payments maintain their `earliestPayTime` function setTimelock(uint _newTimeLock) onlyOwner external { require(_newTimeLock >= absoluteMinTimeLock); timeLock = _newTimeLock; } /// @notice `onlyOwner` Changes the maximum number of seconds /// `securityGuard` can delay a payment /// @param _maxSecurityGuardDelay The new maximum delay in seconds that /// `securityGuard` can delay the payment's execution in total function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyOwner external { maxSecurityGuardDelay = _maxSecurityGuardDelay; } /// @dev called by the owner to pause the contract. Triggers a stopped state /// and resets allowDisbursePaymentWhenPaused to false function pause() onlyOwner whenNotPaused public { allowDisbursePaymentWhenPaused = false; super.pause(); } /// Owner can allow payment disbursement when the contract is paused. This is so the /// bridge can be upgraded without having to migrate any existing authorizedPayments /// @dev only callable whenPaused b/c pausing the contract will reset `allowDisbursePaymentWhenPaused` to false /// @param allowed `true` if allowing payments to be disbursed when paused, otherwise 'false' function setAllowDisbursePaymentWhenPaused(bool allowed) onlyOwner whenPaused public { allowDisbursePaymentWhenPaused = allowed; } // for overidding during testing function _getTime() internal view returns (uint) { return now; } } ///File: ./contracts/lib/FailClosedVault.sol pragma solidity ^0.4.21; /* Copyright 2018, RJ Ewing 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/>. */ /** * @dev `FailClosedVault` is a version of the vault that requires * the securityGuard to "see" each payment before it can be collected */ contract FailClosedVault is Vault { uint public securityGuardLastCheckin; /** * @param _absoluteMinTimeLock For this version of the vault, it is recommended * that this value is > 24hrs. If not, it will require the securityGuard to checkIn * multiple times a day. Also consider that `securityGuardLastCheckin >= payment.earliestPayTime - timelock + 30mins);` * is the condition to allow payments to be payed. The additional 30 mins is to reduce (not eliminate) * the risk of front-running */ function FailClosedVault( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay ) Vault( _escapeHatchCaller, _escapeHatchDestination, _absoluteMinTimeLock, _timeLock, _securityGuard, _maxSecurityGuardDelay ) public { } ///////////////////// // Spender Interface ///////////////////// /** * Disburse an authorizedPayment to the recipient if all checks pass. * * @param _idPayment The payment ID to be disbursed */ function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public { // Check that the `_idPayment` has been added to the payments struct require(_idPayment < authorizedPayments.length); Payment storage p = authorizedPayments[_idPayment]; // The current minimum delay for a payment is `timeLock`. Thus the following ensuress // that the `securityGuard` has checked in after the payment was created // @notice earliestPayTime is updated when a payment is delayed. Which may require // another checkIn before the payment can be collected. // @notice We add 30 mins to this to reduce (not eliminate) the risk of front-running require(securityGuardLastCheckin >= p.earliestPayTime - timeLock + 30 minutes); super.disburseAuthorizedPayment(_idPayment); } /////////////////////////// // SecurityGuard Interface /////////////////////////// /** * @notice `onlySecurityGuard` can checkin. If they fail to checkin, * payments will not be allowed to be disbursed, unless the payment has * an `earliestPayTime` <= `securityGuardLastCheckin`. * @notice To reduce the risk of a front-running attack on payments, it * is important that this is called with a resonable gasPrice set for the * current network congestion. If this tx is not mined, within 30 mins * of being sent, it is possible that a payment can be authorized w/o the * securityGuard's knowledge */ function checkIn() onlySecurityGuard external { securityGuardLastCheckin = _getTime(); } } ///File: ./contracts/GivethBridge.sol pragma solidity ^0.4.21; /* Copyright 2017, RJ Ewing <[email protected]> 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/>. */ /** * @notice It is not recommened to call this function outside of the giveth dapp (giveth.io) * this function is bridged to a side chain. If for some reason the sidechain tx fails, the donation * will end up in the givers control inside LiquidPledging contract. If you do not use the dapp, there * will be no way of notifying the sender/giver that the giver has to take action (withdraw/donate) in * the dapp */ contract GivethBridge is FailClosedVault { mapping(address => bool) tokenWhitelist; event Donate(uint64 giverId, uint64 receiverId, address token, uint amount); event DonateAndCreateGiver(address giver, uint64 receiverId, address token, uint amount); event EscapeFundsCalled(address token, uint amount); //== constructor /** * @param _escapeHatchCaller The address of a trusted account or contract to * call `escapeHatch()` to send the ether in this contract to the * `escapeHatchDestination` in the case on an emergency. it would be ideal * if `escapeHatchCaller` cannot move funds out of `escapeHatchDestination` * @param _escapeHatchDestination The address of a safe location (usually a * Multisig) to send the ether held in this contract in the case of an emergency * @param _absoluteMinTimeLock The minimum number of seconds `timelock` can * be set to, if set to 0 the `owner` can remove the `timeLock` completely * @param _timeLock Minimum number of seconds that payments are delayed * after they are authorized (a security precaution) * @param _securityGuard Address that will be able to delay the payments * beyond the initial timelock requirements; can be set to 0x0 to remove * the `securityGuard` functionality * @param _maxSecurityGuardDelay The maximum number of seconds in total * that `securityGuard` can delay a payment so that the owner can cancel * the payment if needed */ function GivethBridge( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay ) FailClosedVault( _escapeHatchCaller, _escapeHatchDestination, _absoluteMinTimeLock, _timeLock, _securityGuard, _maxSecurityGuardDelay ) public { tokenWhitelist[0] = true; // enable eth transfers } //== public methods /** * @notice It is not recommened to call this function outside of the giveth dapp (giveth.io) * this function is bridged to a side chain. If for some reason the sidechain tx fails, the donation * will end up in the givers control inside LiquidPledging contract. If you do not use the dapp, there * will be no way of notifying the sender/giver that the giver has to take action (withdraw/donate) in * the dapp * * @param giver The address to create a 'giver' pledge admin for in the liquidPledging contract * @param receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function donateAndCreateGiver(address giver, uint64 receiverId) payable external { donateAndCreateGiver(giver, receiverId, 0, 0); } /** * @notice It is not recommened to call this function outside of the giveth dapp (giveth.io) * this function is bridged to a side chain. If for some reason the sidechain tx fails, the donation * will end up in the givers control inside LiquidPledging contract. If you do not use the dapp, there * will be no way of notifying the sender/giver that the giver has to take action (withdraw/donate) in * the dapp * * @param giver The address to create a 'giver' pledge admin for in the liquidPledging contract * @param receiverId The adminId of the liquidPledging pledge admin receiving the donation * @param token The token to donate. If donating ETH, then 0x0. Note: the token must be whitelisted * @param _amount The amount of the token to donate. If donating ETH, then 0x0 as the msg.value will be used instead. */ function donateAndCreateGiver(address giver, uint64 receiverId, address token, uint _amount) whenNotPaused payable public { require(giver != 0); require(receiverId != 0); uint amount = _receiveDonation(token, _amount); emit DonateAndCreateGiver(giver, receiverId, token, amount); } /** * @notice It is not recommened to call this function outside of the giveth dapp (giveth.io) * this function is bridged to a side chain. If for some reason the sidechain tx fails, the donation * will end up in the givers control inside LiquidPledging contract. If you do not use the dapp, there * will be no way of notifying the sender/giver that the giver has to take action (withdraw/donate) in * the dapp * * @param giverId The adminId of the liquidPledging pledge admin who is donating * @param receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function donate(uint64 giverId, uint64 receiverId) payable external { donate(giverId, receiverId, 0, 0); } /** * @notice It is not recommened to call this function outside of the giveth dapp (giveth.io) * this function is bridged to a side chain. If for some reason the sidechain tx fails, the donation * will end up in the givers control inside LiquidPledging contract. If you do not use the dapp, there * will be no way of notifying the sender/giver that the giver has to take action (withdraw/donate) in * the dapp * * @param giverId The adminId of the liquidPledging pledge admin who is donating * @param receiverId The adminId of the liquidPledging pledge admin receiving the donation * @param token The token to donate. If donating ETH, then 0x0. Note: the token must be whitelisted * @param _amount The amount of the token to donate. If donating ETH, then 0x0 as the msg.value will be used instead. */ function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) whenNotPaused payable public { require(giverId != 0); require(receiverId != 0); uint amount = _receiveDonation(token, _amount); emit Donate(giverId, receiverId, token, amount); } /** * The `owner` can call this function to add/remove a token from the whitelist * * @param token The address of the token to update * @param accepted Wether or not to accept this token for donations */ function whitelistToken(address token, bool accepted) whenNotPaused onlyOwner external { tokenWhitelist[token] = accepted; } /** * Transfer tokens/eth to the escapeHatchDestination. * Used as a safety mechanism to prevent the bridge from holding too much value * * before being thoroughly battle-tested. * @param _token the token to transfer. 0x0 for ETH * @param _amount the amount to transfer */ function escapeFunds(address _token, uint _amount) external onlyEscapeHatchCallerOrOwner { // @dev Logic for ether if (_token == 0) { escapeHatchDestination.transfer(_amount); // @dev Logic for tokens } else { ERC20 token = ERC20(_token); require(token.transfer(escapeHatchDestination, _amount)); } emit EscapeFundsCalled(_token, _amount); } //== internal methods /** * @dev used to actually receive the donation. Will transfer the token to to this contract */ function _receiveDonation(address token, uint _amount) internal returns(uint amount) { require(tokenWhitelist[token]); amount = _amount; // eth donation if (token == 0) { amount = msg.value; } require(amount > 0); if (token != 0) { require(ERC20(token).transferFrom(msg.sender, this, amount)); } } }
* @notice `onlySecurityGuard` can checkin. If they fail to checkin, payments will not be allowed to be disbursed, unless the payment has an `earliestPayTime` <= `securityGuardLastCheckin`. @notice To reduce the risk of a front-running attack on payments, it is important that this is called with a resonable gasPrice set for the current network congestion. If this tx is not mined, within 30 mins of being sent, it is possible that a payment can be authorized w/o the securityGuard's knowledge/
function checkIn() onlySecurityGuard external { securityGuardLastCheckin = _getTime(); }
10,468,519
[ 1, 68, 3700, 4368, 16709, 68, 848, 866, 267, 18, 971, 2898, 2321, 358, 866, 267, 16, 25754, 903, 486, 506, 2935, 358, 506, 1015, 70, 295, 730, 16, 3308, 326, 5184, 711, 392, 1375, 2091, 17452, 9148, 950, 68, 1648, 1375, 7462, 16709, 3024, 1564, 267, 8338, 225, 2974, 5459, 326, 18404, 434, 279, 6641, 17, 8704, 13843, 603, 25754, 16, 518, 353, 10802, 716, 333, 353, 2566, 598, 279, 400, 265, 429, 16189, 5147, 444, 364, 326, 783, 2483, 356, 75, 6868, 18, 971, 333, 2229, 353, 486, 1131, 329, 16, 3470, 5196, 26381, 434, 3832, 3271, 16, 518, 353, 3323, 716, 279, 5184, 848, 506, 10799, 341, 19, 83, 326, 4373, 16709, 1807, 20272, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 382, 1435, 1338, 4368, 16709, 3903, 288, 203, 3639, 4373, 16709, 3024, 1564, 267, 273, 389, 588, 950, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface StandardToken { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } interface IStakeAndYield { function getRewardToken() external view returns(address); function totalSupply(uint256 stakeType) external view returns(uint256); function totalYieldWithdrawed() external view returns(uint256); function notifyRewardAmount(uint256 reward, uint256 stakeType) external; } interface IController { function withdrawETH(uint256 amount) external; function depositTokenForStrategy(uint256 amount, address addr, address yearnToken, address yearnVault) external; function buyForStrategy( uint256 amount, address rewardToken, address recipient ) external; function withdrawForStrategy( uint256 sharesToWithdraw, address yearnVault ) external; function strategyBalance(address stra) external view returns(uint256); } interface IYearnVault{ function balanceOf(address account) external view returns (uint256); function withdraw(uint256 amount) external; function getPricePerFullShare() external view returns(uint256); function deposit(uint256 _amount) external returns(uint256); } interface IWETH is StandardToken{ function withdraw(uint256 amount) external returns(uint256); } interface ICurve{ function get_virtual_price() external view returns(uint256); function add_liquidity(uint256[2] memory amounts, uint256 min_amounts) external payable returns(uint256); function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 _min_amount) external returns(uint256); } contract YearnCrvAETHStrategy is Ownable { using SafeMath for uint256; uint256 public lastEpochTime; uint256 public lastBalance; uint256 public lastYieldWithdrawed; uint256 public yearnFeesPercent; uint256 public ethPushedToYearn; IStakeAndYield public vault; IController public controller; //crvAETH address yearnDepositableToken = 0xaA17A236F2bAdc98DDc0Cf999AbB47D47Fc0A6Cf; IYearnVault public yearnVault = IYearnVault(0xE625F5923303f1CE7A43ACFEFd11fd12f30DbcA4); //IWETH public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); StandardToken crvAETH = StandardToken(0xaA17A236F2bAdc98DDc0Cf999AbB47D47Fc0A6Cf); ICurve curve = ICurve(0xA96A65c051bF88B4095Ee1f2451C2A9d43F53Ae2); address public operator; uint256 public minRewards = 0.01 ether; uint256 public minDepositable = 0.05 ether; modifier onlyOwnerOrOperator(){ require( msg.sender == owner() || msg.sender == operator, "!owner" ); _; } constructor( address _vault, address _controller ) public{ vault = IStakeAndYield(_vault); controller = IController(_controller); } // Since Owner is calling this function, we can pass // the ETHPerToken amount function epoch(uint256 ETHPerToken) public onlyOwnerOrOperator{ uint256 balance = pendingBalance(); //require(balance > 0, "balance is 0"); uint256 withdrawable = harvest(balance.mul(ETHPerToken).div(1 ether)); lastEpochTime = block.timestamp; lastBalance = lastBalance.add(balance); uint256 currentWithdrawd = vault.totalYieldWithdrawed(); uint256 withdrawAmountToken = currentWithdrawd.sub(lastYieldWithdrawed); if(withdrawAmountToken > 0){ lastYieldWithdrawed = currentWithdrawd; uint256 ethWithdrawed = withdrawAmountToken.mul( ETHPerToken ).div(1 ether); withdrawFromYearn(ethWithdrawed.add(withdrawable)); ethPushedToYearn = ethPushedToYearn.sub(ethWithdrawed); }else{ if(withdrawable > 0){ withdrawFromYearn(withdrawable); } } } function harvest(uint256 ethBalance) private returns( uint256 withdrawable ){ uint256 rewards = calculateRewards(); uint256 depositable = ethBalance > rewards ? ethBalance.sub(rewards) : 0; if(depositable >= minDepositable){ //deposit to yearn controller.depositTokenForStrategy(depositable, address(this), yearnDepositableToken, address(yearnVault)); ethPushedToYearn = ethPushedToYearn.add( depositable ); } if(rewards > minRewards){ withdrawable = rewards > ethBalance ? rewards.sub(ethBalance) : 0; // get DEA and send to Vault controller.buyForStrategy( rewards, vault.getRewardToken(), address(vault) ); }else{ withdrawable = 0; } } function withdrawFromYearn(uint256 ethAmount) private returns(uint256){ uint256 yShares = controller.strategyBalance(address(this)); uint256 sharesToWithdraw = ethAmount.mul(1 ether).div( yearnVault.getPricePerFullShare() ); uint256 curveVirtualPrice = curve.get_virtual_price(); sharesToWithdraw = sharesToWithdraw.mul(curveVirtualPrice).div( 1 ether ); require(yShares >= sharesToWithdraw, "Not enough shares"); controller.withdrawForStrategy( sharesToWithdraw, address(yearnVault) ); return ethAmount; } function calculateRewards() public view returns(uint256){ uint256 yShares = controller.strategyBalance(address(this)); uint256 yETHBalance = yShares.mul( yearnVault.getPricePerFullShare() ).div(1 ether); uint256 curveVirtualPrice = curve.get_virtual_price(); yETHBalance = yETHBalance.mul(curveVirtualPrice).div( 1 ether ); yETHBalance = yETHBalance.mul(1000 - yearnFeesPercent).div(1000); if(yETHBalance > ethPushedToYearn){ return yETHBalance - ethPushedToYearn; } return 0; } function pendingBalance() public view returns(uint256){ uint256 vaultBalance = vault.totalSupply(2); if(vaultBalance < lastBalance){ return 0; } return vaultBalance.sub(lastBalance); } function getLastEpochTime() public view returns(uint256){ return lastEpochTime; } function setYearnFeesPercent(uint256 _val) public onlyOwner{ yearnFeesPercent = _val; } function setOperator(address _addr) public onlyOwner{ operator = _addr; } function setMinRewards(uint256 _val) public onlyOwner{ minRewards = _val; } function setMinDepositable(uint256 _val) public onlyOwner{ minDepositable = _val; } function setController(address _controller, address _vault) public onlyOwner{ if(_controller != address(0)){ controller = IController(_controller); } if(_vault != address(0)){ vault = IStakeAndYield(_vault); } } function emergencyWithdrawETH(uint256 amount, address addr) public onlyOwner{ require(addr != address(0)); payable(addr).transfer(amount); } function emergencyWithdrawERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { StandardToken(_tokenAddr).transfer(_to, _amount); } }
deposit to yearn get DEA and send to Vault
function harvest(uint256 ethBalance) private returns( uint256 withdrawable ){ uint256 rewards = calculateRewards(); uint256 depositable = ethBalance > rewards ? ethBalance.sub(rewards) : 0; if(depositable >= minDepositable){ controller.depositTokenForStrategy(depositable, address(this), yearnDepositableToken, address(yearnVault)); ethPushedToYearn = ethPushedToYearn.add( depositable ); } if(rewards > minRewards){ withdrawable = rewards > ethBalance ? rewards.sub(ethBalance) : 0; controller.buyForStrategy( rewards, vault.getRewardToken(), address(vault) ); withdrawable = 0; } }
1,283,395
[ 1, 323, 1724, 358, 677, 73, 1303, 336, 2030, 37, 471, 1366, 358, 17329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 12, 11890, 5034, 13750, 13937, 13, 3238, 1135, 12, 203, 3639, 2254, 5034, 598, 9446, 429, 203, 565, 262, 95, 203, 3639, 2254, 5034, 283, 6397, 273, 4604, 17631, 14727, 5621, 203, 3639, 2254, 5034, 443, 1724, 429, 273, 13750, 13937, 405, 283, 6397, 692, 13750, 13937, 18, 1717, 12, 266, 6397, 13, 294, 374, 31, 203, 3639, 309, 12, 323, 1724, 429, 1545, 1131, 758, 1724, 429, 15329, 203, 5411, 2596, 18, 323, 1724, 1345, 1290, 4525, 12, 323, 1724, 429, 16, 1758, 12, 2211, 3631, 7010, 7734, 677, 73, 1303, 758, 1724, 429, 1345, 16, 1758, 12, 20513, 1303, 12003, 10019, 203, 5411, 13750, 7621, 329, 774, 61, 73, 1303, 273, 13750, 7621, 329, 774, 61, 73, 1303, 18, 1289, 12, 203, 7734, 443, 1724, 429, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 309, 12, 266, 6397, 405, 1131, 17631, 14727, 15329, 203, 5411, 598, 9446, 429, 273, 283, 6397, 405, 13750, 13937, 692, 283, 6397, 18, 1717, 12, 546, 13937, 13, 294, 374, 31, 203, 5411, 2596, 18, 70, 9835, 1290, 4525, 12, 203, 7734, 283, 6397, 16, 203, 7734, 9229, 18, 588, 17631, 1060, 1345, 9334, 203, 7734, 1758, 12, 26983, 13, 203, 5411, 11272, 203, 5411, 598, 9446, 429, 273, 374, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-03-26 */ // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol 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; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @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; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @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)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/whitelist/IWhitelist.sol pragma solidity ^0.5.0; // Interface to be implemented by the Whitelist contract. contract IWhitelist { function isWhitelisted(address account) public view returns (bool); } // File: contracts/whitelist/Blacklist.sol pragma solidity ^0.5.0; contract Blacklist is IWhitelist, Ownable { using Roles for Roles.Role; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); Roles.Role private _blacklisted; function addBlacklisted(address account) public onlyOwner { _blacklisted.add(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function removeBlacklisted(address account) public onlyOwner { _blacklisted.remove(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function isWhitelisted(address account) public view returns (bool) { return !_blacklisted.has(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } }
* @title Roles @dev Library for managing addresses assigned to a Role./
library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
1,069,769
[ 1, 6898, 225, 18694, 364, 30632, 6138, 6958, 358, 279, 6204, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 19576, 288, 203, 203, 203, 565, 1958, 6204, 288, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 28802, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 5, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 3639, 2478, 18, 29400, 264, 63, 4631, 65, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 3639, 2478, 18, 29400, 264, 63, 4631, 65, 273, 629, 31, 203, 565, 289, 203, 203, 565, 445, 711, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 327, 2478, 18, 29400, 264, 63, 4631, 15533, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >0.7.5; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iL1NFTBridge } from "./interfaces/iL1NFTBridge.sol"; import { iL2NFTBridge } from "./interfaces/iL2NFTBridge.sol"; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /* Library Imports */ import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { CrossDomainEnabled } from "@eth-optimism/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol"; import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@eth-optimism/contracts/contracts/libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { IL2StandardERC721 } from "../standards/IL2StandardERC721.sol"; /* External Imports */ import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import "@eth-optimism/contracts/contracts/L2/predeploys/OVM_GasPriceOracle.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; /** * @title L2NFTBridge * @dev The L2 NFT bridge is a contract which works together with the L1 Standard bridge to * enable ERC721 transitions between L1 and L2. * This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard * bridge. * This contract also acts as a burner of the tokens intended for withdrawal, informing the L1 * bridge to release L1 funds. * * Compiler used: optimistic-solc * Runtime target: OVM */ // add is interface contract L2NFTBridge is iL2NFTBridge, CrossDomainEnabled, ERC721Holder, ReentrancyGuardUpgradeable, PausableUpgradeable { using SafeMath for uint256; /******************************** * External Contract References * ********************************/ address public owner; address public l1NFTBridge; uint256 public extraGasRelay; uint32 public exitL1Gas; enum Network { L1, L2 } // Info of each NFT struct PairNFTInfo { address l1Contract; address l2Contract; Network baseNetwork; // L1 or L2 } // Maps L2 token to tokenId to L1 token contract deposited for the native L2 NFT mapping(address => mapping (uint256 => address)) public exits; // Maps L2 NFT address to NFTInfo mapping(address => PairNFTInfo) public pairNFTInfo; /*************** * Constructor * ***************/ constructor() CrossDomainEnabled(address(0)) {} /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require(msg.sender == owner || owner == address(0), 'Caller is not the owner'); _; } modifier onlyGasPriceOracleOwner() { require(msg.sender == OVM_GasPriceOracle(Lib_PredeployAddresses.OVM_GAS_PRICE_ORACLE).owner(), 'Caller is not the gasPriceOracle owner'); _; } modifier onlyInitialized() { require(address(messenger) != address(0), "Contract has not yet been initialized"); _; } /** * @dev transfer ownership * * @param _newOwner new owner of this contract */ function transferOwnership( address _newOwner ) public onlyOwner() { owner = _newOwner; } /** * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. * @param _l1NFTBridge Address of the L1 bridge deployed to the main chain. */ function initialize( address _l2CrossDomainMessenger, address _l1NFTBridge ) public onlyOwner() initializer() { require(messenger == address(0), "Contract has already been initialized."); require(_l2CrossDomainMessenger != address(0) && _l1NFTBridge != address(0), "zero address not allowed"); messenger = _l2CrossDomainMessenger; l1NFTBridge = _l1NFTBridge; owner = msg.sender; configureGas(100000); __Context_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Configure gas. * * @param _exitL1Gas default finalized withdraw L1 Gas */ function configureGas( uint32 _exitL1Gas ) public onlyOwner() onlyInitialized() { exitL1Gas = _exitL1Gas; } /** * @param _extraGasRelay The extra gas for exiting L2 */ function configureExtraGasRelay( uint256 _extraGasRelay ) public onlyGasPriceOracleOwner() onlyInitialized() { extraGasRelay = _extraGasRelay; } /*** * @dev Add the new NFT pair to the pool * DO NOT add the same NFT token more than once. * * @param _l1Contract L1 NFT contract address * @param _l2Contract L2 NFT contract address * @param _baseNetwork Network where the NFT contract was created * */ function registerNFTPair( address _l1Contract, address _l2Contract, string memory _baseNetwork ) public onlyOwner() { //create2 would prevent this check //require(_l1Contract != _l2Contract, "Contracts should not be the same"); bytes4 erc721 = 0x80ac58cd; require(ERC165Checker.supportsInterface(_l2Contract, erc721), "L2 NFT is not ERC721 compatible"); bytes32 bn = keccak256(abi.encodePacked(_baseNetwork)); bytes32 l1 = keccak256(abi.encodePacked("L1")); bytes32 l2 = keccak256(abi.encodePacked("L2")); // l1 NFT address equal to zero, then pair is not registered yet. // use with caution, can register only once PairNFTInfo storage pairNFT = pairNFTInfo[_l2Contract]; require(pairNFT.l1Contract == address(0), "L1 NFT address already registered"); // _baseNetwork can only be L1 or L2 require(bn == l1 || bn == l2, "Invalid Network"); Network baseNetwork; if (bn == l1) { require(ERC165Checker.supportsInterface(_l2Contract, 0x646dd6ec), "L2 contract is not bridgable"); baseNetwork = Network.L1; } else { baseNetwork = Network.L2; } pairNFTInfo[_l2Contract] = PairNFTInfo({ l1Contract: _l1Contract, l2Contract: _l2Contract, baseNetwork: baseNetwork }); } /*************** * Withdrawing * ***************/ /** * @inheritdoc iL2NFTBridge */ function withdraw( address _l2Contract, uint256 _tokenId, uint32 _l1Gas, bytes calldata _data ) external virtual override nonReentrant() whenNotPaused() { _initiateWithdrawal( _l2Contract, msg.sender, msg.sender, _tokenId, _l1Gas, _data ); } /** * @inheritdoc iL2NFTBridge */ function withdrawTo( address _l2Contract, address _to, uint256 _tokenId, uint32 _l1Gas, bytes calldata _data ) external virtual override nonReentrant() whenNotPaused() { _initiateWithdrawal( _l2Contract, msg.sender, _to, _tokenId, _l1Gas, _data ); } /** * @dev Performs the logic for withdrawals by burning the token and informing the L1 ERC721 Gateway * of the withdrawal. * @param _l2Contract Address of L2 ERC721 where withdrawal was initiated. * @param _from Account to pull the deposit from on L2. * @param _to Account to give the withdrawal to on L1. * @param _tokenId Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateWithdrawal( address _l2Contract, address _from, address _to, uint256 _tokenId, uint32 _l1Gas, bytes calldata _data ) internal { uint256 startingGas = gasleft(); require(startingGas > extraGasRelay, "Insufficient Gas For a Relay Transaction"); uint256 desiredGasLeft = startingGas.sub(extraGasRelay); uint256 i; while (gasleft() > desiredGasLeft) { i++; } PairNFTInfo storage pairNFT = pairNFTInfo[_l2Contract]; require(pairNFT.l1Contract != address(0), "Can't Find L1 NFT Contract"); if (pairNFT.baseNetwork == Network.L1) { address l1Contract = IL2StandardERC721(_l2Contract).l1Contract(); require(pairNFT.l1Contract == l1Contract, "L1 NFT Contract Address Error"); // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // usage address NFTOwner = IL2StandardERC721(_l2Contract).ownerOf(_tokenId); require( msg.sender == NFTOwner || IL2StandardERC721(_l2Contract).getApproved(_tokenId) == msg.sender || IL2StandardERC721(_l2Contract).isApprovedForAll(NFTOwner, msg.sender) ); IL2StandardERC721(_l2Contract).burn(_tokenId); // Construct calldata for l1NFTBridge.finalizeNFTWithdrawal(_to, _amount) bytes memory message; message = abi.encodeWithSelector( iL1NFTBridge.finalizeNFTWithdrawal.selector, l1Contract, _l2Contract, _from, _to, _tokenId, _data ); // Send message up to L1 bridge sendCrossDomainMessage( l1NFTBridge, _l1Gas, message ); } else { // This check could be bypassed by a malicious contract via initcode, // but it takes care of the user error we want to avoid. require(!Address.isContract(msg.sender), "Account not EOA"); // When a native NFT is withdrawn on L2, the L1 Bridge mints the funds to itself for future // withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if // _from is an EOA or address(0). IERC721(_l2Contract).safeTransferFrom( _from, address(this), _tokenId ); // Construct calldata for _l2Contract.finalizeDeposit(_to, _amount) bytes memory message = abi.encodeWithSelector( iL1NFTBridge.finalizeNFTWithdrawal.selector, pairNFT.l1Contract, _l2Contract, _from, _to, _tokenId, _data ); // Send calldata into L2 sendCrossDomainMessage( l1NFTBridge, _l1Gas, message ); exits[_l2Contract][_tokenId] = pairNFT.l1Contract; } emit WithdrawalInitiated(pairNFT.l1Contract, _l2Contract, msg.sender, _to, _tokenId, _data); } /************************************ * Cross-chain Function: Depositing * ************************************/ // /** // * @inheritdoc IL2ERC20Bridge // */ function finalizeDeposit( address _l1Contract, address _l2Contract, address _from, address _to, uint256 _tokenId, bytes calldata _data ) external virtual override onlyFromCrossDomainAccount(l1NFTBridge) { PairNFTInfo storage pairNFT = pairNFTInfo[_l2Contract]; if (pairNFT.baseNetwork == Network.L1) { // Check the target token is compliant and // verify the deposited token on L1 matches the L2 deposited token representation here if ( // check with interface of IL2StandardERC721 ERC165Checker.supportsInterface(_l2Contract, 0x646dd6ec) && _l1Contract == IL2StandardERC721(_l2Contract).l1Contract() ) { // When a deposit is finalized, we credit the account on L2 with the same amount of // tokens. IL2StandardERC721(_l2Contract).mint(_to, _tokenId); emit DepositFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } else { // Either the L2 token which is being deposited-into disagrees about the correct address // of its L1 token, or does not support the correct interface. // This should only happen if there is a malicious L2 token, or if a user somehow // specified the wrong L2 token address to deposit into. // In either case, we stop the process here and construct a withdrawal // message so that users can get their funds out in some cases. // There is no way to prevent malicious token contracts altogether, but this does limit // user error and mitigate some forms of malicious contract behavior. bytes memory message = abi.encodeWithSelector( iL1NFTBridge.finalizeNFTWithdrawal.selector, _l1Contract, _l2Contract, _to, // switched the _to and _from here to bounce back the deposit to the sender _from, _tokenId, _data ); // Send message up to L1 bridge sendCrossDomainMessage( l1NFTBridge, exitL1Gas, message ); emit DepositFailed(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } } else { // needs to verify comes from correct l1Contract require(exits[_l2Contract][_tokenId] == _l1Contract, "Incorrect Deposit"); // When a deposit is finalized on L2, the L2 Bridge transfers the NFT to the depositer IERC721(_l2Contract).safeTransferFrom( address(this), _to, _tokenId ); emit DepositFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data); } } /****************** * Pause * ******************/ /** * Pause contract */ function pause() external onlyOwner() { _pause(); } /** * UnPause contract */ function unpause() external onlyOwner() { _unpause(); } }
* @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. @param _l1NFTBridge Address of the L1 bridge deployed to the main chain./
function initialize( address _l2CrossDomainMessenger, address _l1NFTBridge ) public onlyOwner() initializer() { require(messenger == address(0), "Contract has already been initialized."); require(_l2CrossDomainMessenger != address(0) && _l1NFTBridge != address(0), "zero address not allowed"); messenger = _l2CrossDomainMessenger; l1NFTBridge = _l1NFTBridge; owner = msg.sender; configureGas(100000); __Context_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); }
12,620,387
[ 1, 67, 80, 22, 13941, 3748, 29329, 19742, 17, 4308, 31086, 1399, 635, 333, 6835, 18, 225, 389, 80, 21, 50, 4464, 13691, 5267, 434, 326, 511, 21, 10105, 19357, 358, 326, 2774, 2687, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 203, 3639, 1758, 389, 80, 22, 13941, 3748, 29329, 16, 203, 3639, 1758, 389, 80, 21, 50, 4464, 13691, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1338, 5541, 1435, 203, 3639, 12562, 1435, 203, 565, 288, 203, 3639, 2583, 12, 81, 18912, 422, 1758, 12, 20, 3631, 315, 8924, 711, 1818, 2118, 6454, 1199, 1769, 203, 3639, 2583, 24899, 80, 22, 13941, 3748, 29329, 480, 1758, 12, 20, 13, 597, 389, 80, 21, 50, 4464, 13691, 480, 1758, 12, 20, 3631, 315, 7124, 1758, 486, 2935, 8863, 203, 3639, 31086, 273, 389, 80, 22, 13941, 3748, 29329, 31, 203, 3639, 328, 21, 50, 4464, 13691, 273, 389, 80, 21, 50, 4464, 13691, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 5068, 27998, 12, 21, 11706, 1769, 203, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 16507, 16665, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 426, 8230, 12514, 16709, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x342B6ECbd777AF880702B9670C1A2dECB403bc38/sources/Khroma.sol
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = 0x7Ab7B55a6c6716f9BFe23d8bec4f252241Bd12e5; emit OwnershipTransferred(address(0), _owner); } 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; } }
17,030,809
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 3639, 1758, 8808, 2416, 5541, 16, 203, 3639, 1758, 8808, 394, 5541, 203, 565, 11272, 203, 203, 565, 3885, 1435, 2713, 288, 203, 3639, 389, 8443, 273, 374, 92, 27, 5895, 27, 38, 2539, 69, 26, 71, 9599, 2313, 74, 29, 38, 2954, 4366, 72, 28, 70, 557, 24, 74, 2947, 23622, 21, 38, 72, 2138, 73, 25, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 394, 5541, 480, 1758, 12, 20, 3631, 203, 5411, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 6, 203, 3639, 11272, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 2 ]
./full_match/5/0xdF03d0DD06cd35e547b6A270a8fe821aA788e8aa/sources/src/stake/HoprStakeBase.sol
Cap on actual locked tokens for receiving additional boosts, in LOCK_TOKEN's decimals (1e18)
uint256 public immutable BOOST_CAP;
1,882,180
[ 1, 4664, 603, 3214, 8586, 2430, 364, 15847, 3312, 14994, 87, 16, 316, 14631, 67, 8412, 1807, 15105, 261, 21, 73, 2643, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 11732, 9784, 4005, 67, 17296, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xB6214030521bC6D27c770a6037fdDC07288A6086/sources/browser/myERC20.sol
* @dev Allows the current owner to set the pendingOwner address. @param newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) onlyOwner external { pendingOwner = newOwner; }
13,372,458
[ 1, 19132, 326, 783, 3410, 358, 444, 326, 4634, 5541, 1758, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 3903, 288, 203, 565, 4634, 5541, 273, 394, 5541, 31, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * Copyright 2016 Modum.io and the CSG Group at University of Zurich * * Licensed under the Apache License, Version 2.0 (the 'License'); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ pragma solidity ^0.4.3; contract TemperatureMeasurementA { address owner; address temperatureWriter; string storageLocation; /* set at contract creation */ int8 minTemperature; int8 maxTemperature; uint16 maxFailureReports; /* state */ uint32[] failedTimestampSeconds; int8[] failedTemperatures; uint32 measurements = 0; uint32 failures = 0; uint32 firstTimestamp = 0; uint32 lastTimestamp = 0; bytes32[] hashes; /* Constructor, set who is allowed to write and the temperature range */ function TemperatureMeasurementA(address _temperatureWriter, int8 _minTemperature, int8 _maxTemperature, uint16 _maxFailureReports, string _storageLocation) { owner = msg.sender; temperatureWriter = _temperatureWriter; minTemperature = _minTemperature; maxTemperature = _maxTemperature; if(_maxFailureReports < 1) { throw; } maxFailureReports = _maxFailureReports; storageLocation = _storageLocation; } /* Any remaining funds should be sent back to the sender Both, sender and the reporter can call this function */ function done() { if (msg.sender == owner || msg.sender == temperatureWriter) { suicide(msg.sender); } } function reportResult(uint32[] _failedTimestampSeconds, int8[] _failedTemperatures, uint32 _failures, uint32 _measurements, uint32 _firstTimestamp, uint32 _lastTimestamp, bytes32 _hash) public { /* Only temperature reporter can write temperature */ if (msg.sender != temperatureWriter) { throw; } if(_failedTimestampSeconds.length != _failedTemperatures.length) { throw; } uint32 _current = uint32(failedTimestampSeconds.length); uint32 _len = uint32(_failedTimestampSeconds.length); uint16 _max = maxFailureReports; for (uint32 i = _current; (i - _current) < _len && i < _max; i++) { failedTimestampSeconds.push(_failedTimestampSeconds[(i-_current)]); failedTemperatures.push(_failedTemperatures[(i-_current)]); } measurements += _measurements; failures += _failures; if (firstTimestamp == 0) { firstTimestamp = _firstTimestamp; } lastTimestamp = _lastTimestamp; hashes.push(_hash); } function generateReport2(int8[] _temperatures, uint32[] _timestamps) constant returns (uint32[], int8[], uint32, uint32, bytes32) { uint32 len = uint32 (_temperatures.length); if(len != _timestamps.length) { throw; } uint8[] memory b = new uint8[](5*len); uint32 _failures = 0; uint32[] memory _failedTimestampSeconds; int8[] memory _failedTemperatures; for (uint16 i = 0; i < len; i++) { b[(i*5)+0]=uint8(_timestamps[i]); b[(i*5)+1]=uint8(shr(_timestamps[i], 8)); b[(i*5)+2]=uint8(shr(_timestamps[i], 16)); b[(i*5)+3]=uint8(shr(_timestamps[i], 24)); b[(i*5)+4]=uint8(_temperatures[i]); if(_temperatures[i] > maxTemperature || _temperatures[i] < minTemperature) { _failures++; } } return (_failedTimestampSeconds, _failedTemperatures, _failures, len, sha256(b)); } function generateReport(int8[] _temperatures, uint32[] _timestamps) constant returns (uint32[], int8[], uint32, uint32, bytes32) { var len = uint32 (_temperatures.length); if(len != _timestamps.length) { throw; } uint32 _failures = 0; uint32[] memory _failedTimestampSeconds; int8[] memory _failedTemperatures; uint8[] memory b = new uint8[](5*len); for (uint16 i = 0; i < len; i++) { b[(i*5)+0]=uint8(_timestamps[i]); b[(i*5)+1]=uint8(shr(_timestamps[i], 8)); b[(i*5)+2]=uint8(shr(_timestamps[i], 16)); b[(i*5)+3]=uint8(shr(_timestamps[i], 24)); b[(i*5)+4]=uint8(_temperatures[i]); if(_temperatures[i] > maxTemperature || _temperatures[i] < minTemperature) { _failures++; if(_failures < maxFailureReports) { _failedTimestampSeconds[_failedTimestampSeconds.length] = (_timestamps[i]); _failedTemperatures[_failedTimestampSeconds.length] = (_temperatures[i]); } } } return (_failedTimestampSeconds, _failedTemperatures, _failures, len, sha256(b)); } function verifyReport(uint16 series, int8[] _temperatures, uint32[] _timestamps) constant returns (bool) { var (_failedTimestampSeconds, _failedTemperatures, _failures, _measurements, _hash) = generateReport(_temperatures, _timestamps); if(series == hashes.length - 1) { /* full check */ if(_failedTimestampSeconds.length != failedTimestampSeconds.length || _failedTemperatures.length != failedTemperatures.length || _failedTemperatures.length != _failedTimestampSeconds.length) { return false; } for (uint16 i = 0; i < failedTimestampSeconds.length; i++) { if(_failedTimestampSeconds[i] != failedTimestampSeconds[i]) { return false; } if(_failedTemperatures[i] != failedTemperatures[i]) { return false; } } return hashes[series] == _hash && _failures == failures && _measurements == measurements; } else { /* intermediate, check only hashes */ return hashes[series] == _hash; } } /* Success is when no failed timestamp was reported and at least one measurement was carried out */ function success() constant returns (bool) { return failedTimestampSeconds.length == 0 && measurements > 0; } /* Failed is when one failed timestamp was reported and at least one measurement was carried out */ function failed() constant returns (bool) { return failedTimestampSeconds.length > 0 && measurements > 0; } /* The number of carried out measurements */ function nrMeasurements() constant returns (uint32) { return measurements; } /* The number of reported failures */ function nrFailures() constant returns (uint32) { return failures; } /* The timestamp of the frist temperature that was out of range */ function failedTimestampSecondsAt(uint16 index) constant returns (uint32) { return failedTimestampSeconds[index]; } /* The length of the failed timestamp array */ function failedTimestampLength() constant returns (uint16) { return uint16(failedTimestampSeconds.length); } /* The temperature that was off at given indenx */ function failedTemperaturesAt(uint16 index) constant returns (int8) { return failedTemperatures[index]; } /* The length of the failed temperature array */ function failedTemperaturesLength() constant returns (uint16) { return uint16(failedTemperatures.length); } /* The temperature range to check */ function temperatureRange() constant returns (int8, int8) { return (minTemperature, maxTemperature); } /* The timestamp range */ function timestampFirst() constant returns (uint32) { return firstTimestamp; } function timestampLast() constant returns (uint32) { return lastTimestamp; } /* Hash */ function hashLength() constant returns (uint16) { return uint16(hashes.length); } function hashAt(uint16 index) constant returns (bytes32) { return hashes[index]; } /* shift right, currently not implemented: https://github.com/ethereum/solidity/issues/33 */ function shr(uint32 input, uint8 bits) constant returns (uint32) { return input / (2 ** uint32(bits)); } }
The timestamp of the frist temperature that was out of range */
function failedTimestampSecondsAt(uint16 index) constant returns (uint32) { return failedTimestampSeconds[index]; }
2,478,251
[ 1, 1986, 2858, 434, 326, 3812, 376, 12843, 716, 1703, 596, 434, 1048, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2535, 4921, 6762, 861, 12, 11890, 2313, 770, 13, 5381, 1135, 261, 11890, 1578, 13, 288, 203, 4202, 327, 2535, 4921, 6762, 63, 1615, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xd8c2cd8D6819246D15B312aD95258C26ECFAb2D2/sources/contracts/StrategyProviders/WHProtectivePut.sol
* @notice Returns list of options to be bought in order to follow this strategy @param _amount Amount of underlying asset to hedge @param _period Period of time to hedge trade/
function getOptionsList(uint _amount, uint _period) external view returns (IWHHedge.Option[] memory optionList){ uint currentPrice = getCurrentPrice(); optionList = new IWHHedge.Option[](1); optionList[0] = IWHHedge.Option(currentPrice, _period, _amount, IHegicOptions.OptionType.Put); }
8,616,492
[ 1, 1356, 666, 434, 702, 358, 506, 800, 9540, 316, 1353, 358, 2805, 333, 6252, 225, 389, 8949, 16811, 434, 6808, 3310, 358, 366, 7126, 225, 389, 6908, 12698, 434, 813, 358, 366, 7126, 18542, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9849, 682, 12, 11890, 389, 8949, 16, 2254, 389, 6908, 13, 3903, 1476, 1135, 261, 45, 12557, 44, 7126, 18, 1895, 8526, 3778, 1456, 682, 15329, 203, 3639, 2254, 783, 5147, 273, 5175, 5147, 5621, 203, 3639, 1456, 682, 273, 394, 467, 12557, 44, 7126, 18, 1895, 8526, 12, 21, 1769, 203, 3639, 1456, 682, 63, 20, 65, 273, 467, 12557, 44, 7126, 18, 1895, 12, 2972, 5147, 16, 389, 6908, 16, 389, 8949, 16, 467, 44, 1332, 335, 1320, 18, 1895, 559, 18, 6426, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /** * smatthewenglish oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOo niftynathan * OoOoOoOoOoOoOoOoOoOoOoOoOoO OoOoOoOoOoOoOoOoOoOoOoOoOoOo * OoOoOoOoOoOoOoOoOoOoO OoOoOoOoOoOoOoOoOoOoOo * OoOoOoOoOoOoOoOoOo OoOoOoOoOoOoOoOoOo * OoOoOoOoOoOoOo oOoOoOoOoOoOoOo * OoOoOoOoOoOo OoOoOoOoOoOo * OoOoOoOoOo OoOoOoOoOo * OoOoOoOo OoOoOoOo * OoOoOo OoOoOo * OoOoO oOoOo * OoOo OoOo * OoO oOo * Oo oO * Oo oO * O O * O O * O O * O O * O O * Oo oO * Oo oO * OoO oOo * OoOo OoOo * OoOoO oOoOo * OoOoOo OoOoOo * OoOoOoOo OoOoOoOo * OoOoOoOoOo OoOoOoOoOo * OoOoOoOoOoOo OoOoOoOoOoOo * OoOoOoOoOoOoOo oOoOoOoOoOoOoOo * OoOoOoOoOoOoOoOoOo OoOoOoOoOoOoOoOoOo * OoOoOoOoOoOoOoOoOoOoO OoOoOoOoOoOoOoOoOoOoOo * OoOoOoOoOoOoOoOoOoOoOoOoOoO OoOoOoOoOoOoOoOoOoOoOoOoOoOo * soliditygoldminerz oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOo reviewed by manifold.xyz */ import {IMergeMetadata} from "./MergeMetadata.sol"; interface INiftyRegistry { function isValidNiftySender(address sending_key) external view returns (bool); } 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); } interface ERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); 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 ERC721Metadata { function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory); } contract Merge is ERC721, ERC721Metadata { IMergeMetadata public _metadataGenerator; string private _name; string private _symbol; uint256 constant private CLASS_MULTIPLIER = 100 * 1000 * 1000; // 100 million // valid classes are in the range [1, 4] uint256 constant private MIN_CLASS_INCL = 1; uint256 constant private MAX_CLASS_INCL = 4; function ensureValidClass(uint256 class) private pure { require(MIN_CLASS_INCL <= class && class <= MAX_CLASS_INCL, "Merge: Class must be [1, 4]."); } // valid masses are in the range [1, 100m - 1) uint256 constant private MIN_MASS_INCL = 1; uint256 constant private MAX_MASS_EXCL = CLASS_MULTIPLIER - 1; function ensureValidMass(uint256 mass) private pure { require(MIN_MASS_INCL <= mass && mass < MAX_MASS_EXCL, "Merge: Mass must be [1, 100m - 1)."); } function isSentinelMass(uint256 value) private pure returns (bool) { return (value % CLASS_MULTIPLIER) == MAX_MASS_EXCL; } bool public _mintingFinalized; bool public frozen; uint256 public _nextMintId; uint256 public _countToken; uint256 immutable public _percentageTotal; uint256 public _percentageRoyalty; uint256 public _alphaMass; uint256 public _alphaId; uint256 public _massTotal; address public _pak; address constant public _dead = 0x000000000000000000000000000000000000dEaD; address public _omnibus; address public _receiver; address immutable public _registry; event AlphaMassUpdate(uint256 indexed tokenId, uint256 alphaMass); event MassUpdate(uint256 indexed tokenIdBurned, uint256 indexed tokenIdPersist, uint256 mass); // Mapping of addresses disbarred from holding any token. mapping (address => bool) private _blacklistAddress; // Mapping of address allowed to hold multiple tokens. mapping (address => bool) private _whitelistAddress; // Mapping from owner address to token ID. mapping (address => uint256) private _tokens; // Mapping owner address to token count. mapping (address => uint256) private _balances; // Mapping from token ID to owner address. mapping (uint256 => address) private _owners; // Mapping from token ID to approved address. mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals. mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping token ID to mass value. mapping (uint256 => uint256) private _values; // Mapping token ID to all quantity merged into it. mapping (uint256 => uint256) private _mergeCount; function getMergeCount(uint256 tokenId) public view returns (uint256 mergeCount) { require(_exists(tokenId), "ERC721: nonexistent token"); return _mergeCount[tokenId]; } modifier onlyPak() { require(_msgSender() == _pak, "Merge: msg.sender is not pak"); _; } modifier onlyValidWhitelist() { require(_whitelistAddress[_msgSender()], "Merge: Invalid msg.sender"); _; } modifier onlyValidSender() { require(INiftyRegistry(_registry).isValidNiftySender(_msgSender()), "Merge: Invalid msg.sender"); _; } modifier notFrozen() { require(!frozen, "Merge: movement frozen"); _; } /** * @dev Set the values carefully! * * Requirements: * * - `registry_` enforce access control on state-changing ops * - `omnibus_` for efficient minting of initial token stock * - `metadataGenerator_` * - `pak_` - Initial pak address (0x2Ce780D7c743A57791B835a9d6F998B15BBbA5a4) * */ constructor(address registry_, address omnibus_, address metadataGenerator_, address pak_) { _nextMintId = 1; _registry = registry_; _omnibus = omnibus_; _metadataGenerator = IMergeMetadata(metadataGenerator_); _name = "merge."; _symbol = "m"; _pak = pak_; _receiver = pak_; _percentageTotal = 10000; _percentageRoyalty = 1000; _blacklistAddress[address(this)] = true; _whitelistAddress[omnibus_] = true; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view returns (uint256) { return _countToken; } function merge(uint256 tokenIdRcvr, uint256 tokenIdSndr) external onlyValidWhitelist notFrozen returns (uint256 tokenIdDead) { address owner = ownerOf(tokenIdRcvr); require(owner == ownerOf(tokenIdSndr), "Merge: Illegal argument disparate owner."); require(_msgSender() == owner, "ERC721: msg.sender is not token owner."); // owners are same, so decrement their balance as we are merging _balances[owner] -= 1; tokenIdDead = _merge(tokenIdRcvr, tokenIdSndr); // clear ownership of dead token delete _owners[tokenIdDead]; // owners are the same; burn dead token from common owner emit Transfer(owner, address(0), tokenIdDead); } function _transfer(address owner, address from, address to, uint256 tokenId) internal notFrozen { require(owner == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(!_blacklistAddress[to], "Merge: transfer attempt to blacklist address"); // if transferring to `_dead_` then `_transfer` is interpreted as a burn if (to == _dead) { _burnNoEmitTransfer(owner, tokenId); emit Transfer(from, _dead, tokenId); emit Transfer(_dead, address(0), tokenId); } else { // Clear any prior approvals // includes an emit of Approval to zero _approve(owner, address(0), tokenId); // in all cases we first wish to log the transfer // no merging later can deny the fact that `from` transferred to `to` emit Transfer(from, to, tokenId); if (from == to) { // !non-local control flow! // we make an exception here, as it’s easy to follow that a self transfer // can skip _all_ following state changes return; } // if all addresses were whitelisted, then transfer would be like any other ERC-721 // _balances[from] -= 1; // _balances[to] += 1; // _owners[tokenId] = to; // _balances (1) and _owners (2) are the main mappings to update // for non-whitelisted addresses there is also the _tokens (3) mapping // // Our updates will be // - 1a: decrement balance of `from` // - 1b: update balance of `to` (not guaranteed to increase) // - 2: assign ownership of `tokenId` // - 3a: assign unique token of `to` // - 3b: unassign unique token of `from` bool fromIsWhitelisted = isWhitelisted(from); bool toIsWhitelisted = isWhitelisted(to); // BEGIN PART 1: update _balances // // PART 1a: decrease balance of `from` // the classic implementation would be // _balances[from] -= 1; if (fromIsWhitelisted) { // from the reasoning: // > if all addresses were whitelisted, then transfer would be like any other ERC-721 _balances[from] -= 1; } else { // for non-whitelisted addresses, we have the invariant that // _balances[a] <= 1 // we known that `from` was the owner so the only possible state is // _balances[from] == 1 // to save an SLOAD, we can assign a balance of 0 (or delete) delete _balances[from]; } // PART 1b: increase balance of `to` // the classic implementation would be // _balances[to] += 1; if (toIsWhitelisted) { // from the reasoning: // > if all addresses were whitelisted, then transfer would be like any other ERC-721 _balances[to] += 1; } else if (_tokens[to] == 0) { // for non-whitelisted addresses, we have the invariant that // _balances[a] <= 1 // if _tokens[to] == 0 then _balances[to] == 0 // to save an SLOAD, we can assign a balance of 1 _balances[to] = 1; } else { // for non-whitelisted addresses, we have the invariant that // _balances[a] <= 1 // if _tokens[to] != 0 then _balance[to] == 1 // to preserve the invariant, we have nothing to do (the balance is already 1) } // END PART 1 if (toIsWhitelisted) { // PART 2: update _owners // assign ownership of token // the classic implementation would be // _owners[tokenId] = to; // // from the reasoning: // > if all addresses were whitelisted, then transfer would be like any other ERC-721 _owners[tokenId] = to; } else { // label current and sent token with respect to address `to` uint256 currentTokenId = _tokens[to]; if (currentTokenId == 0) { // PART 2: update _owners // assign ownership of token _owners[tokenId] = to; // PART 3a // assign unique token of `to` _tokens[to] = tokenId; } else { uint256 sentTokenId = tokenId; // compute token merge, returning the dead token uint256 deadTokenId = _merge(currentTokenId, sentTokenId); // logically, the token has already been transferred to `to` // so log the burning of the dead token id as originating ‘from’ `to` emit Transfer(to, address(0), deadTokenId); // thus inferring the alive token uint256 aliveTokenId = currentTokenId; if (currentTokenId == deadTokenId) { aliveTokenId = sentTokenId; } // PART 2 continued: // and ownership of dead token is deleted delete _owners[deadTokenId]; // if received token surplanted the current token if (currentTokenId != aliveTokenId) { // PART 2 continued: // to takes ownership of alive token _owners[aliveTokenId] = to; // PART 3a // assign unique token of `to` _tokens[to] = aliveTokenId; } } } // PART 3b: // unassign unique token of `from` // // _tokens is only defined for non-whitelisted addresses if (!fromIsWhitelisted) { delete _tokens[from]; } } } function _merge(uint256 tokenIdRcvr, uint256 tokenIdSndr) internal returns (uint256 tokenIdDead) { require(tokenIdRcvr != tokenIdSndr, "Merge: Illegal argument identical tokenId."); uint256 massRcvr = decodeMass(_values[tokenIdRcvr]); uint256 massSndr = decodeMass(_values[tokenIdSndr]); uint256 massSmall = massRcvr; uint256 massLarge = massSndr; uint256 tokenIdSmall = tokenIdRcvr; uint256 tokenIdLarge = tokenIdSndr; if (massRcvr >= massSndr) { massSmall = massSndr; massLarge = massRcvr; tokenIdSmall = tokenIdSndr; tokenIdLarge = tokenIdRcvr; } _values[tokenIdLarge] += massSmall; uint256 combinedMass = massLarge + massSmall; if(combinedMass > _alphaMass) { _alphaId = tokenIdLarge; _alphaMass = combinedMass; emit AlphaMassUpdate(_alphaId, combinedMass); } _mergeCount[tokenIdLarge]++; delete _values[tokenIdSmall]; _countToken -= 1; emit MassUpdate(tokenIdSmall, tokenIdLarge, combinedMass); return tokenIdSmall; } function setRoyaltyBips(uint256 percentageRoyalty_) external onlyPak { require(percentageRoyalty_ <= _percentageTotal, "Merge: Illegal argument more than 100%"); _percentageRoyalty = percentageRoyalty_; } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address, uint256) { uint256 royaltyAmount = (salePrice * _percentageRoyalty) / _percentageTotal; return (_receiver, royaltyAmount); } function setBlacklistAddress(address address_, bool status) external onlyPak { require(address_ != _omnibus, "Merge: Illegal argument address_ is _omnibus."); _blacklistAddress[address_] = status; } function setPak(address pak_) external onlyPak { _pak = pak_; } function setRoyaltyReceiver(address receiver_) external onlyPak { _receiver = receiver_; } function setMetadataGenerator(address metadataGenerator_) external onlyPak { _metadataGenerator = IMergeMetadata(metadataGenerator_); } function whitelistUpdate(address address_, bool status) external onlyPak { if(address_ == _omnibus){ require(status != false, "Merge: Illegal argument _omnibus can't be removed."); } if(status == false) { require(balanceOf(address_) <= 1, "Merge: Address with more than one token can't be removed."); } _whitelistAddress[address_] = status; } function isWhitelisted(address address_) public view returns (bool) { return _whitelistAddress[address_]; } function isBlacklisted(address address_) public view returns (bool) { return _blacklistAddress[address_]; } function ownerOf(uint256 tokenId) public view override returns (address owner) { owner = _owners[tokenId]; require(owner != address(0), "ERC721: nonexistent token"); } /** * @dev Generate the NFTs of this collection. * * [20001000, 20000900, ] * * Requirements: * * - `values_` provided as a list of addresses, each of * which implicitly corresponds to a tokenId, * derrived by the index of the value in the * input array. The values map to a color * attribute. * * Emits a series of {Transfer} events. */ function mint(uint256[] calldata values_) external onlyValidSender { require(!_mintingFinalized, "Merge: Minting is finalized."); // for efficiency reasons copy from storage into local variables uint256 index = _nextMintId; uint256 alphaId = _alphaId; uint256 alphaMass = _alphaMass; address omnibus = _omnibus; // initialize accumulators and counters uint256 massAdded = 0; uint256 newlyMintedCount = 0; uint256 valueIx = 0; while (valueIx < values_.length) { if (isSentinelMass(values_[valueIx])) { // SKIP FLAG SET - DON'T MINT } else { newlyMintedCount++; _values[index] = values_[valueIx]; _owners[index] = omnibus; (/* uint256 class */, uint256 mass) = decodeClassAndMass(values_[valueIx]); if (alphaMass < mass){ alphaMass = mass; alphaId = index; } massAdded += mass; emit Transfer(address(0), omnibus, index); } // update counters for loop valueIx++; index++; } // return new token id index to storage _nextMintId = index; // update token supply and balances based on batch mint _countToken += newlyMintedCount; _balances[omnibus] += newlyMintedCount; // update total mass in system with aggregate mass of batch mint // we must fail if we attempt to mint sufficient mass such that it // new total mass in the system becomes unrepresentable // i.e., total mass must be bounded by MAX_MASS_EXCL uint256 prevMassTotal = _massTotal; uint256 newMassTotal = prevMassTotal + massAdded; require(newMassTotal < MAX_MASS_EXCL, "Merge: Mass total overflow"); _massTotal = newMassTotal; // if the alpha was supplanted during minting, // then return that new state to storage if(_alphaId != alphaId) { _alphaId = alphaId; _alphaMass = alphaMass; emit AlphaMassUpdate(alphaId, alphaMass); } } function batchSetMergeCountFromSnapshot(uint256[] calldata tokenIds_, uint256[] calldata mergeCounts_) external onlyValidSender { require(!_mintingFinalized, "Merge: Minting is finalized."); require(tokenIds_.length == mergeCounts_.length, ""); for(uint256 i = 0 ; i < tokenIds_.length; i++) { _mergeCount[tokenIds_[i]] = mergeCounts_[i]; } } function finalize() external onlyPak { thaw(); _mintingFinalized = true; } function freeze() external onlyPak { require(!_mintingFinalized); frozen = true; } function thaw() public onlyPak { frozen = false; } 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 { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function transferFrom(address from, address to, uint256 tokenId) public virtual override { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, "ERC721: transfer caller is not owner nor approved"); _transfer(owner, from, to, tokenId); } function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } function massOf(uint256 tokenId) public view virtual returns (uint256) { uint256 value = getValueOf(tokenId); return decodeMass(value); } function getValueOf(uint256 tokenId) public view virtual returns (uint256 value) { value = _values[tokenId]; require(value != 0, "ERC721: nonexistent token"); } function tokenOf(address owner) public view virtual returns (uint256) { require(!isWhitelisted(owner), "Merge: tokenOf undefined"); uint256 token = _tokens[owner]; return token; } function approve(address to, uint256 tokenId) public virtual override { address owner = 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(owner, to, tokenId); } function _approve(address owner, address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: 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 exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } function _exists(uint256 tokenId) internal view returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (address owner, bool isApprovedOrOwner) { owner = _owners[tokenId]; require(owner != address(0), "ERC721: nonexistent token"); isApprovedOrOwner = (spender == owner || _tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } function tokenURI(uint256 tokenId) public virtual view override returns (string memory) { require(_exists(tokenId), "ERC721: nonexistent token"); return _metadataGenerator.tokenMetadata( tokenId, decodeClass(_values[tokenId]), decodeMass(_values[tokenId]), decodeMass(_values[_alphaId]), tokenId == _alphaId, getMergeCount(tokenId)); } function encodeClassAndMass(uint256 class, uint256 mass) public pure returns (uint256) { ensureValidClass(class); ensureValidMass(mass); return ((class * CLASS_MULTIPLIER) + mass); } function decodeClassAndMass(uint256 value) public pure returns (uint256, uint256) { uint256 class = decodeClass(value); uint256 mass = decodeMass(value); return (class, mass); } function decodeClass(uint256 value) public pure returns (uint256 class) { class = value / CLASS_MULTIPLIER; // integer division is ‘checked’ in Solidity 0.8.x ensureValidClass(class); } function decodeMass(uint256 value) public pure returns (uint256 mass) { mass = value % CLASS_MULTIPLIER; // integer modulo is ‘checked’ in Solidity 0.8.x ensureValidMass(mass); } function _msgSender() internal view returns (address) { return msg.sender; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (isContract(to)) { 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"); } // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } return true; } function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { bytes4 _ERC165_ = 0x01ffc9a7; bytes4 _ERC721_ = 0x80ac58cd; bytes4 _ERC2981_ = 0x2a55205a; bytes4 _ERC721Metadata_ = 0x5b5e139f; return interfaceId == _ERC165_ || interfaceId == _ERC721_ || interfaceId == _ERC2981_ || interfaceId == _ERC721Metadata_; } function burn(uint256 tokenId) public notFrozen { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, "ERC721: caller is not owner nor approved"); _burnNoEmitTransfer(owner, tokenId); emit Transfer(owner, address(0), tokenId); } function _burnNoEmitTransfer(address owner, uint256 tokenId) internal { _approve(owner, address(0), tokenId); _massTotal -= decodeMass(_values[tokenId]); delete _tokens[owner]; delete _owners[tokenId]; delete _values[tokenId]; _countToken -= 1; _balances[owner] -= 1; emit MassUpdate(tokenId, 0, 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /** * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX .*** XXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ,********* XXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX *************** XXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX .******************* XXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX *********** ********** XXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX *********** *********** XXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXX *********** *************** XXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXX *********** **** ********* XXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXX ********* *** *** ********* XXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXX ********** ***** *********** XXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXX /////.************* *********** XXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXX /////////...*********** ************ XXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXX/ ///////////..... ///////// /////////// XXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXX / //////........./////////////////// XXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXX .///////...........////////////// XXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXX .///////.....//..//// ///////// XXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXX# ///////////////////// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXX //////////////////// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXX ////////////// ////// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ import {ABDKMath64x64} from "../util/ABDKMath64x64.sol"; import {Base64} from "../util/Base64.sol"; import {Roots} from "../util/Roots.sol"; import {Strings} from "../util/Strings.sol"; interface IMergeMetadata { function tokenMetadata( uint256 tokenId, uint256 rarity, uint256 tokenMass, uint256 alphaMass, bool isAlpha, uint256 mergeCount) external view returns (string memory); } contract MergeMetadata is IMergeMetadata { struct ERC721MetadataStructure { bool isImageLinked; string name; string description; string createdBy; string image; ERC721MetadataAttribute[] attributes; } struct ERC721MetadataAttribute { bool includeDisplayType; bool includeTraitType; bool isValueAString; string displayType; string traitType; string value; } using ABDKMath64x64 for int128; using Base64 for string; using Roots for uint; using Strings for uint256; address public owner; string private _name; string private _imageBaseURI; string private _imageExtension; uint256 private _maxRadius; string[] private _imageParts; mapping (string => string) private _classStyles; string constant private _RADIUS_TAG = '<RADIUS>'; string constant private _CLASS_TAG = '<CLASS>'; string constant private _CLASS_STYLE_TAG = '<CLASS_STYLE>'; constructor() { owner = msg.sender; _name = "m"; _imageBaseURI = ""; // Set to empty string - results in on-chain SVG generation by default unless this is set later _imageExtension = ""; // Set to empty string - can be changed later to remain empty, .png, .mp4, etc _maxRadius = 1000; // Deploy with default SVG image parts - can be completely replaced later _imageParts.push("<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='2000' height='2000'>"); _imageParts.push("<style>"); _imageParts.push(".m1 #c{fill: #fff;}"); _imageParts.push(".m1 #r{fill: #000;}"); _imageParts.push(".m2 #c{fill: #fc3;}"); _imageParts.push(".m2 #r{fill: #000;}"); _imageParts.push(".m3 #c{fill: #fff;}"); _imageParts.push(".m3 #r{fill: #33f;}"); _imageParts.push(".m4 #c{fill: #fff;}"); _imageParts.push(".m4 #r{fill: #f33;}"); _imageParts.push(".a #c{fill: #000 !important;}"); _imageParts.push(".a #r{fill: #fff !important;}"); _imageParts.push(_CLASS_STYLE_TAG); _imageParts.push("</style>"); _imageParts.push("<g class='"); _imageParts.push(_CLASS_TAG); _imageParts.push("'>"); _imageParts.push("<rect id='r' width='2000' height='2000'/>"); _imageParts.push("<circle id='c' cx='1000' cy='1000' r='"); _imageParts.push(_RADIUS_TAG); _imageParts.push("'/>"); _imageParts.push("</g>"); _imageParts.push("</svg>"); } function setName(string calldata name_) external { _requireOnlyOwner(); _name = name_; } function setImageBaseURI(string calldata imageBaseURI_, string calldata imageExtension_) external { _requireOnlyOwner(); _imageBaseURI = imageBaseURI_; _imageExtension = imageExtension_; } function setMaxRadius(uint256 maxRadius_) external { _requireOnlyOwner(); _maxRadius = maxRadius_; } function tokenMetadata(uint256 tokenId, uint256 rarity, uint256 tokenMass, uint256 alphaMass, bool isAlpha, uint256 mergeCount) external view override returns (string memory) { string memory base64Json = Base64.encode(bytes(string(abi.encodePacked(_getJson(tokenId, rarity, tokenMass, alphaMass, isAlpha, mergeCount))))); return string(abi.encodePacked('data:application/json;base64,', base64Json)); } function updateImageParts(string[] memory imageParts_) public { _requireOnlyOwner(); _imageParts = imageParts_; } function updateClassStyle(string calldata cssClass, string calldata cssStyle) external { _requireOnlyOwner(); _classStyles[cssClass] = cssStyle; } function getClassStyle(string memory cssClass) public view returns (string memory) { return _classStyles[cssClass]; } function name() public view returns (string memory) { return _name; } function imageBaseURI() public view returns (string memory) { return _imageBaseURI; } function imageExtension() public view returns (string memory) { return _imageExtension; } function maxRadius() public view returns (uint256) { return _maxRadius; } function getClassString(uint256 tokenId, uint256 rarity, bool isAlpha, bool offchainImage) public pure returns (string memory) { return _getClassString(tokenId, rarity, isAlpha, offchainImage); } function _getJson(uint256 tokenId, uint256 rarity, uint256 tokenMass, uint256 alphaMass, bool isAlpha, uint256 mergeCount) private view returns (string memory) { string memory imageData = bytes(_imageBaseURI).length == 0 ? _getSvg(tokenId, rarity, tokenMass, alphaMass, isAlpha) : string(abi.encodePacked(imageBaseURI(), _getClassString(tokenId, rarity, isAlpha, true), "_", uint256(int256(_getScaledRadius(tokenMass, alphaMass, _maxRadius).toInt())).toString(), imageExtension())); ERC721MetadataStructure memory metadata = ERC721MetadataStructure({ isImageLinked: bytes(_imageBaseURI).length > 0, name: string(abi.encodePacked(name(), "(", tokenMass.toString(), ") #", tokenId.toString())), description: tokenMass.toString(), createdBy: "Pak", image: imageData, attributes: _getJsonAttributes(tokenId, rarity, tokenMass, mergeCount, isAlpha) }); return _generateERC721Metadata(metadata); } function _getJsonAttributes(uint256 tokenId, uint256 rarity, uint256 tokenMass, uint256 mergeCount, bool isAlpha) private pure returns (ERC721MetadataAttribute[] memory) { uint256 tensDigit = tokenId % 100 / 10; uint256 onesDigit = tokenId % 10; uint256 class = tensDigit * 10 + onesDigit; ERC721MetadataAttribute[] memory metadataAttributes = new ERC721MetadataAttribute[](5); metadataAttributes[0] = _getERC721MetadataAttribute(false, true, false, "", "Mass", tokenMass.toString()); metadataAttributes[1] = _getERC721MetadataAttribute(false, true, false, "", "Alpha", isAlpha ? "1" : "0"); metadataAttributes[2] = _getERC721MetadataAttribute(false, true, false, "", "Tier", rarity.toString()); metadataAttributes[3] = _getERC721MetadataAttribute(false, true, false, "", "Class", class.toString()); metadataAttributes[4] = _getERC721MetadataAttribute(false, true, false, "", "Merges", mergeCount.toString()); return metadataAttributes; } function _getERC721MetadataAttribute(bool includeDisplayType, bool includeTraitType, bool isValueAString, string memory displayType, string memory traitType, string memory value) private pure returns (ERC721MetadataAttribute memory) { ERC721MetadataAttribute memory attribute = ERC721MetadataAttribute({ includeDisplayType: includeDisplayType, includeTraitType: includeTraitType, isValueAString: isValueAString, displayType: displayType, traitType: traitType, value: value }); return attribute; } function _getSvg(uint256 tokenId, uint256 rarity, uint256 tokenMass, uint256 alphaMass, bool isAlpha) private view returns (string memory) { bytes memory byteString; for (uint i = 0; i < _imageParts.length; i++) { if (_checkTag(_imageParts[i], _RADIUS_TAG)) { byteString = abi.encodePacked(byteString, _floatToString(_getScaledRadius(tokenMass, alphaMass, _maxRadius))); } else if (_checkTag(_imageParts[i], _CLASS_TAG)) { byteString = abi.encodePacked(byteString, _getClassString(tokenId, rarity, isAlpha, false)); } else if (_checkTag(_imageParts[i], _CLASS_STYLE_TAG)) { uint256 tensDigit = tokenId % 100 / 10; uint256 onesDigit = tokenId % 10; uint256 class = tensDigit * 10 + onesDigit; string memory classCss = getClassStyle(_getTokenIdClass(class)); if(bytes(classCss).length > 0) { byteString = abi.encodePacked(byteString, classCss); } } else { byteString = abi.encodePacked(byteString, _imageParts[i]); } } return string(byteString); } function _getScaledRadius(uint256 tokenMass, uint256 alphaMass, uint256 maximumRadius) private pure returns (int128) { int128 radiusMass = _getRadius64x64(tokenMass); int128 radiusAlphaMass = _getRadius64x64(alphaMass); int128 scalePercentage = ABDKMath64x64.div(radiusMass, radiusAlphaMass); int128 scaledRadius = ABDKMath64x64.mul(ABDKMath64x64.fromUInt(maximumRadius), scalePercentage); if(uint256(int256(scaledRadius.toInt())) == 0) { scaledRadius = ABDKMath64x64.fromUInt(1); } return scaledRadius; } // Radius = Cube Root(Mass) * Cube Root (0.23873241463) // Radius = Cube Root(Mass) * 0.62035049089 function _getRadius64x64(uint256 mass) private pure returns (int128) { int128 cubeRootScalar = ABDKMath64x64.divu(62035049089, 100000000000); int128 cubeRootMass = ABDKMath64x64.divu(mass.nthRoot(3, 6, 32), 1000000); int128 radius = ABDKMath64x64.mul(cubeRootMass, cubeRootScalar); return radius; } function _generateERC721Metadata(ERC721MetadataStructure memory metadata) private pure returns (string memory) { bytes memory byteString; byteString = abi.encodePacked( byteString, _openJsonObject()); byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("name", metadata.name, true)); byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("description", metadata.description, true)); byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("created_by", metadata.createdBy, true)); if(metadata.isImageLinked) { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("image", metadata.image, true)); } else { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("image_data", metadata.image, true)); } byteString = abi.encodePacked( byteString, _pushJsonComplexAttribute("attributes", _getAttributes(metadata.attributes), false)); byteString = abi.encodePacked( byteString, _closeJsonObject()); return string(byteString); } function _getAttributes(ERC721MetadataAttribute[] memory attributes) private pure returns (string memory) { bytes memory byteString; byteString = abi.encodePacked( byteString, _openJsonArray()); for (uint i = 0; i < attributes.length; i++) { ERC721MetadataAttribute memory attribute = attributes[i]; byteString = abi.encodePacked( byteString, _pushJsonArrayElement(_getAttribute(attribute), i < (attributes.length - 1))); } byteString = abi.encodePacked( byteString, _closeJsonArray()); return string(byteString); } function _getAttribute(ERC721MetadataAttribute memory attribute) private pure returns (string memory) { bytes memory byteString; byteString = abi.encodePacked( byteString, _openJsonObject()); if(attribute.includeDisplayType) { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("display_type", attribute.displayType, true)); } if(attribute.includeTraitType) { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("trait_type", attribute.traitType, true)); } if(attribute.isValueAString) { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveStringAttribute("value", attribute.value, false)); } else { byteString = abi.encodePacked( byteString, _pushJsonPrimitiveNonStringAttribute("value", attribute.value, false)); } byteString = abi.encodePacked( byteString, _closeJsonObject()); return string(byteString); } function _getClassString(uint256 tokenId, uint256 rarity, bool isAlpha, bool offchainImage) private pure returns (string memory) { bytes memory byteString; byteString = abi.encodePacked(byteString, _getRarityClass(rarity)); if(isAlpha) { byteString = abi.encodePacked( byteString, string(abi.encodePacked(offchainImage ? "_" : " ", "a"))); } uint256 tensDigit = tokenId % 100 / 10; uint256 onesDigit = tokenId % 10; uint256 class = tensDigit * 10 + onesDigit; byteString = abi.encodePacked( byteString, string(abi.encodePacked(offchainImage ? "_" : " ", _getTokenIdClass(class)))); return string(byteString); } function _getRarityClass(uint256 rarity) private pure returns (string memory) { return string(abi.encodePacked("m", rarity.toString())); } function _getTokenIdClass(uint256 class) private pure returns (string memory) { return string(abi.encodePacked("c", class.toString())); } function _checkTag(string storage a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function _floatToString(int128 value) private pure returns (string memory) { uint256 decimal4 = (value & 0xFFFFFFFFFFFFFFFF).mulu(10000); return string(abi.encodePacked(uint256(int256(value.toInt())).toString(), '.', _decimal4ToString(decimal4))); } function _decimal4ToString(uint256 decimal4) private pure returns (string memory) { bytes memory decimal4Characters = new bytes(4); for (uint i = 0; i < 4; i++) { decimal4Characters[3 - i] = bytes1(uint8(0x30 + decimal4 % 10)); decimal4 /= 10; } return string(abi.encodePacked(decimal4Characters)); } function _requireOnlyOwner() private view { require(msg.sender == owner, "You are not the owner"); } function _openJsonObject() private pure returns (string memory) { return string(abi.encodePacked("{")); } function _closeJsonObject() private pure returns (string memory) { return string(abi.encodePacked("}")); } function _openJsonArray() private pure returns (string memory) { return string(abi.encodePacked("[")); } function _closeJsonArray() private pure returns (string memory) { return string(abi.encodePacked("]")); } function _pushJsonPrimitiveStringAttribute(string memory key, string memory value, bool insertComma) private pure returns (string memory) { return string(abi.encodePacked('"', key, '": "', value, '"', insertComma ? ',' : '')); } function _pushJsonPrimitiveNonStringAttribute(string memory key, string memory value, bool insertComma) private pure returns (string memory) { return string(abi.encodePacked('"', key, '": ', value, insertComma ? ',' : '')); } function _pushJsonComplexAttribute(string memory key, string memory value, bool insertComma) private pure returns (string memory) { return string(abi.encodePacked('"', key, '": ', value, insertComma ? ',' : '')); } function _pushJsonArrayElement(string memory value, bool insertComma) private pure returns (string memory) { return string(abi.encodePacked(value, insertComma ? ',' : '')); } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } pragma solidity ^0.8.6; library Roots { // calculates a^(1/n) to dp decimal places // maxIts bounds the number of iterations performed function nthRoot(uint _a, uint _n, uint _dp, uint _maxIts) pure internal returns(uint) { assert (_n > 1); // The scale factor is a crude way to turn everything into integer calcs. // Actually do (a * (10 ^ ((dp + 1) * n))) ^ (1/n) // We calculate to one extra dp and round at the end uint one = 10 ** (1 + _dp); uint a0 = one ** _n * _a; // Initial guess: 1.0 uint xNew = one; uint iter = 0; while (iter < _maxIts) { uint x = xNew; uint t0 = x ** (_n - 1); if (x * t0 > a0) { xNew = x - (x - a0 / t0) / _n; } else { xNew = x + (a0 / t0 - x) / _n; } ++iter; if(xNew == x) { break; } } // Round to nearest in the last dp. return (xNew + 5) / 10; } } /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
* @dev Generate the NFTs of this collection. [20001000, 20000900, ] Requirements: - `values_` provided as a list of addresses, each of which implicitly corresponds to a tokenId, derrived by the index of the value in the input array. The values map to a color attribute. Emits a series of {Transfer} events./ for efficiency reasons copy from storage into local variables initialize accumulators and counters SKIP FLAG SET - DON'T MINT if the alpha was supplanted during minting, then return that new state to storage
function mint(uint256[] calldata values_) external onlyValidSender { require(!_mintingFinalized, "Merge: Minting is finalized."); uint256 index = _nextMintId; uint256 alphaId = _alphaId; uint256 alphaMass = _alphaMass; address omnibus = _omnibus; uint256 massAdded = 0; uint256 newlyMintedCount = 0; uint256 valueIx = 0; while (valueIx < values_.length) { if (isSentinelMass(values_[valueIx])) { newlyMintedCount++; _values[index] = values_[valueIx]; _owners[index] = omnibus; (/* uint256 class */, uint256 mass) = decodeClassAndMass(values_[valueIx]); if (alphaMass < mass){ alphaMass = mass; alphaId = index; } massAdded += mass; emit Transfer(address(0), omnibus, index); } index++; } _balances[omnibus] += newlyMintedCount; uint256 newMassTotal = prevMassTotal + massAdded; require(newMassTotal < MAX_MASS_EXCL, "Merge: Mass total overflow"); _massTotal = newMassTotal; if(_alphaId != alphaId) { _alphaId = alphaId; _alphaMass = alphaMass; emit AlphaMassUpdate(alphaId, alphaMass); } }
6,060,364
[ 1, 4625, 326, 423, 4464, 87, 434, 333, 1849, 18, 306, 6976, 1611, 3784, 16, 576, 2787, 29, 713, 16, 308, 29076, 30, 300, 1375, 2372, 67, 68, 2112, 487, 279, 666, 434, 6138, 16, 1517, 434, 2398, 1492, 24682, 13955, 358, 279, 1147, 548, 16, 2398, 302, 370, 2950, 635, 326, 770, 434, 326, 460, 316, 326, 2398, 810, 526, 18, 1021, 924, 852, 358, 279, 2036, 2398, 1566, 18, 7377, 1282, 279, 4166, 434, 288, 5912, 97, 2641, 18, 19, 364, 30325, 14000, 1610, 628, 2502, 1368, 1191, 3152, 4046, 8822, 3062, 471, 13199, 18420, 10972, 7855, 300, 463, 673, 11, 56, 490, 3217, 309, 326, 4190, 1703, 1169, 412, 970, 329, 4982, 312, 474, 310, 16, 1508, 327, 716, 394, 919, 358, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 312, 474, 12, 11890, 5034, 8526, 745, 892, 924, 67, 13, 3903, 1338, 1556, 12021, 288, 203, 3639, 2583, 12, 5, 67, 81, 474, 310, 7951, 1235, 16, 315, 6786, 30, 490, 474, 310, 353, 727, 1235, 1199, 1769, 540, 203, 540, 203, 3639, 2254, 5034, 770, 273, 389, 4285, 49, 474, 548, 31, 1171, 203, 3639, 2254, 5034, 4190, 548, 273, 389, 5429, 548, 31, 203, 3639, 2254, 5034, 4190, 18060, 273, 389, 5429, 18060, 31, 203, 3639, 1758, 8068, 82, 495, 407, 273, 389, 362, 82, 495, 407, 31, 203, 203, 3639, 2254, 5034, 8039, 8602, 273, 374, 31, 203, 3639, 2254, 5034, 10894, 49, 474, 329, 1380, 273, 374, 31, 203, 3639, 2254, 5034, 460, 45, 92, 273, 374, 31, 203, 203, 3639, 1323, 261, 1132, 45, 92, 411, 924, 27799, 2469, 13, 288, 2398, 203, 203, 5411, 309, 261, 291, 7828, 12927, 18060, 12, 2372, 67, 63, 1132, 45, 92, 22643, 288, 203, 7734, 10894, 49, 474, 329, 1380, 9904, 31, 203, 203, 7734, 389, 2372, 63, 1615, 65, 273, 924, 67, 63, 1132, 45, 92, 15533, 2398, 203, 7734, 389, 995, 414, 63, 1615, 65, 273, 8068, 82, 495, 407, 31, 203, 203, 7734, 261, 20308, 2254, 5034, 667, 1195, 16, 2254, 5034, 8039, 13, 273, 2495, 797, 1876, 18060, 12, 2372, 67, 63, 1132, 45, 92, 19226, 203, 203, 7734, 309, 261, 5429, 18060, 411, 8039, 15329, 203, 10792, 4190, 18060, 273, 8039, 31, 203, 10792, 4190, 548, 273, 770, 31, 203, 7734, 289, 203, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RoleAware.sol"; import "./Fund.sol"; import "./CrossMarginTrading.sol"; import "../libraries/IncentiveReporter.sol"; /** @title Here we support staking for MFI incentives as well as staking to perform the maintenance role. */ contract Admin is RoleAware { /// Margenswap (MFI) token address address public immutable MFI; mapping(address => uint256) public stakes; uint256 public totalStakes; uint256 public constant mfiStakeTranche = 1; uint256 public maintenanceStakePerBlock = 15 ether; mapping(address => address) public nextMaintenanceStaker; mapping(address => mapping(address => bool)) public maintenanceDelegateTo; address public currentMaintenanceStaker; address public prevMaintenanceStaker; uint256 public currentMaintenanceStakerStartBlock; address public immutable lockedMFI; constructor( address _MFI, address _lockedMFI, address lockedMFIDelegate, address _roles ) RoleAware(_roles) { MFI = _MFI; lockedMFI = _lockedMFI; // for initialization purposes and to ensure availability of service // the team's locked MFI participate in maintenance staking only // (not in the incentive staking part) // this implies some trust of the team to execute, which we deem reasonable // since the locked stake is temporary and diminishing as well as the fact // that the team is heavily invested in the protocol and incentivized // by fees like any other maintainer // furthermore others could step in to liquidate via the attacker route // and take away the team fees if they were delinquent nextMaintenanceStaker[_lockedMFI] = _lockedMFI; currentMaintenanceStaker = _lockedMFI; prevMaintenanceStaker = _lockedMFI; maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate]; currentMaintenanceStakerStartBlock = block.number; } /// Maintence stake setter function setMaintenanceStakePerBlock(uint256 amount) external onlyOwnerExec { maintenanceStakePerBlock = amount; } function _stake(address holder, uint256 amount) internal { Fund(fund()).depositFor(holder, MFI, amount); stakes[holder] += amount; totalStakes += amount; IncentiveReporter.addToClaimAmount(MFI, holder, amount); } /// Deposit a stake for sender function depositStake(uint256 amount) external { _stake(msg.sender, amount); } function _withdrawStake( address holder, uint256 amount, address recipient ) internal { // overflow failure desirable stakes[holder] -= amount; totalStakes -= amount; Fund(fund()).withdraw(MFI, recipient, amount); IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount); } /// Withdraw stake for sender function withdrawStake(uint256 amount) external { require( !isAuthorizedStaker(msg.sender), "You can't withdraw while you're authorized staker" ); _withdrawStake(msg.sender, amount, msg.sender); } /// Deposit maintenance stake function depositMaintenanceStake(uint256 amount) external { require( amount + stakes[msg.sender] >= maintenanceStakePerBlock, "Insufficient stake to call even one block" ); _stake(msg.sender, amount); if (nextMaintenanceStaker[msg.sender] == address(0)) { nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker(); nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender; } } function getMaintenanceStakerStake(address staker) public view returns (uint256) { if (staker == lockedMFI) { return IERC20(MFI).balanceOf(lockedMFI) / 2; } else { return stakes[staker]; } } function getUpdatedCurrentStaker() public returns (address) { uint256 currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if ( (block.number - currentMaintenanceStakerStartBlock) * maintenanceStakePerBlock >= currentStake ) { currentMaintenanceStakerStartBlock = block.number; prevMaintenanceStaker = currentMaintenanceStaker; currentMaintenanceStaker = nextMaintenanceStaker[ currentMaintenanceStaker ]; currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if (maintenanceStakePerBlock > currentStake) { // delete current from daisy chain address nextOne = nextMaintenanceStaker[currentMaintenanceStaker]; nextMaintenanceStaker[prevMaintenanceStaker] = nextOne; nextMaintenanceStaker[currentMaintenanceStaker] = address(0); currentMaintenanceStaker = nextOne; currentStake = getMaintenanceStakerStake( currentMaintenanceStaker ); } } return currentMaintenanceStaker; } function viewCurrentMaintenanceStaker() public view returns (address staker, uint256 startBlock) { staker = currentMaintenanceStaker; uint256 currentStake = getMaintenanceStakerStake(staker); startBlock = currentMaintenanceStakerStartBlock; if ( (block.number - startBlock) * maintenanceStakePerBlock >= currentStake ) { staker = nextMaintenanceStaker[staker]; currentStake = getMaintenanceStakerStake(staker); startBlock = block.number; if (maintenanceStakePerBlock > currentStake) { staker = nextMaintenanceStaker[staker]; } } } /// Add a delegate for staker function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; } /// Remove a delegate for staker function removeDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = false; } function isAuthorizedStaker(address caller) public returns (bool isAuthorized) { address currentStaker = getUpdatedCurrentStaker(); isAuthorized = currentStaker == caller || maintenanceDelegateTo[currentStaker][caller]; } /// Penalize a staker function penalizeMaintenanceStake( address maintainer, uint256 penalty, address recipient ) external returns (uint256 stakeTaken) { require( isStakePenalizer(msg.sender), "msg.sender not authorized to penalize stakers" ); if (penalty > stakes[maintainer]) { stakeTaken = stakes[maintainer]; } else { stakeTaken = penalty; } _withdrawStake(maintainer, stakeTaken, recipient); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; /// @title Base lending behavior abstract contract BaseLending { uint256 constant FP48 = 2**48; uint256 constant ACCUMULATOR_INIT = 10**18; uint256 constant hoursPerYear = 365 days / (1 hours); uint256 constant CHANGE_POINT = 79; uint256 public normalRatePerPercent = (FP48 * 15) / hoursPerYear / CHANGE_POINT / 100; uint256 public highRatePerPercent = (FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100; struct YieldAccumulator { uint256 accumulatorFP; uint256 lastUpdated; uint256 hourlyYieldFP; } struct LendingMetadata { uint256 totalLending; uint256 totalBorrowed; uint256 lendingCap; } mapping(address => LendingMetadata) public lendingMeta; /// @dev accumulate interest per issuer (like compound indices) mapping(address => YieldAccumulator) public borrowYieldAccumulators; /// @dev simple formula for calculating interest relative to accumulator function applyInterest( uint256 balance, uint256 accumulatorFP, uint256 yieldQuotientFP ) internal pure returns (uint256) { // 1 * FP / FP = 1 return (balance * accumulatorFP) / yieldQuotientFP; } function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing) internal view returns (uint256 rate) { rate = FP48; uint256 utilizationPercent = (100 * totalBorrowing) / totalLending; if (utilizationPercent < CHANGE_POINT) { rate += utilizationPercent * normalRatePerPercent; } else { rate += CHANGE_POINT * normalRatePerPercent + (utilizationPercent - CHANGE_POINT) * highRatePerPercent; } } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } /// @dev maximum function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a; } else { return b; } } /// Available tokens to this issuance function issuanceBalance(address issuance) internal view virtual returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "../libraries/UniswapStyleLib.sol"; abstract contract BaseRouter { modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Trade has expired"); _; } // **** SWAP **** /// @dev requires the initial amount to have already been sent to the first pair /// and for pairs to be vetted (which getAmountsIn / getAmountsOut do) function _swap( uint256[] memory amounts, address[] memory pairs, address[] memory tokens, address _to ) internal { for (uint256 i; i < pairs.length; i++) { (address input, address output) = (tokens[i], tokens[i + 1]); (address token0, ) = UniswapStyleLib.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < pairs.length - 1 ? pairs[i + 1] : _to; IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./PriceAware.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course struct CrossMarginAccount { uint256 lastDepositBlock; address[] borrowTokens; // borrowed token address => amount mapping(address => uint256) borrowed; // borrowed token => yield quotient mapping(address => uint256) borrowedYieldQuotientsFP; address[] holdingTokens; // token held in portfolio => amount mapping(address => uint256) holdings; // boolean value of whether an account holds a token mapping(address => bool) holdsToken; } abstract contract CrossMarginAccounts is RoleAware, PriceAware { /// @dev gets used in calculating how much accounts can borrow uint256 public leveragePercent = 300; /// @dev percentage of assets held per assets borrowed at which to liquidate uint256 public liquidationThresholdPercent = 115; /// @dev record of all cross margin accounts mapping(address => CrossMarginAccount) internal marginAccounts; /// @dev total token caps mapping(address => uint256) public tokenCaps; /// @dev tracks total of short positions per token mapping(address => uint256) public totalShort; /// @dev tracks total of long positions per token mapping(address => uint256) public totalLong; uint256 public coolingOffPeriod = 10; /// @dev add an asset to be held by account function addHolding( CrossMarginAccount storage account, address token, uint256 depositAmount ) internal { if (!hasHoldingToken(account, token)) { account.holdingTokens.push(token); account.holdsToken[token] = true; } account.holdings[token] += depositAmount; } /// @dev adjust account to reflect borrowing of token amount function borrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { if (!hasBorrowedToken(account, borrowToken)) { account.borrowTokens.push(borrowToken); account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending()) .getUpdatedBorrowYieldAccuFP(borrowToken); account.borrowed[borrowToken] = borrowAmount; } else { (uint256 oldBorrowed, uint256 accumulatorFP) = Lending(lending()).applyBorrowInterest( account.borrowed[borrowToken], borrowToken, account.borrowedYieldQuotientsFP[borrowToken] ); account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP; account.borrowed[borrowToken] = oldBorrowed + borrowAmount; } require(positiveBalance(account), "Insufficient balance"); } /// @dev checks whether account is in the black, deposit + earnings relative to borrowed function positiveBalance(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following condition should hold: // holdings / loan >= leveragePercent / (leveragePercent - 100) // => return holdings * (leveragePercent - 100) >= loan * leveragePercent; } /// @dev internal function adjusting holding and borrow balances when debt extinguished function extinguishDebt( CrossMarginAccount storage account, address debtToken, uint256 extinguishAmount ) internal { // will throw if insufficient funds (uint256 borrowAmount, uint256 newYieldQuot) = Lending(lending()).applyBorrowInterest( account.borrowed[debtToken], debtToken, account.borrowedYieldQuotientsFP[debtToken] ); uint256 newBorrowAmount = borrowAmount - extinguishAmount; account.borrowed[debtToken] = newBorrowAmount; if (newBorrowAmount > 0) { account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot; } else { delete account.borrowedYieldQuotientsFP[debtToken]; bool decrement = false; uint256 len = account.borrowTokens.length; for (uint256 i; len > i; i++) { address currToken = account.borrowTokens[i]; if (currToken == debtToken) { decrement = true; } else if (decrement) { account.borrowTokens[i - 1] = currToken; } } account.borrowTokens.pop(); } } /// @dev checks whether an account holds a token function hasHoldingToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.holdsToken[token]; } /// @dev checks whether an account has borrowed a token function hasBorrowedToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.borrowedYieldQuotientsFP[token] > 0; } /// @dev calculate total loan in reference currency, including compound interest function loanInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function holdingsInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPeg(account.holdingTokens, account.holdings); } /// @dev check whether an account can/should be liquidated function belowMaintenanceThreshold(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following should hold: // holdings / loan >= 1.1 // => holdings >= loan * 1.1 return 100 * holdings < liquidationThresholdPercent * loan; } /// @dev go through list of tokens and their amounts, summing up function sumTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and their amounts, summing up function viewTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and ammounts, summing up with interest function sumTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += yieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev go through list of tokens and ammounts, summing up with interest function viewTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += viewYieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev calculate yield for token amount and convert to reference currency function yieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.getCurrentPriceInPeg(token, amountInToken); } /// @dev calculate yield for token amount and convert to reference currency function viewYieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.viewCurrentPriceInPeg(token, amountInToken); } /// @dev move tokens from one holding to another function adjustAmounts( CrossMarginAccount storage account, address fromToken, address toToken, uint256 soldAmount, uint256 boughtAmount ) internal { account.holdings[fromToken] = account.holdings[fromToken] - soldAmount; addHolding(account, toToken, boughtAmount); } /// sets borrow and holding to zero function deleteAccount(CrossMarginAccount storage account) internal { uint256 len = account.borrowTokens.length; for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) { address borrowToken = account.borrowTokens[borrowIdx]; totalShort[borrowToken] -= account.borrowed[borrowToken]; account.borrowed[borrowToken] = 0; account.borrowedYieldQuotientsFP[borrowToken] = 0; } len = account.holdingTokens.length; for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) { address holdingToken = account.holdingTokens[holdingIdx]; totalLong[holdingToken] -= account.holdings[holdingToken]; account.holdings[holdingToken] = 0; account.holdsToken[holdingToken] = false; } delete account.borrowTokens; delete account.holdingTokens; } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./CrossMarginAccounts.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @title Handles liquidation of accounts below maintenance threshold @notice Liquidation can be called by the authorized staker, as determined in the Admin contract. If the authorized staker is delinquent, other participants can jump in and attack, taking their fees and potentially even their stake, depending how delinquent the responsible authorized staker is. */ abstract contract CrossMarginLiquidation is CrossMarginAccounts { event LiquidationShortfall(uint256 amount); event AccountLiquidated(address account); struct Liquidation { uint256 buy; uint256 sell; uint256 blockNum; } /// record kept around until a stake attacker can claim their reward struct AccountLiqRecord { uint256 blockNum; address loser; uint256 amount; address stakeAttacker; } mapping(address => Liquidation) liquidationAmounts; address[] internal liquidationTokens; address[] internal tradersToLiquidate; mapping(address => uint256) public maintenanceFailures; mapping(address => AccountLiqRecord) public stakeAttackRecords; uint256 public avgLiquidationPerCall = 10; uint256 public liqStakeAttackWindow = 5; uint256 public MAINTAINER_CUT_PERCENT = 5; uint256 public failureThreshold = 10; /// Set failure threshold function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec { failureThreshold = threshFactor; } /// Set liquidity stake attack window function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec { liqStakeAttackWindow = window; } /// Set maintainer's percent cut function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec { MAINTAINER_CUT_PERCENT = cut; } /// @dev calcLiquidationAmounts does a number of tasks in this contract /// and some of them are not straightforward. /// First of all it aggregates liquidation amounts, /// as well as which traders are ripe for liquidation, in storage (not in memory) /// owing to the fact that arrays can't be pushed to and hash maps don't /// exist in memory. /// Then it also returns any stake attack funds if the stake was unsuccessful /// (i.e. current caller is authorized). Also see context below. function calcLiquidationAmounts( address[] memory liquidationCandidates, bool isAuthorized ) internal returns (uint256 attackReturns) { liquidationTokens = new address[](0); tradersToLiquidate = new address[](0); for ( uint256 traderIndex = 0; liquidationCandidates.length > traderIndex; traderIndex++ ) { address traderAddress = liquidationCandidates[traderIndex]; CrossMarginAccount storage account = marginAccounts[traderAddress]; if (belowMaintenanceThreshold(account)) { tradersToLiquidate.push(traderAddress); uint256 len = account.holdingTokens.length; for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) { address token = account.holdingTokens[sellIdx]; Liquidation storage liquidation = liquidationAmounts[token]; if (liquidation.blockNum != block.number) { liquidation.sell = account.holdings[token]; liquidation.buy = 0; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.sell += account.holdings[token]; } } len = account.borrowTokens.length; for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) { address token = account.borrowTokens[buyIdx]; Liquidation storage liquidation = liquidationAmounts[token]; (uint256 loanAmount, ) = Lending(lending()).applyBorrowInterest( account.borrowed[token], token, account.borrowedYieldQuotientsFP[token] ); Lending(lending()).payOff(token, loanAmount); if (liquidation.blockNum != block.number) { liquidation.sell = 0; liquidation.buy = loanAmount; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.buy += loanAmount; } } } AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; if (isAuthorized) { attackReturns += _disburseLiqAttack(liqAttackRecord); } } } function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord) internal returns (uint256 returnAmount) { if (liqAttackRecord.amount > 0) { // validate attack records, if any uint256 blockDiff = min( block.number - liqAttackRecord.blockNum, liqStakeAttackWindow ); uint256 attackerCut = (liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow; Fund(fund()).withdraw( PriceAware.peg, liqAttackRecord.stakeAttacker, attackerCut ); Admin a = Admin(admin()); uint256 penalty = (a.maintenanceStakePerBlock() * attackerCut) / avgLiquidationPerCall; a.penalizeMaintenanceStake( liqAttackRecord.loser, penalty, liqAttackRecord.stakeAttacker ); // return remainder, after cut was taken to authorized stakekr returnAmount = liqAttackRecord.amount - attackerCut; } } /// Disburse liquidity stake attacks function disburseLiqStakeAttacks(address[] memory liquidatedAccounts) external { for (uint256 i = 0; liquidatedAccounts.length > i; i++) { address liqAccount = liquidatedAccounts[i]; AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[liqAccount]; if ( block.number > liqAttackRecord.blockNum + liqStakeAttackWindow ) { _disburseLiqAttack(liqAttackRecord); delete stakeAttackRecords[liqAccount]; } } } function liquidateFromPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) { address buyToken = liquidationTokens[tokenIdx]; Liquidation storage liq = liquidationAmounts[buyToken]; if (liq.buy > liq.sell) { pegAmount += PriceAware.liquidateFromPeg( buyToken, liq.buy - liq.sell ); delete liquidationAmounts[buyToken]; } } } function liquidateToPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) { address token = liquidationTokens[tokenIndex]; Liquidation storage liq = liquidationAmounts[token]; if (liq.sell > liq.buy) { uint256 sellAmount = liq.sell - liq.buy; pegAmount += PriceAware.liquidateToPeg(token, sellAmount); delete liquidationAmounts[token]; } } } function maintainerIsFailing() internal view returns (bool) { (address currentMaintainer, ) = Admin(admin()).viewCurrentMaintenanceStaker(); return maintenanceFailures[currentMaintainer] > failureThreshold * avgLiquidationPerCall; } /// called by maintenance stakers to liquidate accounts below liquidation threshold function liquidate(address[] memory liquidationCandidates) external noIntermediary returns (uint256 maintainerCut) { bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender); bool canTakeNow = isAuthorized || maintainerIsFailing(); // calcLiquidationAmounts does a lot of the work here // * aggregates both sell and buy side targets to be liquidated // * returns attacker cuts to them // * aggregates any returned fees from unauthorized (attacking) attempts maintainerCut = calcLiquidationAmounts( liquidationCandidates, isAuthorized ); uint256 sale2pegAmount = liquidateToPeg(); uint256 peg2targetCost = liquidateFromPeg(); delete liquidationTokens; // this may be a bit imprecise, since individual shortfalls may be obscured // by overall returns and the maintainer cut is taken out of the net total, // but it gives us the general picture uint256 costWithCut = (peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100; if (costWithCut > sale2pegAmount) { emit LiquidationShortfall(costWithCut - sale2pegAmount); canTakeNow = canTakeNow && IERC20(peg).balanceOf(fund()) > costWithCut; } address loser = address(0); if (!canTakeNow) { // whoever is the current responsible maintenance staker // and liable to lose their stake loser = Admin(admin()).getUpdatedCurrentStaker(); } // iterate over traders and send back their money // as well as giving attackers their due, in case caller isn't authorized for ( uint256 traderIdx = 0; tradersToLiquidate.length > traderIdx; traderIdx++ ) { address traderAddress = tradersToLiquidate[traderIdx]; CrossMarginAccount storage account = marginAccounts[traderAddress]; uint256 holdingsValue = holdingsInPeg(account); uint256 borrowValue = loanInPeg(account); // 5% of value borrowed uint256 maintainerCut4Account = (borrowValue * MAINTAINER_CUT_PERCENT) / 100; maintainerCut += maintainerCut4Account; if (!canTakeNow) { // This could theoretically lead to a previous attackers // record being overwritten, but only if the trader restarts // their account and goes back into the red within the short time window // which would be a costly attack requiring collusion without upside AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; liqAttackRecord.amount = maintainerCut4Account; liqAttackRecord.stakeAttacker = msg.sender; liqAttackRecord.blockNum = block.number; liqAttackRecord.loser = loser; } // send back trader money // include 1% for protocol uint256 forfeited = maintainerCut4Account + (borrowValue * 101) / 100; if (holdingsValue > forfeited) { // send remaining funds back to trader Fund(fund()).withdraw( PriceAware.peg, traderAddress, holdingsValue - forfeited ); } emit AccountLiquidated(traderAddress); deleteAccount(account); } avgLiquidationPerCall = (avgLiquidationPerCall * 99 + maintainerCut) / 100; if (canTakeNow) { Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut); } address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker(); if (isAuthorized) { if (maintenanceFailures[currentMaintainer] > maintainerCut) { maintenanceFailures[currentMaintainer] -= maintainerCut; } else { maintenanceFailures[currentMaintainer] = 0; } } else { maintenanceFailures[currentMaintainer] += maintainerCut; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./CrossMarginLiquidation.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading { constructor(address _peg, address _roles) RoleAware(_roles) PriceAware(_peg) {} /// @dev admin function to set the token cap function setTokenCap(address token, uint256 cap) external onlyOwnerExecActivator { tokenCaps[token] = cap; } /// @dev setter for cooling off period for withdrawing funds after deposit function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec { coolingOffPeriod = blocks; } /// @dev admin function to set leverage function setLeveragePercent(uint256 _leveragePercent) external onlyOwnerExec { leveragePercent = _leveragePercent; } /// @dev admin function to set liquidation threshold function setLiquidationThresholdPercent(uint256 threshold) external onlyOwnerExec { liquidationThresholdPercent = threshold; } /// @dev gets called by router to affirm a deposit to an account function registerDeposit( address trader, address token, uint256 depositAmount ) external override returns (uint256 extinguishableDebt) { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; account.lastDepositBlock = block.number; if (account.borrowed[token] > 0) { extinguishableDebt = min(depositAmount, account.borrowed[token]); extinguishDebt(account, token, extinguishableDebt); totalShort[token] -= extinguishableDebt; } // no overflow because depositAmount >= extinguishableDebt uint256 addedHolding = depositAmount - extinguishableDebt; _registerDeposit(account, token, addedHolding); } function _registerDeposit( CrossMarginAccount storage account, address token, uint256 addedHolding ) internal { addHolding(account, token, addedHolding); totalLong[token] += addedHolding; require( tokenCaps[token] >= totalLong[token], "Exceeds global token cap" ); } /// @dev gets called by router to affirm borrowing event function registerBorrow( address trader, address borrowToken, uint256 borrowAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; addHolding(account, borrowToken, borrowAmount); _registerBorrow(account, borrowToken, borrowAmount); } function _registerBorrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { totalShort[borrowToken] += borrowAmount; totalLong[borrowToken] += borrowAmount; require( tokenCaps[borrowToken] >= totalShort[borrowToken] && tokenCaps[borrowToken] >= totalLong[borrowToken], "Exceeds global token cap" ); borrow(account, borrowToken, borrowAmount); } /// @dev gets called by router to affirm withdrawal of tokens from account function registerWithdrawal( address trader, address withdrawToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerWithdrawal(account, withdrawToken, withdrawAmount); } function _registerWithdrawal( CrossMarginAccount storage account, address withdrawToken, uint256 withdrawAmount ) internal { require( block.number > account.lastDepositBlock + coolingOffPeriod, "No withdrawal soon after deposit" ); totalLong[withdrawToken] -= withdrawAmount; // throws on underflow account.holdings[withdrawToken] = account.holdings[withdrawToken] - withdrawAmount; require(positiveBalance(account), "Insufficient balance"); } /// @dev overcollateralized borrowing on a cross margin account, called by router function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerDeposit(account, depositToken, depositAmount); _registerBorrow(account, borrowToken, withdrawAmount); _registerWithdrawal(account, borrowToken, withdrawAmount); account.lastDepositBlock = block.number; } /// @dev gets called by router to register a trade and borrow and extinguish as necessary function registerTradeAndBorrow( address trader, address tokenFrom, address tokenTo, uint256 inAmount, uint256 outAmount ) external override returns (uint256 extinguishableDebt, uint256 borrowAmount) { require(isMarginTrader(msg.sender), "Calling contr. not an authorized"); CrossMarginAccount storage account = marginAccounts[trader]; if (account.borrowed[tokenTo] > 0) { extinguishableDebt = min(outAmount, account.borrowed[tokenTo]); extinguishDebt(account, tokenTo, extinguishableDebt); totalShort[tokenTo] -= extinguishableDebt; } uint256 sellAmount = inAmount; uint256 fromHoldings = account.holdings[tokenFrom]; if (inAmount > fromHoldings) { sellAmount = fromHoldings; /// won't overflow borrowAmount = inAmount - sellAmount; } if (inAmount > borrowAmount) { totalLong[tokenFrom] -= inAmount - borrowAmount; } if (outAmount > extinguishableDebt) { totalLong[tokenTo] += outAmount - extinguishableDebt; } require( tokenCaps[tokenTo] >= totalLong[tokenTo], "Exceeds global token cap" ); adjustAmounts( account, tokenFrom, tokenTo, sellAmount, outAmount - extinguishableDebt ); if (borrowAmount > 0) { totalShort[tokenFrom] += borrowAmount; require( tokenCaps[tokenFrom] >= totalShort[tokenFrom], "Exceeds global token cap" ); borrow(account, tokenFrom, borrowAmount); } } /// @dev can get called by router to register the dissolution of an account function registerLiquidation(address trader) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; require(loanInPeg(account) == 0, "Can't liquidate: borrowing"); deleteAccount(account); } /// @dev currently holding in this token function viewBalanceInToken(address trader, address token) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return account.holdings[token]; } /// @dev view function to display account held assets state function getHoldingAmounts(address trader) external view override returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ) { CrossMarginAccount storage account = marginAccounts[trader]; holdingTokens = account.holdingTokens; holdingAmounts = new uint256[](account.holdingTokens.length); for (uint256 idx = 0; holdingTokens.length > idx; idx++) { address tokenAddress = holdingTokens[idx]; holdingAmounts[idx] = account.holdings[tokenAddress]; } } /// @dev view function to display account borrowing state function getBorrowAmounts(address trader) external view override returns (address[] memory borrowTokens, uint256[] memory borrowAmounts) { CrossMarginAccount storage account = marginAccounts[trader]; borrowTokens = account.borrowTokens; borrowAmounts = new uint256[](account.borrowTokens.length); for (uint256 idx = 0; borrowTokens.length > idx; idx++) { address tokenAddress = borrowTokens[idx]; borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest( account.borrowed[tokenAddress], tokenAddress, account.borrowedYieldQuotientsFP[tokenAddress] ); } } /// @dev view function to get loan amount in peg function viewLoanInPeg(address trader) external view returns (uint256 amount) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function viewHoldingsInPeg(address trader) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPeg(account.holdingTokens, account.holdings); } /// @dev can this trader be liquidated? function canBeLiquidated(address trader) external view returns (bool) { CrossMarginAccount storage account = marginAccounts[trader]; uint256 loan = viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); uint256 holdings = viewTokensInPeg(account.holdingTokens, account.holdings); return liquidationThresholdPercent * loan >= 100 * holdings; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./RoleAware.sol"; /// @title Manage funding contract Fund is RoleAware { using SafeERC20 for IERC20; /// wrapped ether address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /// Deposit an active token function deposit(address depositToken, uint256 depositAmount) external { IERC20(depositToken).safeTransferFrom( msg.sender, address(this), depositAmount ); } /// Deposit token on behalf of `sender` function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); } /// Deposit to wrapped ether function depositToWETH() external payable { IWETH(WETH).deposit{value: msg.value}(); } // withdrawers role function withdraw( address withdrawalToken, address recipient, uint256 withdrawalAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount); } // withdrawers role function withdrawETH(address recipient, uint256 withdrawalAmount) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IWETH(WETH).withdraw(withdrawalAmount); Address.sendValue(payable(recipient), withdrawalAmount); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./BaseLending.sol"; struct HourlyBond { uint256 amount; uint256 yieldQuotientFP; uint256 moduloHour; } /// @title Here we offer subscriptions to auto-renewing hourly bonds /// Funds are locked in for an 50 minutes per hour, while interest rates float abstract contract HourlyBondSubscriptionLending is BaseLending { mapping(address => YieldAccumulator) hourlyBondYieldAccumulators; uint256 constant RATE_UPDATE_WINDOW = 10 minutes; uint256 public withdrawalWindow = 20 minutes; uint256 constant MAX_HOUR_UPDATE = 4; // issuer => holder => bond record mapping(address => mapping(address => HourlyBond)) public hourlyBondAccounts; uint256 public borrowingFactorPercent = 200; uint256 constant borrowMinAPR = 6; uint256 constant borrowMinHourlyYield = FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear; function _makeHourlyBond( address issuer, address holder, uint256 amount ) internal { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; updateHourlyBondAmount(issuer, bond); YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; bond.yieldQuotientFP = yieldAccumulator.accumulatorFP; if (bond.amount == 0) { bond.moduloHour = block.timestamp % (1 hours); } bond.amount += amount; lendingMeta[issuer].totalLending += amount; } function updateHourlyBondAmount(address issuer, HourlyBond storage bond) internal { uint256 yieldQuotientFP = bond.yieldQuotientFP; if (yieldQuotientFP > 0) { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); uint256 oldAmount = bond.amount; bond.amount = applyInterest( bond.amount, yA.accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = bond.amount - oldAmount; lendingMeta[issuer].totalLending += deltaAmount; } } // Retrieves bond balance for issuer and holder function viewHourlyBondAmount(address issuer, address holder) public view returns (uint256) { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; uint256 yieldQuotientFP = bond.yieldQuotientFP; uint256 cumulativeYield = viewCumulativeYieldFP( hourlyBondYieldAccumulators[issuer], block.timestamp ); if (yieldQuotientFP > 0) { return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP); } else { return bond.amount; } } function _withdrawHourlyBond( address issuer, HourlyBond storage bond, uint256 amount ) internal { // how far the current hour has advanced (relative to acccount hourly clock) uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours); require( withdrawalWindow >= currentOffset, "Tried withdrawing outside subscription cancellation time window" ); bond.amount -= amount; lendingMeta[issuer].totalLending -= amount; } function calcCumulativeYieldFP( YieldAccumulator storage yieldAccumulator, uint256 timeDelta ) internal view returns (uint256 accumulatorFP) { uint256 secondsDelta = timeDelta % (1 hours); // linearly interpolate interest for seconds // FP * FP * 1 / (FP * 1) = FP accumulatorFP = yieldAccumulator.accumulatorFP + (yieldAccumulator.accumulatorFP * (yieldAccumulator.hourlyYieldFP - FP48) * secondsDelta) / (FP48 * 1 hours); uint256 hoursDelta = timeDelta / (1 hours); if (hoursDelta > 0) { uint256 accumulatorBeforeFP = accumulatorFP; for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) { // FP48 * FP48 / FP48 = FP48 accumulatorFP = (accumulatorFP * yieldAccumulator.hourlyYieldFP) / FP48; } // a lot of time has passed if (hoursDelta > MAX_HOUR_UPDATE) { // apply interest in non-compounding way accumulatorFP += ((accumulatorFP - accumulatorBeforeFP) * (hoursDelta - MAX_HOUR_UPDATE)) / MAX_HOUR_UPDATE; } } } /// @dev updates yield accumulators for both borrowing and lending /// issuer address represents a token function updateHourlyYield(address issuer) public returns (uint256 hourlyYield) { return getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ) .hourlyYieldFP; } /// @dev updates yield accumulators for both borrowing and lending function getUpdatedHourlyYield( address issuer, YieldAccumulator storage accumulator, uint256 window ) internal returns (YieldAccumulator storage) { uint256 lastUpdated = accumulator.lastUpdated; uint256 timeDelta = (block.timestamp - lastUpdated); if (timeDelta > window) { YieldAccumulator storage borrowAccumulator = borrowYieldAccumulators[issuer]; accumulator.accumulatorFP = calcCumulativeYieldFP( accumulator, timeDelta ); LendingMetadata storage meta = lendingMeta[issuer]; accumulator.hourlyYieldFP = currentLendingRateFP( meta.totalLending, meta.totalBorrowed ); accumulator.lastUpdated = block.timestamp; updateBorrowYieldAccu(borrowAccumulator); borrowAccumulator.hourlyYieldFP = max( borrowMinHourlyYield, FP48 + (borrowingFactorPercent * (accumulator.hourlyYieldFP - FP48)) / 100 ); } return accumulator; } function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator) internal { uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated; if (timeDelta > RATE_UPDATE_WINDOW) { borrowAccumulator.accumulatorFP = calcCumulativeYieldFP( borrowAccumulator, timeDelta ); borrowAccumulator.lastUpdated = block.timestamp; } } function getUpdatedBorrowYieldAccuFP(address issuer) external returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); return yA.accumulatorFP; } function viewCumulativeYieldFP( YieldAccumulator storage yA, uint256 timestamp ) internal view returns (uint256) { uint256 timeDelta = (timestamp - yA.lastUpdated); if (timeDelta > RATE_UPDATE_WINDOW) { return calcCumulativeYieldFP(yA, timeDelta); } else { return yA.accumulatorFP; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "./HourlyBondSubscriptionLending.sol"; import "../libraries/IncentiveReporter.sol"; // TODO activate bonds for lending /// @title Manage lending for a variety of bond issuers contract Lending is RoleAware, HourlyBondSubscriptionLending { /// mapping issuers to tokens /// (in crossmargin, the issuers are tokens themselves) mapping(address => address) public issuerTokens; /// In case of shortfall, adjust debt mapping(address => uint256) public haircuts; /// map of available issuers mapping(address => bool) public activeIssuers; uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes; constructor(address _roles) RoleAware(_roles) {} /// Make a issuer available for protocol function activateIssuer(address issuer) external { activateIssuer(issuer, issuer); } /// Make issuer != token available for protocol (isol. margin) function activateIssuer(address issuer, address token) public onlyOwnerExecActivator { activeIssuers[issuer] = true; issuerTokens[issuer] = token; } /// Remove a issuer from trading availability function deactivateIssuer(address issuer) external onlyOwnerExecActivator { activeIssuers[issuer] = false; } /// Set lending cap function setLendingCap(address issuer, uint256 cap) external onlyOwnerExecActivator { lendingMeta[issuer].lendingCap = cap; } /// Set withdrawal window function setWithdrawalWindow(uint256 window) external onlyOwnerExec { withdrawalWindow = window; } function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec { normalRatePerPercent = rate; } function setHighRatePerPercent(uint256 rate) external onlyOwnerExec { highRatePerPercent = rate; } /// Set hourly yield APR for issuer function setHourlyYieldAPR(address issuer, uint256 aprPercent) external onlyOwnerExecActivator { YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; if (yieldAccumulator.accumulatorFP == 0) { uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365); hourlyBondYieldAccumulators[issuer] = YieldAccumulator({ accumulatorFP: FP48, lastUpdated: block.timestamp, hourlyYieldFP: yieldFP }); } else { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, yieldAccumulator, RATE_UPDATE_WINDOW ); yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365); } } /// @dev how much interest has accrued to a borrowed balance over time function applyBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) { require(isBorrower(msg.sender), "Not approved call"); YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); accumulatorFP = yA.accumulatorFP; balanceWithInterest = applyInterest( balance, accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = balanceWithInterest - balance; LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += deltaAmount; } /// @dev view function to get balance with borrowing interest applied function viewWithBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external view returns (uint256) { uint256 accumulatorFP = viewCumulativeYieldFP( borrowYieldAccumulators[issuer], block.timestamp ); return applyInterest(balance, accumulatorFP, yieldQuotientFP); } /// @dev gets called by router to register if a trader borrows issuers function registerBorrow(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], BORROW_RATE_UPDATE_WINDOW ); require( meta.totalLending >= meta.totalBorrowed, "Insufficient lending" ); } /// @dev gets called when external sources provide lending function registerLend(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called when external sources pay withdraw their bobnd function registerWithdrawal(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending -= amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called by router if loan is extinguished function payOff(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); lendingMeta[issuer].totalBorrowed -= amount; } /// @dev get the borrow yield for a specific issuer/token function viewAccumulatedBorrowingYieldFP(address issuer) external view returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; return viewCumulativeYieldFP(yA, block.timestamp); } function viewAPRPer10k(YieldAccumulator storage yA) internal view returns (uint256) { uint256 hourlyYieldFP = yA.hourlyYieldFP; uint256 aprFP = ((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours); return aprFP / FP48; } /// @dev get current borrowing interest per 10k for a token / issuer function viewBorrowAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(borrowYieldAccumulators[issuer]); } /// @dev get current lending APR per 10k for a token / issuer function viewHourlyBondAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]); } /// @dev In a liquidity crunch make a fallback bond until liquidity is good again function makeFallbackBond( address issuer, address holder, uint256 amount ) external { require(isLender(msg.sender), "Not an approved lender"); _makeHourlyBond(issuer, holder, amount); } /// @dev withdraw an hour bond function withdrawHourlyBond(address issuer, uint256 amount) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); super._withdrawHourlyBond(issuer, bond, amount); if (bond.amount == 0) { delete hourlyBondAccounts[issuer][msg.sender]; } disburse(issuer, msg.sender, amount); IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// Shut down hourly bond account for `issuer` function closeHourlyBondAccount(address issuer) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); uint256 amount = bond.amount; super._withdrawHourlyBond(issuer, bond, amount); disburse(issuer, msg.sender, amount); delete hourlyBondAccounts[issuer][msg.sender]; IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// @dev buy hourly bond subscription function buyHourlyBondSubscription(address issuer, uint256 amount) external { require(activeIssuers[issuer], "Not approved issuer"); collectToken(issuer, msg.sender, amount); super._makeHourlyBond(issuer, msg.sender, amount); IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount); } function initBorrowYieldAccumulator(address issuer) external onlyOwnerExecActivator { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; require(yA.accumulatorFP == 0, "don't re-initialize"); yA.accumulatorFP = FP48; yA.lastUpdated = block.timestamp; yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24); } function setBorrowingFactorPercent(uint256 borrowingFactor) external onlyOwnerExec { borrowingFactorPercent = borrowingFactor; } function issuanceBalance(address issuer) internal view override returns (uint256) { address token = issuerTokens[issuer]; if (token == issuer) { // cross margin return IERC20(token).balanceOf(fund()); } else { return lendingMeta[issuer].totalLending - haircuts[issuer]; } } function disburse( address issuer, address recipient, uint256 amount ) internal { uint256 haircutAmount = haircuts[issuer]; if (haircutAmount > 0 && amount > 0) { uint256 totalLending = lendingMeta[issuer].totalLending; uint256 adjustment = (amount * min(totalLending, haircutAmount)) / totalLending; amount = amount - adjustment; haircuts[issuer] -= adjustment; } address token = issuerTokens[issuer]; Fund(fund()).withdraw(token, recipient, amount); } function collectToken( address issuer, address source, uint256 amount ) internal { Fund(fund()).depositFor(source, issuer, amount); } function haircut(uint256 amount) external { haircuts[msg.sender] += amount; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "../interfaces/IMarginTrading.sol"; import "./Lending.sol"; import "./Admin.sol"; import "./BaseRouter.sol"; import "../libraries/IncentiveReporter.sol"; /// @title Top level transaction controller contract MarginRouter is RoleAware, BaseRouter { event AccountUpdated(address indexed trader); uint256 public constant mswapFeesPer10k = 10; address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /////////////////////////// // Cross margin endpoints /////////////////////////// /// @notice traders call this to deposit funds on cross margin function crossDeposit(address depositToken, uint256 depositAmount) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, depositToken, depositAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(depositToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( depositToken, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice deposit wrapped ehtereum into cross margin account function crossDepositETH() external payable { Fund(fund()).depositToWETH{value: msg.value}(); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, WETH, msg.value ); if (extinguishAmount > 0) { Lending(lending()).payOff(WETH, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( WETH, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice withdraw deposits/earnings from cross margin account function crossWithdraw(address withdrawToken, uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, withdrawToken, withdrawAmount ); Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice withdraw ethereum from cross margin account function crossWithdrawETH(uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, WETH, withdrawAmount ); Fund(fund()).withdrawETH(msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice borrow into cross margin trading account function crossBorrow(address borrowToken, uint256 borrowAmount) external { Lending(lending()).registerBorrow(borrowToken, borrowAmount); IMarginTrading(crossMarginTrading()).registerBorrow( msg.sender, borrowToken, borrowAmount ); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, borrowAmount ); emit AccountUpdated(msg.sender); } /// @notice convenience function to perform overcollateralized borrowing /// against a cross margin account. /// @dev caution: the account still has to have a positive balaance at the end /// of the withdraw. So an underwater account may not be able to withdraw function crossOvercollateralizedBorrow( address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); Lending(lending()).registerBorrow(borrowToken, withdrawAmount); IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow( msg.sender, depositToken, depositAmount, borrowToken, withdrawAmount ); Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, withdrawAmount ); emit AccountUpdated(msg.sender); } /// @notice close an account that is no longer borrowing and return gains function crossCloseAccount() external { (address[] memory holdingTokens, uint256[] memory holdingAmounts) = IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender); // requires all debts paid off IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender); for (uint256 i; holdingTokens.length > i; i++) { Fund(fund()).withdraw( holdingTokens[i], msg.sender, holdingAmounts[i] ); } emit AccountUpdated(msg.sender); } /// @notice entry point for swapping tokens held in cross margin account function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { // calc fees uint256 fees = takeFeesFromInput(amountIn); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn - fees, amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amountIn, amounts[amounts.length - 1] ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } /// @notice entry point for swapping tokens held in cross margin account function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut + takeFeesFromOutput(amountOut), amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amounts[0], amountOut ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } /// @dev helper function does all the work of telling other contracts /// about a cross margin trade function registerTrade( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) internal { (uint256 extinguishAmount, uint256 borrowAmount) = IMarginTrading(crossMarginTrading()).registerTradeAndBorrow( trader, inToken, outToken, inAmount, outAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(outToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( outToken, trader, extinguishAmount ); } if (borrowAmount > 0) { Lending(lending()).registerBorrow(inToken, borrowAmount); IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount); } emit AccountUpdated(trader); } ///////////// // Helpers ///////////// /// @dev internal helper swapping exact token for token on AMM function _fundSwapExactT4T( uint256[] memory amounts, uint256 amountOutMin, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[amounts.length - 1] >= amountOutMin, "MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } /// @notice make swaps on AMM using protocol funds, only for authorized contracts function authorizedSwapExactT4T( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } // @dev internal helper swapping exact token for token on on AMM function _fundSwapT4ExactT( uint256[] memory amounts, uint256 amountInMax, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[0] <= amountInMax, "MarginRouter: EXCESSIVE_INPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } //// @notice swap protocol funds on AMM, only for authorized function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } function takeFeesFromOutput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / 10_000; } function takeFeesFromInput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k); } function getAmountsOut( uint256 inAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens); } function getAmountsIn( uint256 outAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "./MarginRouter.sol"; import "../libraries/UniswapStyleLib.sol"; /// Stores how many of token you could get for 1k of peg struct TokenPrice { uint256 lastUpdated; uint256 priceFP; address[] liquidationTokens; bytes32 amms; address[] inverseLiquidationTokens; bytes32 inverseAmms; } struct VolatilitySetting { uint256 priceUpdateWindow; uint256 updateRatePermil; uint256 voluntaryUpdateWindow; } struct PairPrice { uint256 cumulative; uint256 lastUpdated; uint256 priceFP; } /// @title The protocol features several mechanisms to prevent vulnerability to /// price manipulation: /// 1) global exposure caps on all tokens which need to be raised gradually /// during the process of introducing a new token, making attacks unprofitable /// due to lack of scale /// 2) Exponential moving average with cautious price update. Prices for estimating /// how much a trader can borrow need not be extremely current and precise, mainly /// they must be resilient against extreme manipulation /// 3) Liquidators may not call from a contract address, to prevent extreme forms of /// of front-running and other price manipulation. abstract contract PriceAware is RoleAware { uint256 constant FP112 = 2**112; address public immutable peg; mapping(address => TokenPrice) public tokenPrices; mapping(address => mapping(address => PairPrice)) public pairPrices; /// update window in blocks // TODO uint256 public priceUpdateWindow = 20 minutes; uint256 public voluntaryUpdateWindow = 5 minutes; uint256 public UPDATE_RATE_PERMIL = 400; VolatilitySetting[] public volatilitySettings; constructor(address _peg) { peg = _peg; } /// Set window for price updates function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow) external onlyOwnerExec { priceUpdateWindow = window; voluntaryUpdateWindow = voluntaryWindow; } /// Add a new volatility setting function addVolatilitySetting( uint256 _priceUpdateWindow, uint256 _updateRatePermil, uint256 _voluntaryUpdateWindow ) external onlyOwnerExec { volatilitySettings.push( VolatilitySetting({ priceUpdateWindow: _priceUpdateWindow, updateRatePermil: _updateRatePermil, voluntaryUpdateWindow: _voluntaryUpdateWindow }) ); } /// Choose a volatitlity setting function chooseVolatilitySetting(uint256 index) external onlyOwnerExecDisabler { VolatilitySetting storage vs = volatilitySettings[index]; if (vs.updateRatePermil > 0) { UPDATE_RATE_PERMIL = vs.updateRatePermil; priceUpdateWindow = vs.priceUpdateWindow; voluntaryUpdateWindow = vs.voluntaryUpdateWindow; } } /// Set rate for updates function setUpdateRate(uint256 rate) external onlyOwnerExec { UPDATE_RATE_PERMIL = rate; } function getCurrentPriceInPeg(address token, uint256 inAmount) internal returns (uint256) { return getCurrentPriceInPeg(token, inAmount, false); } function getCurrentPriceInPeg( address token, uint256 inAmount, bool voluntary ) public returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated; if ( timeDelta > priceUpdateWindow || tokenPrice.priceFP == 0 || (voluntary && timeDelta > voluntaryUpdateWindow) ) { // update the currently cached price uint256 priceUpdateFP; priceUpdateFP = getPriceByPairs( tokenPrice.liquidationTokens, tokenPrice.amms ); _setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL); } priceInPeg = (inAmount * tokenPrice.priceFP) / FP112; } } /// Get view of current price of token in peg function viewCurrentPriceInPeg(address token, uint256 inAmount) public view returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 priceFP = tokenPrice.priceFP; priceInPeg = (inAmount * priceFP) / FP112; } } function _setPriceVal( TokenPrice storage tokenPrice, uint256 updateFP, uint256 weightPerMil ) internal { tokenPrice.priceFP = (tokenPrice.priceFP * (1000 - weightPerMil) + updateFP * weightPerMil) / 1000; tokenPrice.lastUpdated = block.timestamp; } /// add path from token to current liquidation peg function setLiquidationPath(bytes32 amms, address[] memory tokens) external onlyOwnerExecActivator { address token = tokens[0]; if (token != peg) { TokenPrice storage tokenPrice = tokenPrices[token]; tokenPrice.amms = amms; tokenPrice.liquidationTokens = tokens; tokenPrice.inverseLiquidationTokens = new address[](tokens.length); bytes32 inverseAmms; for (uint256 i = 0; tokens.length - 1 > i; i++) { initPairPrice(tokens[i], tokens[i + 1], amms[i]); bytes32 shifted = bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8); inverseAmms = inverseAmms | shifted; } tokenPrice.inverseAmms = inverseAmms; for (uint256 i = 0; tokens.length > i; i++) { tokenPrice.inverseLiquidationTokens[i] = tokens[ tokens.length - i - 1 ]; } tokenPrice.priceFP = getPriceByPairs(tokens, amms); tokenPrice.lastUpdated = block.timestamp; } } function liquidateToPeg(address token, uint256 amount) internal returns (uint256) { if (token == peg) { return amount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapExactT4T( amount, 0, tP.amms, tP.liquidationTokens ); uint256 outAmount = amounts[amounts.length - 1]; return outAmount; } } function liquidateFromPeg(address token, uint256 targetAmount) internal returns (uint256) { if (token == peg) { return targetAmount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapT4ExactT( targetAmount, type(uint256).max, tP.amms, tP.inverseLiquidationTokens ); return amounts[0]; } } function getPriceByPairs(address[] memory tokens, bytes32 amms) internal returns (uint256 priceFP) { priceFP = FP112; for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; (, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated; if (timeDelta > voluntaryUpdateWindow) { // we are in business (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); uint256 cumulative = inToken == token0 ? IUniswapV2Pair(pair).price0CumulativeLast() : IUniswapV2Pair(pair).price1CumulativeLast(); uint256 pairPriceFP = (cumulative - pairPrice.cumulative) / timeDelta; priceFP = (priceFP * pairPriceFP) / FP112; pairPrice.priceFP = pairPriceFP; pairPrice.cumulative = cumulative; pairPrice.lastUpdated = pairLastUpdated; } else { priceFP = (priceFP * pairPrice.priceFP) / FP112; } } } function initPairPrice( address inToken, address outToken, bytes1 amm ) internal { address pair = amm == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; if (pairPrice.lastUpdated == 0) { (uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); if (inToken == token0) { pairPrice.priceFP = (FP112 * reserve1) / reserve0; pairPrice.cumulative = IUniswapV2Pair(pair) .price0CumulativeLast(); } else { pairPrice.priceFP = (FP112 * reserve0) / reserve1; pairPrice.cumulative = IUniswapV2Pair(pair) .price1CumulativeLast(); } pairPrice.lastUpdated = block.timestamp; pairPrice.lastUpdated = pairLastUpdated; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Roles.sol"; /// @title Role management behavior /// Main characters are for service discovery /// Whereas roles are for access control contract RoleAware { Roles public immutable roles; mapping(uint256 => address) public mainCharacterCache; mapping(address => mapping(uint256 => bool)) public roleCache; constructor(address _roles) { require(_roles != address(0), "Please provide valid roles address"); roles = Roles(_roles); } modifier noIntermediary() { require( msg.sender == tx.origin, "Currently no intermediaries allowed for this function call" ); _; } // @dev Throws if called by any account other than the owner or executor modifier onlyOwnerExec() { require( owner() == msg.sender || executor() == msg.sender, "Roles: caller is not the owner" ); _; } modifier onlyOwnerExecDisabler() { require( owner() == msg.sender || executor() == msg.sender || disabler() == msg.sender, "Caller is not the owner, executor or authorized disabler" ); _; } modifier onlyOwnerExecActivator() { require( owner() == msg.sender || executor() == msg.sender || isTokenActivator(msg.sender), "Caller is not the owner, executor or authorized activator" ); _; } function updateRoleCache(uint256 role, address contr) public virtual { roleCache[contr][role] = roles.getRole(role, contr); } function updateMainCharacterCache(uint256 role) public virtual { mainCharacterCache[role] = roles.mainCharacters(role); } function owner() internal view returns (address) { return roles.owner(); } function executor() internal returns (address) { return roles.executor(); } function disabler() internal view returns (address) { return mainCharacterCache[DISABLER]; } function fund() internal view returns (address) { return mainCharacterCache[FUND]; } function lending() internal view returns (address) { return mainCharacterCache[LENDING]; } function marginRouter() internal view returns (address) { return mainCharacterCache[MARGIN_ROUTER]; } function crossMarginTrading() internal view returns (address) { return mainCharacterCache[CROSS_MARGIN_TRADING]; } function feeController() internal view returns (address) { return mainCharacterCache[FEE_CONTROLLER]; } function price() internal view returns (address) { return mainCharacterCache[PRICE_CONTROLLER]; } function admin() internal view returns (address) { return mainCharacterCache[ADMIN]; } function incentiveDistributor() internal view returns (address) { return mainCharacterCache[INCENTIVE_DISTRIBUTION]; } function tokenAdmin() internal view returns (address) { return mainCharacterCache[TOKEN_ADMIN]; } function isBorrower(address contr) internal view returns (bool) { return roleCache[contr][BORROWER]; } function isFundTransferer(address contr) internal view returns (bool) { return roleCache[contr][FUND_TRANSFERER]; } function isMarginTrader(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_TRADER]; } function isFeeSource(address contr) internal view returns (bool) { return roleCache[contr][FEE_SOURCE]; } function isMarginCaller(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_CALLER]; } function isLiquidator(address contr) internal view returns (bool) { return roleCache[contr][LIQUIDATOR]; } function isAuthorizedFundTrader(address contr) internal view returns (bool) { return roleCache[contr][AUTHORIZED_FUND_TRADER]; } function isIncentiveReporter(address contr) internal view returns (bool) { return roleCache[contr][INCENTIVE_REPORTER]; } function isTokenActivator(address contr) internal view returns (bool) { return roleCache[contr][TOKEN_ACTIVATOR]; } function isStakePenalizer(address contr) internal view returns (bool) { return roleCache[contr][STAKE_PENALIZER]; } function isLender(address contr) internal view returns (bool) { return roleCache[contr][LENDER]; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IDependencyController.sol"; // we chose not to go with an enum // to make this list easy to extend uint256 constant FUND_TRANSFERER = 1; uint256 constant MARGIN_CALLER = 2; uint256 constant BORROWER = 3; uint256 constant MARGIN_TRADER = 4; uint256 constant FEE_SOURCE = 5; uint256 constant LIQUIDATOR = 6; uint256 constant AUTHORIZED_FUND_TRADER = 7; uint256 constant INCENTIVE_REPORTER = 8; uint256 constant TOKEN_ACTIVATOR = 9; uint256 constant STAKE_PENALIZER = 10; uint256 constant LENDER = 11; uint256 constant FUND = 101; uint256 constant LENDING = 102; uint256 constant MARGIN_ROUTER = 103; uint256 constant CROSS_MARGIN_TRADING = 104; uint256 constant FEE_CONTROLLER = 105; uint256 constant PRICE_CONTROLLER = 106; uint256 constant ADMIN = 107; uint256 constant INCENTIVE_DISTRIBUTION = 108; uint256 constant TOKEN_ADMIN = 109; uint256 constant DISABLER = 1001; uint256 constant DEPENDENCY_CONTROLLER = 1002; /// @title Manage permissions of contracts and ownership of everything /// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during /// beta and will then be transfered to governance /// https://github.com/marginswap/governance contract Roles is Ownable { mapping(address => mapping(uint256 => bool)) public roles; mapping(uint256 => address) public mainCharacters; constructor() Ownable() { // token activation from the get-go roles[msg.sender][TOKEN_ACTIVATOR] = true; } /// @dev Throws if called by any account other than the owner. modifier onlyOwnerExecDepController() { require( owner() == msg.sender || executor() == msg.sender || mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender, "Roles: caller is not the owner" ); _; } function giveRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = true; } function removeRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = false; } function setMainCharacter(uint256 role, address actor) external onlyOwnerExecDepController { mainCharacters[role] = actor; } function getRole(uint256 role, address contr) external view returns (bool) { return roles[contr][role]; } /// @dev current executor function executor() public returns (address exec) { address depController = mainCharacters[DEPENDENCY_CONTROLLER]; if (depController != address(0)) { exec = IDependencyController(depController).currentExecutor(); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IDependencyController { function currentExecutor() external returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IMarginTrading { function registerDeposit( address trader, address token, uint256 amount ) external returns (uint256 extinguishAmount); function registerWithdrawal( address trader, address token, uint256 amount ) external; function registerBorrow( address trader, address token, uint256 amount ) external; function registerTradeAndBorrow( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) external returns (uint256 extinguishAmount, uint256 borrowAmount); function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external; function registerLiquidation(address trader) external; function getHoldingAmounts(address trader) external view returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ); function getBorrowAmounts(address trader) external view returns (address[] memory borrowTokens, uint256[] memory borrowAmounts); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } library IncentiveReporter { event AddToClaim(address topic, address indexed claimant, uint256 amount); event SubtractFromClaim( address topic, address indexed claimant, uint256 amount ); /// Start / increase amount of claim function addToClaimAmount( address topic, address recipient, uint256 claimAmount ) internal { emit AddToClaim(topic, recipient, claimAmount); } /// Decrease amount of claim function subtractFromClaimAmount( address topic, address recipient, uint256 subtractAmount ) internal { emit SubtractFromClaim(topic, recipient, subtractAmount); } } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; library UniswapStyleLib { address constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Identical address!"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Zero address!"); } // fetches and sorts the reserves for a pair function getReserves( address pair, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1_000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1_000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( uint256 amountIn, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[0] = amountIn; pairs = new address[](tokens.length - 1); for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( uint256 amountOut, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[amounts.length - 1] = amountOut; pairs = new address[](tokens.length - 1); for (uint256 i = tokens.length - 1; i > 0; i--) { address inToken = tokens[i - 1]; address outToken = tokens[i]; address pair = amms[i - 1] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i - 1] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } // calculates the CREATE2 address for a pair without making any external calls function pairForUni(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", UNISWAP_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } function pairForSushi(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", SUSHI_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } }
delete current from daisy chain
function getUpdatedCurrentStaker() public returns (address) { uint256 currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if ( (block.number - currentMaintenanceStakerStartBlock) * maintenanceStakePerBlock >= currentStake ) { currentMaintenanceStakerStartBlock = block.number; prevMaintenanceStaker = currentMaintenanceStaker; currentMaintenanceStaker = nextMaintenanceStaker[ currentMaintenanceStaker ]; currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if (maintenanceStakePerBlock > currentStake) { address nextOne = nextMaintenanceStaker[currentMaintenanceStaker]; nextMaintenanceStaker[prevMaintenanceStaker] = nextOne; nextMaintenanceStaker[currentMaintenanceStaker] = address(0); currentMaintenanceStaker = nextOne; currentStake = getMaintenanceStakerStake( currentMaintenanceStaker ); } } return currentMaintenanceStaker; }
563,717
[ 1, 3733, 783, 628, 5248, 291, 93, 2687, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 7381, 3935, 510, 6388, 1435, 1071, 1135, 261, 2867, 13, 288, 203, 3639, 2254, 5034, 783, 510, 911, 273, 203, 5411, 2108, 7770, 510, 6388, 510, 911, 12, 2972, 11045, 510, 6388, 1769, 203, 3639, 309, 261, 203, 5411, 261, 2629, 18, 2696, 300, 783, 11045, 510, 6388, 1685, 1768, 13, 380, 203, 7734, 18388, 510, 911, 2173, 1768, 1545, 203, 5411, 783, 510, 911, 203, 3639, 262, 288, 203, 5411, 783, 11045, 510, 6388, 1685, 1768, 273, 1203, 18, 2696, 31, 203, 203, 5411, 2807, 11045, 510, 6388, 273, 783, 11045, 510, 6388, 31, 203, 5411, 783, 11045, 510, 6388, 273, 1024, 11045, 510, 6388, 63, 203, 7734, 783, 11045, 510, 6388, 203, 5411, 308, 31, 203, 5411, 783, 510, 911, 273, 2108, 7770, 510, 6388, 510, 911, 12, 2972, 11045, 510, 6388, 1769, 203, 203, 5411, 309, 261, 29715, 510, 911, 2173, 1768, 405, 783, 510, 911, 13, 288, 203, 7734, 1758, 1024, 3335, 273, 203, 10792, 1024, 11045, 510, 6388, 63, 2972, 11045, 510, 6388, 15533, 203, 7734, 1024, 11045, 510, 6388, 63, 10001, 11045, 510, 6388, 65, 273, 1024, 3335, 31, 203, 7734, 1024, 11045, 510, 6388, 63, 2972, 11045, 510, 6388, 65, 273, 1758, 12, 20, 1769, 203, 203, 7734, 783, 11045, 510, 6388, 273, 1024, 3335, 31, 203, 7734, 783, 510, 911, 273, 2108, 7770, 510, 6388, 510, 911, 12, 203, 10792, 783, 11045, 510, 6388, 203, 7734, 11272, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 783, 11045, 510, 6388, 31, 203, 2 ]
pragma solidity 0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ 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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns(uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; assert(c >= a); return c; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint _tokenId) public; function balanceOf(address _owner) public view returns(uint balance); function implementsERC721() public pure returns(bool); function ownerOf(uint _tokenId) public view returns(address addr); function takeOwnership(uint _tokenId) public; function totalSupply() public view returns(uint total); function transferFrom(address _from, address _to, uint _tokenId) public; function transfer(address _to, uint _tokenId) public; //event Transfer(uint tokenId, address indexed from, address indexed to); event Approval(uint tokenId, address indexed owner, address indexed approved); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint tokenId); // function tokenMetadata(uint _tokenId) public view returns (string infoUrl); } contract CryptoCovfefes is ERC721 { /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoCovfefes"; string public constant SYMBOL = "Covfefe Token"; uint private constant startingPrice = 0.001 ether; uint private constant PROMO_CREATION_LIMIT = 5000; uint private constant CONTRACT_CREATION_LIMIT = 45000; uint private constant SaleCooldownTime = 12 hours; uint private randNonce = 0; uint private constant duelVictoryProbability = 51; uint private constant duelFee = .001 ether; uint private addMeaningFee = .001 ether; /*** EVENTS ***/ /// @dev The Creation event is fired whenever a new Covfefe comes into existence. event NewCovfefeCreated(uint tokenId, string term, string meaning, uint generation, address owner); /// @dev The Meaning added event is fired whenever a Covfefe is defined event CovfefeMeaningAdded(uint tokenId, string term, string meaning); /// @dev The CovfefeSold event is fired whenever a token is bought and sold. event CovfefeSold(uint tokenId, string term, string meaning, uint generation, uint sellingpPice, uint currentPrice, address buyer, address seller); /// @dev The Add Value To Covfefe event is fired whenever value is added to the Covfefe token event AddedValueToCovfefe(uint tokenId, string term, string meaning, uint generation, uint currentPrice); /// @dev The Transfer Covfefe event is fired whenever a Covfefe token is transferred event CovfefeTransferred(uint tokenId, address from, address to); /// @dev The ChallengerWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel event ChallengerWinsCovfefeDuel(uint tokenIdChallenger, string termChallenger, uint tokenIdDefender, string termDefender); /// @dev The DefenderWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel event DefenderWinsCovfefeDuel(uint tokenIdDefender, string termDefender, uint tokenIdChallenger, string termChallenger); /*** STORAGE ***/ /// @dev A mapping from covfefe IDs to the address that owns them. All covfefes have /// some valid owner address. mapping(uint => address) public covfefeIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping(address => uint) private ownershipTokenCount; /// @dev A mapping from CovfefeIDs to an address that has been approved to call /// transferFrom(). Each Covfefe can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping(uint => address) public covfefeIndexToApproved; // @dev A mapping from CovfefeIDs to the price of the token. mapping(uint => uint) private covfefeIndexToPrice; // @dev A mapping from CovfefeIDs to the price of the token. mapping(uint => uint) private covfefeIndexToLastPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public covmanAddress; address public covmanagerAddress; uint public promoCreatedCount; uint public contractCreatedCount; /*** DATATYPES ***/ struct Covfefe { string term; string meaning; uint16 generation; uint16 winCount; uint16 lossCount; uint64 saleReadyTime; } Covfefe[] private covfefes; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for Covman-only functionality modifier onlyCovman() { require(msg.sender == covmanAddress); _; } /// @dev Access modifier for Covmanager-only functionality modifier onlyCovmanager() { require(msg.sender == covmanagerAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCovDwellers() { require(msg.sender == covmanAddress || msg.sender == covmanagerAddress); _; } /*** CONSTRUCTOR ***/ function CryptoCovfefes() public { covmanAddress = msg.sender; covmanagerAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint _tokenId) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); covfefeIndexToApproved[_tokenId] = _to; emit Approval(_tokenId, msg.sender, _to); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns(uint balance) { return ownershipTokenCount[_owner]; } ///////////////////Create Covfefe/////////////////////////// /// @dev Creates a new promo Covfefe with the given term, with given _price and assignes it to an address. function createPromoCovfefe(address _owner, string _term, string _meaning, uint16 _generation, uint _price) public onlyCovmanager { require(promoCreatedCount < PROMO_CREATION_LIMIT); address covfefeOwner = _owner; if (covfefeOwner == address(0)) { covfefeOwner = covmanagerAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createCovfefe(_term, _meaning, _generation, covfefeOwner, _price); } /// @dev Creates a new Covfefe with the given term. function createContractCovfefe(string _term, string _meaning, uint16 _generation) public onlyCovmanager { require(contractCreatedCount < CONTRACT_CREATION_LIMIT); contractCreatedCount++; _createCovfefe(_term, _meaning, _generation, address(this), startingPrice); } function _triggerSaleCooldown(Covfefe storage _covfefe) internal { _covfefe.saleReadyTime = uint64(now + SaleCooldownTime); } function _ripeForSale(Covfefe storage _covfefe) internal view returns(bool) { return (_covfefe.saleReadyTime <= now); } /// @notice Returns all the relevant information about a specific covfefe. /// @param _tokenId The tokenId of the covfefe of interest. function getCovfefe(uint _tokenId) public view returns(string Term, string Meaning, uint Generation, uint ReadyTime, uint WinCount, uint LossCount, uint CurrentPrice, uint LastPrice, address Owner) { Covfefe storage covfefe = covfefes[_tokenId]; Term = covfefe.term; Meaning = covfefe.meaning; Generation = covfefe.generation; ReadyTime = covfefe.saleReadyTime; WinCount = covfefe.winCount; LossCount = covfefe.lossCount; CurrentPrice = covfefeIndexToPrice[_tokenId]; LastPrice = covfefeIndexToLastPrice[_tokenId]; Owner = covfefeIndexToOwner[_tokenId]; } function implementsERC721() public pure returns(bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns(string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint _tokenId) public view returns(address owner) { owner = covfefeIndexToOwner[_tokenId]; require(owner != address(0)); } modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == covfefeIndexToOwner[_tokenId]); _; } ///////////////////Add Meaning ///////////////////// function addMeaningToCovfefe(uint _tokenId, string _newMeaning) external payable onlyOwnerOf(_tokenId) { /// Making sure the transaction is not from another smart contract require(!isContract(msg.sender)); /// Making sure the addMeaningFee is included require(msg.value == addMeaningFee); /// Add the new meaning covfefes[_tokenId].meaning = _newMeaning; /// Emit the term meaning added event. emit CovfefeMeaningAdded(_tokenId, covfefes[_tokenId].term, _newMeaning); } function payout(address _to) public onlyCovDwellers { _payout(_to); } /////////////////Buy Token //////////////////// // Allows someone to send ether and obtain the token function buyCovfefe(uint _tokenId) public payable { address oldOwner = covfefeIndexToOwner[_tokenId]; address newOwner = msg.sender; // Making sure sale cooldown is not in effect Covfefe storage myCovfefe = covfefes[_tokenId]; require(_ripeForSale(myCovfefe)); // Making sure the transaction is not from another smart contract require(!isContract(msg.sender)); covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId]; uint sellingPrice = covfefeIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint payment = uint(SafeMath.div(SafeMath.mul(sellingPrice, 95), 100)); uint purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices covfefeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 95); _transfer(oldOwner, newOwner, _tokenId); ///Trigger Sale cooldown _triggerSaleCooldown(myCovfefe); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.05) } emit CovfefeSold(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToLastPrice[_tokenId], covfefeIndexToPrice[_tokenId], newOwner, oldOwner); msg.sender.transfer(purchaseExcess); } function priceOf(uint _tokenId) public view returns(uint price) { return covfefeIndexToPrice[_tokenId]; } function lastPriceOf(uint _tokenId) public view returns(uint price) { return covfefeIndexToLastPrice[_tokenId]; } /// @dev Assigns a new address to act as the Covman. Only available to the current Covman /// @param _newCovman The address of the new Covman function setCovman(address _newCovman) public onlyCovman { require(_newCovman != address(0)); covmanAddress = _newCovman; } /// @dev Assigns a new address to act as the Covmanager. Only available to the current Covman /// @param _newCovmanager The address of the new Covmanager function setCovmanager(address _newCovmanager) public onlyCovman { require(_newCovmanager != address(0)); covmanagerAddress = _newCovmanager; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns(string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint _tokenId) public { address newOwner = msg.sender; address oldOwner = covfefeIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } ///////////////////Add Value to Covfefe///////////////////////////// //////////////There's no fee for adding value////////////////////// function addValueToCovfefe(uint _tokenId) external payable onlyOwnerOf(_tokenId) { // Making sure the transaction is not from another smart contract require(!isContract(msg.sender)); //Making sure amount is within the min and max range require(msg.value >= 0.001 ether); require(msg.value <= 9999.000 ether); //Keeping a record of lastprice before updating price covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId]; uint newValue = msg.value; // Update prices newValue = SafeMath.div(SafeMath.mul(newValue, 115), 100); covfefeIndexToPrice[_tokenId] = SafeMath.add(newValue, covfefeIndexToPrice[_tokenId]); ///Emit the AddValueToCovfefe event emit AddedValueToCovfefe(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToPrice[_tokenId]); } /// @param _owner The owner whose covfefe tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Covfefes array looking for covfefes belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function getTokensOfOwner(address _owner) external view returns(uint[] ownerTokens) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint[](0); } else { uint[] memory result = new uint[](tokenCount); uint totalCovfefes = totalSupply(); uint resultIndex = 0; uint covfefeId; for (covfefeId = 0; covfefeId <= totalCovfefes; covfefeId++) { if (covfefeIndexToOwner[covfefeId] == _owner) { result[resultIndex] = covfefeId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns(uint total) { return covfefes.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint _tokenId) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint _tokenId) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns(bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint _tokenId) private view returns(bool) { return covfefeIndexToApproved[_tokenId] == _to; } /////////////Covfefe Creation//////////// function _createCovfefe(string _term, string _meaning, uint16 _generation, address _owner, uint _price) private { Covfefe memory _covfefe = Covfefe({ term: _term, meaning: _meaning, generation: _generation, saleReadyTime: uint64(now), winCount: 0, lossCount: 0 }); uint newCovfefeId = covfefes.push(_covfefe) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newCovfefeId == uint(uint32(newCovfefeId))); //Emit the Covfefe creation event emit NewCovfefeCreated(newCovfefeId, _term, _meaning, _generation, _owner); covfefeIndexToPrice[newCovfefeId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newCovfefeId); } /// Check for token ownership function _owns(address claimant, uint _tokenId) private view returns(bool) { return claimant == covfefeIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { covmanAddress.transfer(address(this).balance); } else { _to.transfer(address(this).balance); } } /////////////////////Transfer////////////////////// /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. /// @dev Assigns ownership of a specific Covfefe to an address. function _transfer(address _from, address _to, uint _tokenId) private { // Since the number of covfefes is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership covfefeIndexToOwner[_tokenId] = _to; // When creating new covfefes _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete covfefeIndexToApproved[_tokenId]; } // Emit the transfer event. emit CovfefeTransferred(_tokenId, _from, _to); } ///////////////////Covfefe Duel System////////////////////// //Simple Randomizer for the covfefe duelling system function randMod(uint _modulus) internal returns(uint) { randNonce++; return uint(keccak256(now, msg.sender, randNonce)) % _modulus; } function duelAnotherCovfefe(uint _tokenId, uint _targetId) external payable onlyOwnerOf(_tokenId) { //Load the covfefes from storage Covfefe storage myCovfefe = covfefes[_tokenId]; // Making sure the transaction is not from another smart contract require(!isContract(msg.sender)); //Making sure the duelling fee is included require(msg.value == duelFee); // Covfefe storage enemyCovfefe = covfefes[_targetId]; uint rand = randMod(100); if (rand <= duelVictoryProbability) { myCovfefe.winCount++; enemyCovfefe.lossCount++; ///Emit the ChallengerWins event emit ChallengerWinsCovfefeDuel(_tokenId, covfefes[_tokenId].term, _targetId, covfefes[_targetId].term); } else { myCovfefe.lossCount++; enemyCovfefe.winCount++; ///Emit the DefenderWins event emit DefenderWinsCovfefeDuel(_targetId, covfefes[_targetId].term, _tokenId, covfefes[_tokenId].term); } } ////////////////// Utility ////////////////// function isContract(address addr) internal view returns(bool) { uint size; assembly { size: = extcodesize(addr) } return size > 0; } }
* @dev Integer division of two numbers, truncating the quotient./ 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
function div(uint a, uint b) internal pure returns(uint) { return a / b; }
5,488,636
[ 1, 4522, 16536, 434, 2795, 5600, 16, 6956, 1776, 326, 26708, 18, 19, 1815, 12, 70, 405, 374, 1769, 225, 348, 7953, 560, 6635, 1216, 1347, 3739, 10415, 635, 374, 2254, 276, 273, 279, 342, 324, 31, 1815, 12, 69, 422, 324, 225, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 3302, 1404, 6887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 12, 11890, 13, 288, 203, 3639, 327, 279, 342, 324, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.21; // File: contracts/BytesDeserializer.sol /* * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /* * Deserialize bytes payloads. * * Values are in big-endian byte order. * */ library BytesDeserializer { /* * Extract 256-bit worth of data from the bytes stream. */ function slice32(bytes b, uint offset) public pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract Ethereum address worth of data from the bytes stream. */ function sliceAddress(bytes b, uint offset) public pure returns (address) { bytes32 out; for (uint i = 0; i < 20; i++) { out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8); } return address(uint(out)); } /* * Extract 128-bit worth of data from the bytes stream. */ function slice16(bytes b, uint offset) public pure returns (bytes16) { bytes16 out; for (uint i = 0; i < 16; i++) { out |= bytes16(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract 32-bit worth of data from the bytes stream. */ function slice4(bytes b, uint offset) public pure returns (bytes4) { bytes4 out; for (uint i = 0; i < 4; i++) { out |= bytes4(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract 16-bit worth of data from the bytes stream. */ function slice2(bytes b, uint offset) public pure returns (bytes2) { bytes2 out; for (uint i = 0; i < 2; i++) { out |= bytes2(b[offset + i] & 0xFF) >> (i * 8); } return out; } } // File: contracts/KYCPayloadDeserializer.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * A mix-in contract to decode AML payloads. * * @notice This should be a library, but for the complexity and toolchain fragility risks involving of linking library inside library, we put this as a mix-in. */ contract KYCPayloadDeserializer { using BytesDeserializer for bytes; /** * This function takes the dataframe and unpacks it * We have the users ETH address for verification that they are using their own signature * CustomerID so we can track customer purchases * Min/Max ETH to invest for AML/CTF purposes - this can be supplied by the user OR by the back-end. */ function getKYCPayload(bytes dataframe) public pure returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); return (_whitelistedAddress, _customerId, _minETH, _maxETH); } } // File: contracts/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ReleasableToken.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * * Some of this code has been updated by Pickeringware ltd to faciliatte the new solidity compilation requirements */ pragma solidity 0.4.21; /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardToken, 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) { if(!transferAgents[_sender]) { revert(); } } _; } /** * 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() onlyOwner inReleaseState(false) public { // We don&#39;t do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = owner; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyReleaseAgent 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) { if(releaseState != released) { revert(); } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { revert(); } _; } function transfer(address _to, uint _value) canTransfer(msg.sender) public returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) public returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } // File: contracts/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol * * Some of this code has been changed by Pickeringware ltd to facilitate solidities new compilation requirements */ contract MintableToken is ReleasableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/AMLToken.sol /** * This contract has been written by Pickeringware ltd in some areas to facilitate custom crwodsale features */ pragma solidity 0.4.21; /** * The AML Token * * This subset of MintableCrowdsaleToken gives the Owner a possibility to * reclaim tokens from a participant before the token is released * after a participant has failed a prolonged AML process. * * It is assumed that the anti-money laundering process depends on blockchain data. * The data is not available before the transaction and not for the smart contract. * Thus, we need to implement logic to handle AML failure cases post payment. * We give a time window before the token release for the token sale owners to * complete the AML and claw back all token transactions that were * caused by rejected purchases. */ contract AMLToken is MintableToken { // An event when the owner has reclaimed non-released tokens event ReclaimedAllAndBurned(address claimedBy, address fromWhom, uint amount); // An event when the owner has reclaimed non-released tokens event ReclaimAndBurned(address claimedBy, address fromWhom, uint amount); /// @dev Here the owner can reclaim the tokens from a participant if /// the token is not released yet. Refund will be handled in sale contract. /// We also burn the tokens in the interest of economic value to the token holder /// @param fromWhom address of the participant whose tokens we want to claim function reclaimAllAndBurn(address fromWhom) public onlyReleaseAgent inReleaseState(false) { uint amount = balanceOf(fromWhom); balances[fromWhom] = 0; totalSupply = totalSupply.sub(amount); ReclaimedAllAndBurned(msg.sender, fromWhom, amount); } /// @dev Here the owner can reclaim the tokens from a participant if /// the token is not released yet. Refund will be handled in sale contract. /// We also burn the tokens in the interest of economic value to the token holder /// @param fromWhom address of the participant whose tokens we want to claim function reclaimAndBurn(address fromWhom, uint256 amount) public onlyReleaseAgent inReleaseState(false) { balances[fromWhom] = balances[fromWhom].sub(amount); totalSupply = totalSupply.sub(amount); ReclaimAndBurned(msg.sender, fromWhom, amount); } } // File: contracts/PickToken.sol /* * This token is part of Pickeringware ltds smart contracts * It is used to specify certain details about the token upon release */ contract PickToken is AMLToken { string public name = "AX1 Mining token"; string public symbol = "AX1"; uint8 public decimals = 5; } // File: contracts/Stoppable.sol contract Stoppable is Ownable { bool public halted; event SaleStopped(address owner, uint256 datetime); modifier stopInEmergency { require(!halted); _; } function hasHalted() internal view returns (bool isHalted) { return halted; } // called by the owner on emergency, triggers stopped state function stopICO() external onlyOwner { halted = true; SaleStopped(msg.sender, now); } } // File: contracts/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. * * This base contract has been changed in certain areas by Pickeringware ltd to facilitate extra functionality */ contract Crowdsale is Stoppable { using SafeMath for uint256; // The token being sold PickToken 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; address public contractAddr; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; uint256 public presaleWeiRaised; // amount of tokens sent uint256 public tokensSent; // These store balances of participants by ID, address and in wei, pre-sale wei and tokens mapping(uint128 => uint256) public balancePerID; mapping(address => uint256) public balanceOf; mapping(address => uint256) public presaleBalanceOf; mapping(address => uint256) public tokenBalanceOf; /** * 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, uint256 datetime); /* * Contructor * This initialises the basic crowdsale data * It transfers ownership of this token to the chosen beneficiary */ function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, PickToken _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = _token; startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; transferOwnership(_wallet); } /* * This method has been changed by Pickeringware ltd * We have split this method down into overidable functions which may affect how users purchase tokens * We also take in a customerID (UUiD v4) which we store in our back-end in order to track users participation */ function buyTokens(uint128 buyer) internal stopInEmergency { require(buyer != 0); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = tokensToRecieve(weiAmount); // MUST DO REQUIRE AFTER tokens are calculated to check for cap restrictions in stages require(validPurchase(tokens)); // We move the participants sliders before we mint the tokens to prevent re-entrancy finalizeSale(weiAmount, tokens, buyer); produceTokens(msg.sender, weiAmount, tokens); } // This function was created to be overridden by a parent contract function produceTokens(address buyer, uint256 weiAmount, uint256 tokens) internal { token.mint(buyer, tokens); TokenPurchase(msg.sender, buyer, weiAmount, tokens, now); } // This was created to be overriden by stages implementation // It will adjust the stage sliders accordingly if needed function finalizeSale(uint256 _weiAmount, uint256 _tokens, uint128 _buyer) internal { // Collect ETH and send them a token in return balanceOf[msg.sender] = balanceOf[msg.sender].add(_weiAmount); tokenBalanceOf[msg.sender] = tokenBalanceOf[msg.sender].add(_tokens); balancePerID[_buyer] = balancePerID[_buyer].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); tokensSent = tokensSent.add(_tokens); } // This was created to be overridden by the stages implementation // Again, this is dependent on the price of tokens which may or may not be collected in stages function tokensToRecieve(uint256 _wei) internal view returns (uint256 tokens) { return _wei.div(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function successfulWithdraw() external onlyOwner stopInEmergency { require(hasEnded()); owner.transfer(weiRaised); } // @return true if the transaction can buy tokens // Receives tokens to send as variable for custom stage implementation // Has an unused variable _tokens which is necessary for capped sale implementation function validPurchase(uint256 _tokens) internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public softCap; uint256 public hardCap; uint256 public withdrawn; bool public canWithdraw; address public beneficiary; event BeneficiaryWithdrawal(address admin, uint256 amount, uint256 datetime); // Changed implentation to include soft/hard caps function CappedCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, uint256 _softCap, uint256 _hardCap, PickToken _token) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) public { require(_hardCap > 0 && _softCap > 0 && _softCap < _hardCap); softCap = _softCap; hardCap = _hardCap; withdrawn = 0; canWithdraw = false; beneficiary = _beneficiary; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool withinCap = tokensSent.add(_tokens) <= hardCap; return super.validPurchase(_tokens) && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = tokensSent >= hardCap; return super.hasEnded() || capReached; } // overriding Crowdsale#successfulWithdraw to add cap logic // only allow beneficiary to withdraw if softcap has been reached // Uses withdrawn incase a parent contract requires withdrawing softcap early function successfulWithdraw() external onlyOwner stopInEmergency { require(hasEnded()); // This is used for extra functionality if necessary, i.e. KYC checks require(canWithdraw); require(tokensSent > softCap); uint256 withdrawalAmount = weiRaised.sub(withdrawn); withdrawn = withdrawn.add(withdrawalAmount); beneficiary.transfer(withdrawalAmount); BeneficiaryWithdrawal(msg.sender, withdrawalAmount, now); } } // File: contracts/SaleStagesLib.sol /* * SaleStagesLib is a part of Pickeringware ltd&#39;s smart contracts * Its intended use is to abstract the implementation of stages away from a contract to ease deployment and codel length * It uses a stage struct to store specific details about each stage * It has several functions which are used to get/change this data */ library SaleStagesLib { using SafeMath for uint256; // Stores Stage implementation struct Stage{ uint256 deadline; uint256 tokenPrice; uint256 tokensSold; uint256 minimumBuy; uint256 cap; } // The struct that is stored by the contract // Contains counter to iterate through map of stages struct StageStorage { mapping(uint8 => Stage) stages; uint8 stageCount; } // Initiliase the stagecount to 0 function init(StageStorage storage self) public { self.stageCount = 0; } // Create stage adds new stage to stages map and increments stage count function createStage( StageStorage storage self, uint8 _stage, uint256 _deadline, uint256 _price, uint256 _minimum, uint256 _cap ) internal { // Ensures stages cannot overlap each other uint8 prevStage = _stage - 1; require(self.stages[prevStage].deadline < _deadline); self.stages[_stage].deadline = _deadline; self.stages[_stage].tokenPrice = _price; self.stages[_stage].tokensSold = 0; self.stages[_stage].minimumBuy = _minimum; self.stages[_stage].cap = _cap; self.stageCount = self.stageCount + 1; } /* * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. * Each one of these conditions checks if the time has passed into another stage and therefore, act as appropriate */ function getStage(StageStorage storage self) public view returns (uint8 stage) { uint8 thisStage = self.stageCount + 1; for (uint8 i = 0; i < thisStage; i++) { if(now <= self.stages[i].deadline){ return i; } } return thisStage; } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function checkMinimum(StageStorage storage self, uint8 _stage, uint256 _tokens) internal view returns (bool isValid) { if(_tokens < self.stages[_stage].minimumBuy){ return false; } else { return true; } } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function changeDeadline(StageStorage storage self, uint8 _stage, uint256 _deadline) internal { require(self.stages[_stage].deadline > now); self.stages[_stage].deadline = _deadline; } // Checks to see if the tokens they&#39;re about to purchase is below the cap for this stage function checkCap(StageStorage storage self, uint8 _stage, uint256 _tokens) internal view returns (bool isValid) { uint256 totalTokens = self.stages[_stage].tokensSold.add(_tokens); if(totalTokens > self.stages[_stage].cap){ return false; } else { return true; } } // Refund a particular participant, by moving the sliders of stages he participated in function refundParticipant(StageStorage storage self, uint256 stage1, uint256 stage2, uint256 stage3, uint256 stage4) internal { self.stages[1].tokensSold = self.stages[1].tokensSold.sub(stage1); self.stages[2].tokensSold = self.stages[2].tokensSold.sub(stage2); self.stages[3].tokensSold = self.stages[3].tokensSold.sub(stage3); self.stages[4].tokensSold = self.stages[4].tokensSold.sub(stage4); } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function changePrice(StageStorage storage self, uint8 _stage, uint256 _tokenPrice) internal { require(self.stages[_stage].deadline > now); self.stages[_stage].tokenPrice = _tokenPrice; } } // File: contracts/PickCrowdsale.sol /* * PickCrowdsale and PickToken are a part of Pickeringware ltd&#39;s smart contracts * This uses the SaleStageLib which is also a part of Pickeringware ltd&#39;s smart contracts * We create the stages initially in the constructor such that stages cannot be added after the sale has started * We then pre-allocate necessary accounts prior to the sale starting * This contract implements the stages lib functionality with overriding functions for stages implementation */ contract PickCrowdsale is CappedCrowdsale { using SaleStagesLib for SaleStagesLib.StageStorage; using SafeMath for uint256; SaleStagesLib.StageStorage public stages; bool preallocated = false; bool stagesSet = false; address private founders; address private bounty; address private buyer; uint256 public burntBounty; uint256 public burntFounder; event ParticipantWithdrawal(address participant, uint256 amount, uint256 datetime); event StagePriceChanged(address admin, uint8 stage, uint256 price); event ExtendedStart(uint256 oldStart, uint256 newStart); modifier onlyOnce(bool _check) { if(_check) { revert(); } _; } function PickCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, address _buyer, address _founders, address _bounty, uint256 _softCap, uint256 _hardCap, PickToken _token) CappedCrowdsale(_startTime, _endTime, _rate, _wallet, _beneficiary, _softCap, _hardCap, _token) public { stages.init(); stages.createStage(0, _startTime, 0, 0, 0); founders = _founders; bounty = _bounty; buyer = _buyer; } function setPreallocations() external onlyOwner onlyOnce(preallocated) { preallocate(buyer, 1250000, 10000000000); preallocate(founders, 1777777, 0); preallocate(bounty, 444445, 0); preallocated = true; } function setStages() external onlyOwner onlyOnce(stagesSet) { stages.createStage(1, startTime.add(1 weeks), 10000000000, 10000000, 175000000000); //Deadline 1 day (86400) after start - price: 0.001 - min: 90 - cap: 1,250,000 stages.createStage(2, startTime.add(2 weeks), 11000000000, 5000000, 300000000000); //Deadline 2 days (172800) after start - price: 0.0011 - min: 60 - cap: 3,000,000 stages.createStage(3, startTime.add(4 weeks), 12000000000, 2500000, 575000000000); //Deadline 4 days (345600) after start - price: 0.0012 - cap: 5,750,000 stages.createStage(4, endTime, 15000000000, 1000000, 2000000000000); //Deadline 1 week after start - price: 0.0015 - cap: 20,000,000 stagesSet = true; } // Creates new stage for the crowdsale // Can ONLY be called by the owner of the contract as should never change after creating them on initialisation function createStage(uint8 _stage, uint256 _deadline, uint256 _price, uint256 _minimum, uint256 _cap ) internal onlyOwner { stages.createStage(_stage, _deadline, _price, _minimum, _cap); } // Creates new stage for the crowdsale // Can ONLY be called by the owner of the contract as should never change after creating them on initialisation function changePrice(uint8 _stage, uint256 _price) public onlyOwner { stages.changePrice(_stage, _price); StagePriceChanged(msg.sender, _stage, _price); } // Get stage is required to rethen the stage we are currently in // This is necessary to check the stage details listed in the below functions function getStage() public view returns (uint8 stage) { return stages.getStage(); } function getStageDeadline(uint8 _stage) public view returns (uint256 deadline) { return stages.stages[_stage].deadline; } function getStageTokensSold(uint8 _stage) public view returns (uint256 sold) { return stages.stages[_stage].tokensSold; } function getStageCap(uint8 _stage) public view returns (uint256 cap) { return stages.stages[_stage].cap; } function getStageMinimum(uint8 _stage) public view returns (uint256 min) { return stages.stages[_stage].minimumBuy; } function getStagePrice(uint8 _stage) public view returns (uint256 price) { return stages.stages[_stage].tokenPrice; } // This is used for extending the sales start time (and the deadlines of each stage) accordingly function extendStart(uint256 _newStart) external onlyOwner { require(_newStart > startTime); require(_newStart > now); require(now < startTime); uint256 difference = _newStart - startTime; uint256 oldStart = startTime; startTime = _newStart; endTime = endTime + difference; // Loop through every stage in the sale for (uint8 i = 0; i < 4; i++) { // Extend that stages deadline accordingly uint256 temp = stages.stages[i].deadline; temp = temp + difference; stages.changeDeadline(i, temp); } ExtendedStart(oldStart, _newStart); } // @Override crowdsale contract to check the current stage price // @return tokens investors are due to recieve function tokensToRecieve(uint256 _wei) internal view returns (uint256 tokens) { uint8 stage = getStage(); uint256 price = getStagePrice(stage); return _wei.div(price); } // overriding Crowdsale validPurchase to add extra stage logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool isValid = false; uint8 stage = getStage(); if(stages.checkMinimum(stage, _tokens) && stages.checkCap(stage, _tokens)){ isValid = true; } return super.validPurchase(_tokens) && isValid; } // Override crowdsale finalizeSale function to log balance change plus tokens sold in that stage function finalizeSale(uint256 _weiAmount, uint256 _tokens, uint128 _buyer) internal { // Collect ETH and send them a token in return balanceOf[msg.sender] = balanceOf[msg.sender].add(_weiAmount); tokenBalanceOf[msg.sender] = tokenBalanceOf[msg.sender].add(_tokens); balancePerID[_buyer] = balancePerID[_buyer].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); tokensSent = tokensSent.add(_tokens); uint8 stage = getStage(); stages.stages[stage].tokensSold = stages.stages[stage].tokensSold.add(_tokens); } /** * Preallocate tokens for the early investors. */ function preallocate(address receiver, uint tokens, uint weiPrice) internal { uint decimals = token.decimals(); uint tokenAmount = tokens * 10 ** decimals; uint weiAmount = weiPrice * tokens; presaleWeiRaised = presaleWeiRaised.add(weiAmount); tokensSent = tokensSent.add(tokenAmount); tokenBalanceOf[receiver] = tokenBalanceOf[receiver].add(tokenAmount); presaleBalanceOf[receiver] = presaleBalanceOf[receiver].add(weiAmount); produceTokens(receiver, weiAmount, tokenAmount); } // If the sale is unsuccessful (has halted or reached deadline and didnt reach softcap) // Allows participants to withdraw their balance function unsuccessfulWithdrawal() external { require(balanceOf[msg.sender] > 0); require(hasEnded() && tokensSent < softCap || hasHalted()); uint256 withdrawalAmount; withdrawalAmount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(withdrawalAmount); assert(balanceOf[msg.sender] == 0); ParticipantWithdrawal(msg.sender, withdrawalAmount, now); } // Burn the percentage of tokens not sold from the founders and bounty wallets // Must do it this way as solidity doesnt deal with decimals function burnFoundersTokens(uint256 _bounty, uint256 _founders) internal { require(_founders < 177777700000); require(_bounty < 44444500000); // Calculate the number of tokens to burn from founders and bounty wallet burntFounder = _founders; burntBounty = _bounty; token.reclaimAndBurn(founders, burntFounder); token.reclaimAndBurn(bounty, burntBounty); } } // File: contracts/KYCCrowdsale.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * * Some implementation has been changed by Pickeringware ltd to achieve custom features */ /* * A crowdsale that allows only signed payload with server-side specified buy in limits. * * The token distribution happens as in the allocated crowdsale contract */ contract KYCCrowdsale is KYCPayloadDeserializer, PickCrowdsale { /* Server holds the private key to this address to decide if the AML payload is valid or not. */ address public signerAddress; mapping(address => uint256) public refundable; mapping(address => bool) public refunded; mapping(address => bool) public blacklist; /* A new server-side signer key was set to be effective */ event SignerChanged(address signer); event TokensReclaimed(address user, uint256 amount, uint256 datetime); event AddedToBlacklist(address user, uint256 datetime); event RemovedFromBlacklist(address user, uint256 datetime); event RefundCollected(address user, uint256 datetime); event TokensReleased(address agent, uint256 datetime, uint256 bounty, uint256 founders); /* * Constructor. */ function KYCCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, address _buyer, address _founders, address _bounty, uint256 _softCap, uint256 _hardCap, PickToken _token) public PickCrowdsale(_startTime, _endTime, _rate, _wallet, _beneficiary, _buyer, _founders, _bounty, _softCap, _hardCap, _token) {} // This sets the token agent to the contract, allowing the contract to reclaim and burn tokens if necessary function setTokenAgent() external onlyOwner { // contractAddr = token.owner(); // Give the sale contract rights to reclaim tokens token.setReleaseAgent(); } /* * This function was written by Pickeringware ltd to facilitate a refund action upon failure of KYC analysis * * It simply allows the participant to withdraw his ether from the sale * Moves the crowdsale sliders accordingly * Reclaims the users tokens and burns them * Blacklists the user to prevent them from buying any more tokens * * Stage 1, 2, 3, & 4 are all collected from the database prior to calling this function * It allows us to calculate how many tokens need to be taken from each individual stage */ function refundParticipant(address participant, uint256 _stage1, uint256 _stage2, uint256 _stage3, uint256 _stage4) external onlyOwner { require(balanceOf[participant] > 0); uint256 balance = balanceOf[participant]; uint256 tokens = tokenBalanceOf[participant]; balanceOf[participant] = 0; tokenBalanceOf[participant] = 0; // Refund the participant refundable[participant] = balance; // Move the crowdsale sliders weiRaised = weiRaised.sub(balance); tokensSent = tokensSent.sub(tokens); // Reclaim the participants tokens and burn them token.reclaimAllAndBurn(participant); // Blacklist participant so they cannot make further purchases blacklist[participant] = true; AddedToBlacklist(participant, now); stages.refundParticipant(_stage1, _stage2, _stage3, _stage4); TokensReclaimed(participant, tokens, now); } // Allows only the beneficiary to release tokens to people // This is needed as the token is owned by the contract, in order to mint tokens // therefore, the owner essentially gives permission for the contract to release tokens function releaseTokens(uint256 _bounty, uint256 _founders) onlyOwner external { // Unless the hardcap was reached, theremust be tokens to burn require(_bounty > 0 || tokensSent == hardCap); require(_founders > 0 || tokensSent == hardCap); burnFoundersTokens(_bounty, _founders); token.releaseTokenTransfer(); canWithdraw = true; TokensReleased(msg.sender, now, _bounty, _founders); } // overriding Crowdsale#validPurchase to add extra KYC blacklist logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool onBlackList; if(blacklist[msg.sender] == true){ onBlackList = true; } else { onBlackList = false; } return super.validPurchase(_tokens) && !onBlackList; } // This is necessary for the blacklisted user to pull his ether from the contract upon being refunded function collectRefund() external { require(refundable[msg.sender] > 0); require(refunded[msg.sender] == false); uint256 theirwei = refundable[msg.sender]; refundable[msg.sender] = 0; refunded[msg.sender] == true; msg.sender.transfer(theirwei); RefundCollected(msg.sender, now); } /* * A token purchase with anti-money laundering and KYC checks * This function takes in a dataframe and EC signature to verify if the purchaser has been verified * on the server side of our application and has therefore, participated in KYC. * Upon registering to the site, users are supplied with a signature allowing them to purchase tokens, * which can be revoked at any time, this containst their ETH address, a unique ID and the min and max * ETH that user has stated they will purchase. (Any more than the max may be subject to AML checks). */ function buyWithKYCData(bytes dataframe, uint8 v, bytes32 r, bytes32 s) public payable { bytes32 hash = sha256(dataframe); address whitelistedAddress; uint128 customerId; uint32 minETH; uint32 maxETH; (whitelistedAddress, customerId, minETH, maxETH) = getKYCPayload(dataframe); // Check that the KYC data is signed by our server require(ecrecover(hash, v, r, s) == signerAddress); // Check that the user is using his own signature require(whitelistedAddress == msg.sender); // Check they are buying within their limits - THIS IS ONLY NEEDED IF SPECIFIED BY REGULATORS uint256 weiAmount = msg.value; uint256 max = maxETH; uint256 min = minETH; require(weiAmount < (max * 1 ether)); require(weiAmount > (min * 1 ether)); buyTokens(customerId); } /// @dev This function can set the server side address /// @param _signerAddress The address derived from server&#39;s private key function setSignerAddress(address _signerAddress) external onlyOwner { // EC rcover returns 0 in case of error therefore, this CANNOT be 0. require(_signerAddress != 0); signerAddress = _signerAddress; SignerChanged(signerAddress); } function removeFromBlacklist(address _blacklisted) external onlyOwner { require(blacklist[_blacklisted] == true); blacklist[_blacklisted] = false; RemovedFromBlacklist(_blacklisted, now); } }
Both of the below are checked on the overridden validPurchase() function Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage
function checkMinimum(StageStorage storage self, uint8 _stage, uint256 _tokens) internal view returns (bool isValid) { if(_tokens < self.stages[_stage].minimumBuy){ return false; return true; } }
2,166,596
[ 1, 20240, 434, 326, 5712, 854, 5950, 603, 326, 11000, 923, 23164, 1435, 445, 2073, 358, 2621, 309, 326, 2430, 2898, 10, 5520, 31, 266, 2973, 358, 23701, 353, 5721, 326, 5224, 364, 333, 6009, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 13042, 12, 8755, 3245, 2502, 365, 16, 2254, 28, 389, 12869, 16, 2254, 5034, 389, 7860, 13, 2713, 1476, 1135, 261, 6430, 4908, 13, 288, 203, 377, 202, 430, 24899, 7860, 411, 365, 18, 334, 1023, 63, 67, 12869, 8009, 15903, 38, 9835, 15329, 203, 377, 202, 202, 2463, 629, 31, 203, 377, 202, 202, 2463, 638, 31, 203, 377, 202, 97, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.0; import "./Lib/Address.sol"; import "./Lib/SafeMath.sol"; import "./Lib/AddressPayable.sol"; import "./Lib/SafeERC20.sol"; /** * @title NToken contract * @dev Include standard erc20 method, mining method, and mining data */ 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); } // Executable contract interface Nest_3_Implement { // Execute function doit() external; } // NestNode assignment contract interface Nest_NodeAssignment { function bookKeeping(uint256 amount) external; } /** * @title Voting factory + mapping * @dev Vote creating method */ contract Nest_3_VoteFactory { using SafeMath for uint256; uint256 _limitTime = 7 days; // Vote duration uint256 _NNLimitTime = 1 days; // NestNode raising time uint256 _circulationProportion = 51; // Proportion of votes to pass uint256 _NNUsedCreate = 10; // The minimum number of NNs to create a voting contract uint256 _NNCreateLimit = 100; // The minimum number of NNs needed to start voting uint256 _emergencyTime = 0; // The emergency state start time uint256 _emergencyTimeLimit = 3 days; // The emergency state duration uint256 _emergencyNNAmount = 1000; // The number of NNs required to switch the emergency state ERC20 _NNToken; // NestNode Token ERC20 _nestToken; // NestToken mapping(string => address) _contractAddress; // Voting contract mapping mapping(address => bool) _modifyAuthority; // Modify permissions mapping(address => address) _myVote; // Personal voting address mapping(address => uint256) _emergencyPerson; // Emergency state personal voting number mapping(address => bool) _contractData; // Voting contract data bool _stateOfEmergency = false; // Emergency state address _destructionAddress; // Destroy contract address event ContractAddress(address contractAddress); /** * @dev Initialization method */ constructor () public { _modifyAuthority[address(msg.sender)] = true; } /** * @dev Reset contract */ function changeMapping() public onlyOwner { _NNToken = ERC20(checkAddress("nestNode")); _destructionAddress = address(checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(checkAddress("nest"))); } /** * @dev Create voting contract * @param implementContract The executable contract address for voting * @param nestNodeAmount Number of NNs to pledge */ function createVote(address implementContract, uint256 nestNodeAmount) public { require(address(tx.origin) == address(msg.sender), "It can't be a contract"); require(nestNodeAmount >= _NNUsedCreate); Nest_3_VoteContract newContract = new Nest_3_VoteContract(implementContract, _stateOfEmergency, nestNodeAmount); require(_NNToken.transferFrom(address(tx.origin), address(newContract), nestNodeAmount), "Authorization transfer failed"); _contractData[address(newContract)] = true; emit ContractAddress(address(newContract)); } /** * @dev Use NEST to vote * @param contractAddress Vote contract address */ function nestVote(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); require(!checkVoteNow(address(msg.sender))); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); newContract.nestVote(); _myVote[address(tx.origin)] = contractAddress; } /** * @dev Vote using NestNode Token * @param contractAddress Vote contract address * @param NNAmount Amount of NNs to pledge */ function nestNodeVote(address contractAddress, uint256 NNAmount) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_NNToken.transferFrom(address(tx.origin), address(newContract), NNAmount), "Authorization transfer failed"); newContract.nestNodeVote(NNAmount); } /** * @dev Excecute contract * @param contractAddress Vote contract address */ function startChange(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_stateOfEmergency == newContract.checkStateOfEmergency()); addSuperManPrivate(address(newContract)); newContract.startChange(); deleteSuperManPrivate(address(newContract)); } /** * @dev Switch emergency state-transfer in NestNode Token * @param amount Amount of NNs to transfer */ function sendNestNodeForStateOfEmergency(uint256 amount) public { require(_NNToken.transferFrom(address(tx.origin), address(this), amount)); _emergencyPerson[address(tx.origin)] = _emergencyPerson[address(tx.origin)].add(amount); } /** * @dev Switch emergency state-transfer out NestNode Token */ function turnOutNestNodeForStateOfEmergency() public { require(_emergencyPerson[address(tx.origin)] > 0); require(_NNToken.transfer(address(tx.origin), _emergencyPerson[address(tx.origin)])); _emergencyPerson[address(tx.origin)] = 0; uint256 nestAmount = _nestToken.balanceOf(address(this)); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Modify emergency state */ function changeStateOfEmergency() public { if (_stateOfEmergency) { require(now > _emergencyTime.add(_emergencyTimeLimit)); _stateOfEmergency = false; _emergencyTime = 0; } else { require(_emergencyPerson[address(msg.sender)] > 0); require(_NNToken.balanceOf(address(this)) >= _emergencyNNAmount); _stateOfEmergency = true; _emergencyTime = now; } } /** * @dev Check whether participating in the voting * @param user Address to check * @return bool Whether voting */ function checkVoteNow(address user) public view returns (bool) { if (_myVote[user] == address(0x0)) { return false; } else { Nest_3_VoteContract vote = Nest_3_VoteContract(_myVote[user]); if (vote.checkContractEffective() || vote.checkPersonalAmount(user) == 0) { return false; } return true; } } /** * @dev Check my voting * @param user Address to check * @return address Address recently participated in the voting contract address */ function checkMyVote(address user) public view returns (address) { return _myVote[user]; } // Check the voting time function checkLimitTime() public view returns (uint256) { return _limitTime; } // Check the NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the voting proportion to pass function checkCirculationProportion() public view returns (uint256) { return _circulationProportion; } // Check the minimum number of NNs to create a voting contract function checkNNUsedCreate() public view returns (uint256) { return _NNUsedCreate; } // Check the minimum number of NNs raised to start a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check the start time of the emergency state function checkEmergencyTime() public view returns (uint256) { return _emergencyTime; } // Check the duration of the emergency state function checkEmergencyTimeLimit() public view returns (uint256) { return _emergencyTimeLimit; } // Check the amount of personal pledged NNs function checkEmergencyPerson(address user) public view returns (uint256) { return _emergencyPerson[user]; } // Check the number of NNs required for the emergency function checkEmergencyNNAmount() public view returns (uint256) { return _emergencyNNAmount; } // Verify voting contract data function checkContractData(address contractAddress) public view returns (bool) { return _contractData[contractAddress]; } // Modify voting time function changeLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _limitTime = num; } // Modify the NestNode raising time function changeNNLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _NNLimitTime = num; } // Modify the voting proportion function changeCirculationProportion(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _circulationProportion = num; } // Modify the minimum number of NNs to create a voting contract function changeNNUsedCreate(uint256 num) public onlyOwner { _NNUsedCreate = num; } // Modify the minimum number of NNs to raised to start a voting function checkNNCreateLimit(uint256 num) public onlyOwner { _NNCreateLimit = num; } // Modify the emergency state duration function changeEmergencyTimeLimit(uint256 num) public onlyOwner { require(num > 0); _emergencyTimeLimit = num.mul(1 days); } // Modify the number of NNs required for emergency state function changeEmergencyNNAmount(uint256 num) public onlyOwner { require(num > 0); _emergencyNNAmount = num; } // Check address function checkAddress(string memory name) public view returns (address contractAddress) { return _contractAddress[name]; } // Add contract mapping address function addContractAddress(string memory name, address contractAddress) public onlyOwner { _contractAddress[name] = contractAddress; } // Add administrator address function addSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = true; } function addSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = true; } // Delete administrator address function deleteSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = false; } function deleteSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = false; } // Delete voting contract data function deleteContractData(address contractAddress) public onlyOwner { _contractData[contractAddress] = false; } // Check whether the administrator function checkOwners(address man) public view returns (bool) { return _modifyAuthority[man]; } // Administrator only modifier onlyOwner() { require(checkOwners(msg.sender), "No authority"); _; } } /** * @title Voting contract */ contract Nest_3_VoteContract { using SafeMath for uint256; Nest_3_Implement _implementContract; // Executable contract Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_VoteFactory _voteFactory; // Voting factory contract Nest_3_TokenAbonus _tokenAbonus; // Bonus logic contract ERC20 _nestToken; // NestToken ERC20 _NNToken; // NestNode Token address _miningSave; // Mining pool contract address _implementAddress; // Executable contract address address _destructionAddress; // Destruction contract address uint256 _createTime; // Creation time uint256 _endTime; // End time uint256 _totalAmount; // Total votes uint256 _circulation; // Passed votes uint256 _destroyedNest; // Destroyed NEST uint256 _NNLimitTime; // NestNode raising time uint256 _NNCreateLimit; // Minimum number of NNs to create votes uint256 _abonusTimes; // Period number of used snapshot in emergency state uint256 _allNNAmount; // Total number of NNs bool _effective = false; // Whether vote is effective bool _nestVote = false; // Whether NEST vote can be performed bool _isChange = false; // Whether NEST vote is executed bool _stateOfEmergency; // Whether the contract is in emergency state mapping(address => uint256) _personalAmount; // Number of personal votes mapping(address => uint256) _personalNNAmount; // Number of NN personal votes /** * @dev Initialization method * @param contractAddress Executable contract address * @param stateOfEmergency Whether in emergency state * @param NNAmount Amount of NNs */ constructor (address contractAddress, bool stateOfEmergency, uint256 NNAmount) public { Nest_3_VoteFactory voteFactory = Nest_3_VoteFactory(address(msg.sender)); _voteFactory = voteFactory; _nestToken = ERC20(voteFactory.checkAddress("nest")); _NNToken = ERC20(voteFactory.checkAddress("nestNode")); _implementContract = Nest_3_Implement(address(contractAddress)); _implementAddress = address(contractAddress); _destructionAddress = address(voteFactory.checkAddress("nest.v3.destruction")); _personalNNAmount[address(tx.origin)] = NNAmount; _allNNAmount = NNAmount; _createTime = now; _endTime = _createTime.add(voteFactory.checkLimitTime()); _NNLimitTime = voteFactory.checkNNLimitTime(); _NNCreateLimit = voteFactory.checkNNCreateLimit(); _stateOfEmergency = stateOfEmergency; if (stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data _tokenAbonus = Nest_3_TokenAbonus(payable(voteFactory.checkAddress("nest.v3.tokenAbonus"))); _abonusTimes = _tokenAbonus.checkTimes().sub(2); require(_abonusTimes > 0); _circulation = _tokenAbonus.checkTokenAllValueHistory(address(_nestToken),_abonusTimes).mul(voteFactory.checkCirculationProportion()).div(100); } else { _miningSave = address(voteFactory.checkAddress("nest.v3.miningSave")); _tokenSave = Nest_3_TokenSave(voteFactory.checkAddress("nest.v3.tokenSave")); _circulation = (uint256(10000000000 ether).sub(_nestToken.balanceOf(address(_miningSave))).sub(_nestToken.balanceOf(address(_destructionAddress)))).mul(voteFactory.checkCirculationProportion()).div(100); } if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev NEST voting */ function nestVote() public onlyFactory { require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_nestVote); require(_personalAmount[address(tx.origin)] == 0, "Have voted"); uint256 amount; if (_stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data amount = _tokenAbonus.checkTokenSelfHistory(address(_nestToken),_abonusTimes, address(tx.origin)); } else { amount = _tokenSave.checkAmount(address(tx.origin), address(_nestToken)); } _personalAmount[address(tx.origin)] = amount; _totalAmount = _totalAmount.add(amount); ifEffective(); } /** * @dev NEST voting cancellation */ function nestVoteCancel() public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_personalAmount[address(tx.origin)] > 0, "No vote"); _totalAmount = _totalAmount.sub(_personalAmount[address(tx.origin)]); _personalAmount[address(tx.origin)] = 0; } /** * @dev NestNode voting * @param NNAmount Amount of NNs */ function nestNodeVote(uint256 NNAmount) public onlyFactory { require(now <= _createTime.add(_NNLimitTime), "Voting time exceeded"); require(!_nestVote); _personalNNAmount[address(tx.origin)] = _personalNNAmount[address(tx.origin)].add(NNAmount); _allNNAmount = _allNNAmount.add(NNAmount); if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev Withdrawing lock-up NNs */ function turnOutNestNode() public { if (_nestVote) { // Normal NEST voting if (!_stateOfEmergency || !_effective) { // Non-emergency state require(now > _endTime, "Vote unenforceable"); } } else { // NN voting require(now > _createTime.add(_NNLimitTime)); } require(_personalNNAmount[address(tx.origin)] > 0); // Reverting back the NNs require(_NNToken.transfer(address(tx.origin), _personalNNAmount[address(tx.origin)])); _personalNNAmount[address(tx.origin)] = 0; // Destroying NEST Tokens uint256 nestAmount = _nestToken.balanceOf(address(this)); _destroyedNest = _destroyedNest.add(nestAmount); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Execute the contract */ function startChange() public onlyFactory { require(!_isChange); _isChange = true; if (_stateOfEmergency) { require(_effective, "Vote unenforceable"); } else { require(_effective && now > _endTime, "Vote unenforceable"); } // Add the executable contract to the administrator list _voteFactory.addSuperMan(address(_implementContract)); // Execute _implementContract.doit(); // Delete the authorization _voteFactory.deleteSuperMan(address(_implementContract)); } /** * @dev check whether the vote is effective */ function ifEffective() private { if (_totalAmount >= _circulation) { _effective = true; } } /** * @dev Check whether the vote is over */ function checkContractEffective() public view returns (bool) { if (_effective || now > _endTime) { return true; } return false; } // Check the executable implement contract address function checkImplementAddress() public view returns (address) { return _implementAddress; } // Check the voting start time function checkCreateTime() public view returns (uint256) { return _createTime; } // Check the voting end time function checkEndTime() public view returns (uint256) { return _endTime; } // Check the current total number of votes function checkTotalAmount() public view returns (uint256) { return _totalAmount; } // Check the number of votes to pass function checkCirculation() public view returns (uint256) { return _circulation; } // Check the number of personal votes function checkPersonalAmount(address user) public view returns (uint256) { return _personalAmount[user]; } // Check the destroyed NEST function checkDestroyedNest() public view returns (uint256) { return _destroyedNest; } // Check whether the contract is effective function checkEffective() public view returns (bool) { return _effective; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the minimum number of NNs to create a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check the period number of snapshot used in the emergency state function checkAbonusTimes() public view returns (uint256) { return _abonusTimes; } // Check number of personal votes function checkPersonalNNAmount(address user) public view returns (uint256) { return _personalNNAmount[address(user)]; } // Check the total number of NNs function checkAllNNAmount() public view returns (uint256) { return _allNNAmount; } // Check whether NEST voting is available function checkNestVote() public view returns (bool) { return _nestVote; } // Check whether it has been excecuted function checkIsChange() public view returns (bool) { return _isChange; } // Vote Factory contract only modifier onlyFactory() { require(address(_voteFactory) == address(msg.sender), "No authority"); _; } } /** * @title Mining contract * @dev Mining pool + mining logic */ contract Nest_3_MiningContract { using address_make_payable for address; using SafeMath for uint256; uint256 _blockAttenuation = 2400000; // Block decay time interval uint256[10] _attenuationAmount; // Mining decay amount uint256 _afterMiningAmount = 40 ether; // Stable period mining amount uint256 _firstBlockNum; // Starting mining block uint256 _latestMining; // Latest offering block Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestContract; // NEST contract address address _offerFactoryAddress; // Offering contract address // Current block, current block mining amount event OreDrawingLog(uint256 nowBlock, uint256 blockAmount); /** * @dev Initialization method * @param voteFactory voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); // Initiate mining parameters _firstBlockNum = 6236588; _latestMining = block.number; uint256 blockAmount = 400 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); } /** * @dev Offering mining * @return Current block mining amount */ function oreDrawing() public returns (uint256) { require(address(msg.sender) == _offerFactoryAddress, "No authority"); // Update mining amount list uint256 miningAmount = changeBlockAmountList(); // Transfer NEST if (_nestContract.balanceOf(address(this)) < miningAmount){ miningAmount = _nestContract.balanceOf(address(this)); } if (miningAmount > 0) { _nestContract.transfer(address(msg.sender), miningAmount); emit OreDrawingLog(block.number,miningAmount); } return miningAmount; } /** * @dev Update mining amount list */ function changeBlockAmountList() private returns (uint256) { uint256 createBlock = _firstBlockNum; uint256 recentlyUsedBlock = _latestMining; uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); _latestMining = block.number; return miningAmount; } /** * @dev Transfer all NEST * @param target Transfer target address */ function takeOutNest(address target) public onlyOwner { _nestContract.transfer(address(target),_nestContract.balanceOf(address(this))); } // Check block decay time interval function checkBlockAttenuation() public view returns(uint256) { return _blockAttenuation; } // Check latest offering block function checkLatestMining() public view returns(uint256) { return _latestMining; } // Check mining amount decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Check NEST balance function checkNestBalance() public view returns(uint256) { return _nestContract.balanceOf(address(this)); } // Modify block decay time interval function changeBlockAttenuation(uint256 blockNum) public onlyOwner { require(blockNum > 0); _blockAttenuation = blockNum; } // Modify mining amount decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Offering contract * @dev Offering + take order + NEST allocation */ contract Nest_3_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; struct Nest_3_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_3_OfferPriceData [] _prices; // Array used to save offers mapping(address => bool) _tokenAllow; // List of allowed mining token Nest_3_VoteFactory _voteFactory; // Vote contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_3_MiningContract _miningContract; // Mining contract Nest_NodeAssignment _NNcontract; // NestNode contract ERC20 _nestToken; // NestToken Nest_3_Abonus _abonus; // Bonus pool address _coderAddress; // Developer address uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _coderAmount = 5; // Developer ratio uint256 _NNAmount = 15; // NestNode ratio uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint32 _blockLimit = 25; // Block interval upper limit mapping(uint256 => uint256) _offerBlockEth; // Block offer fee mapping(uint256 => uint256) _offerBlockMining; // Block mining amount // Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge); // Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Offering mining * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 token amount * @param erc20Address Offering erc20 token address */ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_tokenAllow[erc20Address], "Token not allow"); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); // Mining uint256 miningAmount = _miningContract.oreDrawing(); _abonus.switchToEth.value(ethMining)(address(_nestToken)); if (miningAmount > 0) { uint256 coder = miningAmount.mul(_coderAmount).div(100); uint256 NN = miningAmount.mul(_NNAmount).div(100); uint256 other = miningAmount.sub(coder).sub(NN); _offerBlockMining[block.number] = other; _NNcontract.bookKeeping(NN); if (coder > 0) { _nestToken.safeTransfer(_coderAddress, coder); } } _offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address * @param mining Offering mining fee (0 for takers) * @param isDeviate Whether the current price chain deviates */ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_3_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Withdraw the assets, and settle the mining * @param contractAddress The offer address to withdraw */ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]); _nestToken.safeTransfer(offerPriceData.owner, myMiningAmount); offerPriceData.serviceCharge = 0; } } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } // View contract state function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Compare the order price function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint32) { return _blockLimit; } // View offering mining fee ratio function checkMiningETH() public view returns (uint256) { return _miningETH; } // View whether the token is allowed to mine function checkTokenAllow(address token) public view returns(bool) { return _tokenAllow[token]; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View the development allocation ratio function checkCoderAmount() public view returns(uint256) { return _coderAmount; } // View the NestNode allocation ratio function checkNNAmount() public view returns(uint256) { return _NNAmount; } // View the least offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View the price deviation function checkDeviate() public view returns(uint256){ return _deviate; } // View deviation from scale function checkDeviationFromScale() public view returns(uint256) { return _deviationFromScale; } // View block offer fee function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) { return _offerBlockEth[blockNum]; } // View taker order fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View block mining amount of user function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) { return _offerBlockMining[blockNum]; } // View offer mining amount function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]); } } // Change offering mining fee ratio function changeMiningETH(uint256 num) public onlyOwner { _miningETH = num; } // Modify taker fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify the upper limit of the block interval function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify whether the token allows mining function changeTokenAllow(address token, bool allow) public onlyOwner { _tokenAllow[token] = allow; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify the initial allocation ratio function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner { require(coderNum.add(NNNum) <= 100, "User allocation ratio error"); _coderAmount = coderNum; _NNAmount = NNNum; } // Modify the minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0); _leastEth = num; } // Modify the offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0); _offerSpan = num; } // Modify the price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_3_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form and write it into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Vote administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Price contract * @dev Price check and call */ contract Nest_3_OfferPrice{ using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestToken; // NestToken Nest_NToken_TokenMapping _tokenMapping; // NToken mapping Nest_3_OfferMain _offerMain; // Offering main contract Nest_3_Abonus _abonus; // Bonus pool address _nTokeOfferMain; // NToken offering main contract address _destructionAddress; // Destruction contract address address _nTokenAuction; // NToken auction contract address struct PriceInfo { // Block price uint256 ethAmount; // ETH amount uint256 erc20Amount; // Erc20 amount uint256 frontBlock; // Last effective block address offerOwner; // Offering address } struct TokenInfo { // Token offer information mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price uint256 latestOffer; // Latest effective block } uint256 destructionAmount = 0 ether; // Amount of NEST to destroy to call prices uint256 effectTime = 0 days; // Waiting time to start calling prices mapping(address => TokenInfo) _tokenInfo; // Token offer information mapping(address => bool) _blocklist; // Block list mapping(address => uint256) _addressEffect; // Effective time of address to call prices mapping(address => bool) _offerMainMapping; // Offering contract mapping uint256 _priceCost = 0.01 ether; // Call price fee // Real-time price token, ETH amount, erc20 amount event NowTokenPrice(address a, uint256 b, uint256 c); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Initialize token price charge parameters * @param tokenAddress Token address */ function addPriceCost(address tokenAddress) public { } /** * @dev Add price * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param endBlock Effective price block * @param tokenAddress Erc20 address * @param offerOwner Offering address */ function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{ // Add effective block price information TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount); if (endBlock != tokenInfo.latestOffer) { // If different block offer priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; } } /** * @dev Price modification in taker orders * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param tokenAddress Token address * @param endBlock Block of effective price */ function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain { TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount); } /** * @dev Update and check the latest price * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount * @return blockNum Price block */ function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } require(checkBlock != 0); PriceInfo memory priceInfo = priceInfoList[checkBlock]; address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount); return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } /** * @dev Update and check the latest price-internal use * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount */ function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) { mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0); } PriceInfo memory priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount); } /** * @dev Update and check the effective price list * @param tokenAddress Token address * @param num Number of prices to check * @return uint256[] price list */ function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; // Extract data uint256 length = num.mul(3); uint256 index = 0; uint256[] memory data = new uint256[](length); uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(index < length && checkBlock > 0){ if (checkBlock < block.number && priceInfoList[checkBlock].ethAmount != 0) { // Add return data data[index++] = priceInfoList[checkBlock].ethAmount; data[index++] = priceInfoList[checkBlock].erc20Amount; data[index++] = checkBlock; } checkBlock = priceInfoList[checkBlock].frontBlock; } require(length == data.length); // Allocation address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } return data; } // Activate the price checking function function activation() public { _nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount); _addressEffect[address(msg.sender)] = now.add(effectTime); } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // Check block price - user account only function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount); } // Check real-time price - user account only function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0,0); } PriceInfo storage priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } // Check whether the price-checking functions can be called function checkUseNestPrice(address target) public view returns (bool) { if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) { return true; } else { return false; } } // Check whether the address is in the blocklist function checkBlocklist(address add) public view returns(bool) { return _blocklist[add]; } // Check the amount of NEST to destroy to call prices function checkDestructionAmount() public view returns(uint256) { return destructionAmount; } // Check the waiting time to start calling prices function checkEffectTime() public view returns (uint256) { return effectTime; } // Check call price fee function checkPriceCost() public view returns (uint256) { return _priceCost; } // Modify the blocklist function changeBlocklist(address add, bool isBlock) public onlyOwner { _blocklist[add] = isBlock; } // Amount of NEST to destroy to call price-checking functions function changeDestructionAmount(uint256 amount) public onlyOwner { destructionAmount = amount; } // Modify the waiting time to start calling prices function changeEffectTime(uint256 num) public onlyOwner { effectTime = num; } // Modify call price fee function changePriceCost(uint256 num) public onlyOwner { _priceCost = num; } // Offering contract only modifier onlyOfferMain(){ require(_offerMainMapping[address(msg.sender)], "No authority"); _; } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title NEST and NToken lock-up contract * @dev NEST and NToken deposit and withdrawal */ contract Nest_3_TokenSave { using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract mapping(address => mapping(address => uint256)) _baseMapping; // Ledger token=>user=>amount /** * @dev initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Withdrawing * @param num Withdrawing amount * @param token Lock-up token address * @param target Transfer target */ function takeOut(uint256 num, address token, address target) public onlyContract { require(num <= _baseMapping[token][address(target)], "Insufficient storage balance"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].sub(num); ERC20(token).transfer(address(target), num); } /** * @dev Depositing * @param num Depositing amount * @param token Lock-up token address * @param target Depositing target */ function depositIn(uint256 num, address token, address target) public onlyContract { require(ERC20(token).transferFrom(address(target),address(this),num), "Authorization transfer failed"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].add(num); } /** * @dev Check the amount * @param sender Check address * @param token Lock-up token address * @return uint256 Check address corresponding lock-up limit */ function checkAmount(address sender, address token) public view returns(uint256) { return _baseMapping[token][address(sender)]; } // Administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } // Only for bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } } /** * @title Dividend logic * @dev Some operations about dividend,logic and asset separation */ contract Nest_3_TokenAbonus { using address_make_payable for address; using SafeMath for uint256; ERC20 _nestContract; Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_Abonus _abonusContract; // ETH bonus pool Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_Leveling _nestLeveling; // Leveling contract address _destructionAddress; // Destroy contract address uint256 _timeLimit = 168 hours; // Bonus period uint256 _nextTime = 1596168000; // Next bonus time uint256 _getAbonusTimeLimit = 60 hours; // During of triggering calculation of bonus uint256 _times = 0; // Bonus ledger uint256 _expectedIncrement = 3; // Expected bonus increment ratio uint256 _expectedSpanForNest = 100000000 ether; // NEST expected bonus increment threshold uint256 _expectedSpanForNToken = 1000000 ether; // NToken expected bonus increment threshold uint256 _expectedMinimum = 100 ether; // Expected minimum bonus uint256 _savingLevelOne = 10; // Saving threshold level 1 uint256 _savingLevelTwo = 20; // Saving threshold level 2 uint256 _savingLevelTwoSub = 100 ether; // Function parameters of savings threshold level 2 uint256 _savingLevelThree = 30; // Function parameters of savings threshold level 3 uint256 _savingLevelThreeSub = 600 ether; // Function parameters of savings threshold level 3 mapping(address => uint256) _abonusMapping; // Bonus pool snapshot - token address (NEST or NToken) => number of ETH in the bonus pool mapping(address => uint256) _tokenAllValueMapping; // Number of tokens (circulation) - token address (NEST or NToken) ) => total circulation mapping(address => mapping(uint256 => uint256)) _tokenAllValueHistory; // NEST or NToken circulation snapshot - token address (NEST or NToken) => number of periods => total circulation mapping(address => mapping(uint256 => mapping(address => uint256))) _tokenSelfHistory; // Personal lockup - NEST or NToken snapshot token address (NEST or NToken) => period => user address => total circulation mapping(address => mapping(uint256 => bool)) _snapshot; // Whether snapshot - token address (NEST or NToken) => number of periods => whether to take a snapshot mapping(uint256 => mapping(address => mapping(address => bool))) _getMapping; // Receiving records - period => token address (NEST or NToken) => user address => whether received // Log token address, amount event GetTokenLog(address tokenAddress, uint256 tokenAmount); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Deposit * @param amount Deposited amount * @param token Locked token address */ function depositIn(uint256 amount, address token) public { uint256 nowTime = now; uint256 nextTime = _nextTime; uint256 timeLimit = _timeLimit; if (nowTime < nextTime) { // Bonus triggered require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(_getAbonusTimeLimit))); } else { // Bonus not triggered uint256 times = (nowTime.sub(_nextTime)).div(_timeLimit); // Calculate the time when bonus should be started uint256 startTime = _nextTime.add((times).mul(_timeLimit)); // Calculate the time when bonus should be stopped uint256 endTime = startTime.add(_getAbonusTimeLimit); require(!(nowTime >= startTime && nowTime <= endTime)); } _tokenSave.depositIn(amount, token, address(msg.sender)); } /** * @dev Withdrawing * @param amount Withdrawing amount * @param token Token address */ function takeOut(uint256 amount, address token) public { require(amount > 0, "Parameter needs to be greater than 0"); require(amount <= _tokenSave.checkAmount(address(msg.sender), token), "Insufficient storage balance"); if (token == address(_nestContract)) { require(!_voteFactory.checkVoteNow(address(tx.origin)), "Voting"); } _tokenSave.takeOut(amount, token, address(msg.sender)); } /** * @dev Receiving * @param token Receiving token address */ function getAbonus(address token) public { uint256 tokenAmount = _tokenSave.checkAmount(address(msg.sender), token); require(tokenAmount > 0, "Insufficient storage balance"); reloadTime(); reloadToken(token); uint256 nowTime = now; require(nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit), "Not time to draw"); require(!_getMapping[_times.sub(1)][token][address(msg.sender)], "Have received"); _tokenSelfHistory[token][_times.sub(1)][address(msg.sender)] = tokenAmount; require(_tokenAllValueMapping[token] > 0, "Total flux error"); uint256 selfNum = tokenAmount.mul(_abonusMapping[token]).div(_tokenAllValueMapping[token]); require(selfNum > 0, "No limit available"); _getMapping[_times.sub(1)][token][address(msg.sender)] = true; _abonusContract.getETH(selfNum, token,address(msg.sender)); emit GetTokenLog(token, selfNum); } /** * @dev Update bonus time and stage ledger */ function reloadTime() private { uint256 nowTime = now; // The current time must exceed the bonus time if (nowTime >= _nextTime) { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); uint256 startTime = _nextTime.add((time).mul(_timeLimit)); uint256 endTime = startTime.add(_getAbonusTimeLimit); if (nowTime >= startTime && nowTime <= endTime) { _nextTime = getNextTime(); _times = _times.add(1); } } } /** * @dev Snapshot of the amount of tokens * @param token Receiving token address */ function reloadToken(address token) private { if (!_snapshot[token][_times.sub(1)]) { levelingResult(token); _abonusMapping[token] = _abonusContract.getETHNum(token); _tokenAllValueMapping[token] = allValue(token); _tokenAllValueHistory[token][_times.sub(1)] = allValue(token); _snapshot[token][_times.sub(1)] = true; } } /** * @dev Leveling settlement * @param token Receiving token address */ function levelingResult(address token) private { uint256 steps; if (token == address(_nestContract)) { steps = allValue(token).div(_expectedSpanForNest); } else { steps = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < steps; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } uint256 thisAbonus = _abonusContract.getETHNum(token); if (thisAbonus > minimumAbonus) { uint256 levelAmount = 0; if (thisAbonus > 5000 ether) { levelAmount = thisAbonus.mul(_savingLevelThree).div(100).sub(_savingLevelThreeSub); } else if (thisAbonus > 1000 ether) { levelAmount = thisAbonus.mul(_savingLevelTwo).div(100).sub(_savingLevelTwoSub); } else { levelAmount = thisAbonus.mul(_savingLevelOne).div(100); } if (thisAbonus.sub(levelAmount) < minimumAbonus) { _abonusContract.getETH(thisAbonus.sub(minimumAbonus), token, address(this)); _nestLeveling.switchToEth.value(thisAbonus.sub(minimumAbonus))(token); } else { _abonusContract.getETH(levelAmount, token, address(this)); _nestLeveling.switchToEth.value(levelAmount)(token); } } else { uint256 ethValue = _nestLeveling.tranEth(minimumAbonus.sub(thisAbonus), token, address(this)); _abonusContract.switchToEth.value(ethValue)(token); } } // Next bonus time, current bonus deadline, ETH number, NEST number, NEST participating in bonus, bonus to receive, approved amount, balance, whether bonus can be paid function getInfo(address token) public view returns (uint256 nextTime, uint256 getAbonusTime, uint256 ethNum, uint256 tokenValue, uint256 myJoinToken, uint256 getEth, uint256 allowNum, uint256 leftNum, bool allowAbonus) { uint256 nowTime = now; if (nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit) && _times > 0 && _snapshot[token][_times.sub(1)]) { // Bonus have been triggered, and during the time of this bonus, display snapshot data allowAbonus = _getMapping[_times.sub(1)][token][address(msg.sender)]; ethNum = _abonusMapping[token]; tokenValue = _tokenAllValueMapping[token]; } else { // Display real-time data ethNum = _abonusContract.getETHNum(token); tokenValue = allValue(token); allowAbonus = _getMapping[_times][token][address(msg.sender)]; } myJoinToken = _tokenSave.checkAmount(address(msg.sender), token); if (allowAbonus == true) { getEth = 0; } else { getEth = myJoinToken.mul(ethNum).div(tokenValue); } nextTime = getNextTime(); getAbonusTime = nextTime.sub(_timeLimit).add(_getAbonusTimeLimit); allowNum = ERC20(token).allowance(address(msg.sender), address(_tokenSave)); leftNum = ERC20(token).balanceOf(address(msg.sender)); } /** * @dev View next bonus time * @return Next bonus time */ function getNextTime() public view returns (uint256) { uint256 nowTime = now; if (_nextTime > nowTime) { return _nextTime; } else { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); return _nextTime.add(_timeLimit.mul(time.add(1))); } } /** * @dev View total circulation * @return Total circulation */ function allValue(address token) public view returns (uint256) { if (token == address(_nestContract)) { uint256 all = 10000000000 ether; uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress))); return leftNum; } else { return ERC20(token).totalSupply(); } } /** * @dev View bonus period * @return Bonus period */ function checkTimeLimit() public view returns (uint256) { return _timeLimit; } /** * @dev View duration of triggering calculation of bonus * @return Bonus period */ function checkGetAbonusTimeLimit() public view returns (uint256) { return _getAbonusTimeLimit; } /** * @dev View current lowest expected bonus * @return Current lowest expected bonus */ function checkMinimumAbonus(address token) public view returns (uint256) { uint256 miningAmount; if (token == address(_nestContract)) { miningAmount = allValue(token).div(_expectedSpanForNest); } else { miningAmount = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < miningAmount; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } return minimumAbonus; } /** * @dev Check whether the bonus token is snapshoted * @param token Token address * @return Whether snapshoted */ function checkSnapshot(address token) public view returns (bool) { return _snapshot[token][_times.sub(1)]; } /** * @dev Check the expected bonus incremental ratio * @return Expected bonus increment ratio */ function checkeExpectedIncrement() public view returns (uint256) { return _expectedIncrement; } /** * @dev View expected minimum bonus * @return Expected minimum bonus */ function checkExpectedMinimum() public view returns (uint256) { return _expectedMinimum; } /** * @dev View savings threshold * @return Save threshold */ function checkSavingLevelOne() public view returns (uint256) { return _savingLevelOne; } function checkSavingLevelTwo() public view returns (uint256) { return _savingLevelTwo; } function checkSavingLevelThree() public view returns (uint256) { return _savingLevelThree; } /** * @dev View NEST liquidity snapshot * @param token Locked token address * @param times Bonus snapshot period */ function checkTokenAllValueHistory(address token, uint256 times) public view returns (uint256) { return _tokenAllValueHistory[token][times]; } /** * @dev View personal lock-up NEST snapshot * @param times Bonus snapshot period * @param user User address * @return The number of personal locked NEST snapshots */ function checkTokenSelfHistory(address token, uint256 times, address user) public view returns (uint256) { return _tokenSelfHistory[token][times][user]; } // View the period number of bonus function checkTimes() public view returns (uint256) { return _times; } // NEST expected bonus increment threshold function checkExpectedSpanForNest() public view returns (uint256) { return _expectedSpanForNest; } // NToken expected bonus increment threshold function checkExpectedSpanForNToken() public view returns (uint256) { return _expectedSpanForNToken; } // View the function parameters of savings threshold level 3 function checkSavingLevelTwoSub() public view returns (uint256) { return _savingLevelTwoSub; } // View the function parameters of savings threshold level 3 function checkSavingLevelThreeSub() public view returns (uint256) { return _savingLevelThreeSub; } /** * @dev Update bonus period * @param hour Bonus period (hours) */ function changeTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _timeLimit = hour.mul(1 hours); } /** * @dev Update collection period * @param hour Collection period (hours) */ function changeGetAbonusTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _getAbonusTimeLimit = hour; } /** * @dev Update expected bonus increment ratio * @param num Expected bonus increment ratio */ function changeExpectedIncrement(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedIncrement = num; } /** * @dev Update expected minimum bonus * @param num Expected minimum bonus */ function changeExpectedMinimum(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedMinimum = num; } /** * @dev Update saving threshold * @param threshold Saving threshold */ function changeSavingLevelOne(uint256 threshold) public onlyOwner { _savingLevelOne = threshold; } function changeSavingLevelTwo(uint256 threshold) public onlyOwner { _savingLevelTwo = threshold; } function changeSavingLevelThree(uint256 threshold) public onlyOwner { _savingLevelThree = threshold; } /** * @dev Update the function parameters of savings threshold level 2 */ function changeSavingLevelTwoSub(uint256 num) public onlyOwner { _savingLevelTwoSub = num; } /** * @dev Update the function parameters of savings threshold level 3 */ function changeSavingLevelThreeSub(uint256 num) public onlyOwner { _savingLevelThreeSub = num; } /** * @dev Update NEST expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNest(uint256 num) public onlyOwner { _expectedSpanForNest = num; } /** * @dev Update NToken expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNToken(uint256 num) public onlyOwner { _expectedSpanForNToken = num; } receive() external payable { } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title ETH bonus pool * @dev ETH collection and inquiry */ contract Nest_3_Abonus { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract address _nestAddress; // NEST contract address mapping (address => uint256) ethMapping; // ETH bonus ledger of corresponding tokens uint256 _mostDistribution = 40; // The highest allocation ratio of NEST bonus pool uint256 _leastDistribution = 20; // The lowest allocation ratio of NEST bonus pool uint256 _distributionTime = 1200000; // The decay time interval of NEST bonus pool allocation ratio uint256 _distributionSpan = 5; // The decay degree of NEST bonus pool allocation ratio /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner{ _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Transfer in bonus * @param token Corresponding to lock-up Token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } /** * @dev Transferin bonus - NToken offering fee * @param token Corresponding to lock-up NToken */ function switchToEthForNTokenOffer(address token) public payable { Nest_NToken nToken = Nest_NToken(token); (uint256 createBlock,) = nToken.checkBlockInfo(); uint256 subBlock = block.number.sub(createBlock); uint256 times = subBlock.div(_distributionTime); uint256 distributionValue = times.mul(_distributionSpan); uint256 distribution = _mostDistribution; if (_leastDistribution.add(distributionValue) > _mostDistribution) { distribution = _leastDistribution; } else { distribution = _mostDistribution.sub(distributionValue); } uint256 nestEth = msg.value.mul(distribution).div(100); ethMapping[_nestAddress] = ethMapping[_nestAddress].add(nestEth); ethMapping[token] = ethMapping[token].add(msg.value.sub(nestEth)); } /** * @dev Receive ETH * @param num Receive amount * @param token Correspond to locked Token * @param target Transfer target */ function getETH(uint256 num, address token, address target) public onlyContract { require(num <= ethMapping[token], "Insufficient storage balance"); ethMapping[token] = ethMapping[token].sub(num); address payable addr = target.make_payable(); addr.transfer(num); } /** * @dev Get bonus pool balance * @param token Corresponded locked Token * @return uint256 Bonus pool balance */ function getETHNum(address token) public view returns (uint256) { return ethMapping[token]; } // View NEST address function checkNestAddress() public view returns(address) { return _nestAddress; } // View the highest NEST bonus pool allocation ratio function checkMostDistribution() public view returns(uint256) { return _mostDistribution; } // View the lowest NEST bonus pool allocation ratio function checkLeastDistribution() public view returns(uint256) { return _leastDistribution; } // View the decay time interval of NEST bonus pool allocation ratio function checkDistributionTime() public view returns(uint256) { return _distributionTime; } // View the decay degree of NEST bonus pool allocation ratio function checkDistributionSpan() public view returns(uint256) { return _distributionSpan; } // Modify the highest NEST bonus pool allocation ratio function changeMostDistribution(uint256 num) public onlyOwner { _mostDistribution = num; } // Modify the lowest NEST bonus pool allocation ratio function changeLeastDistribution(uint256 num) public onlyOwner { _leastDistribution = num; } // Modify the decay time interval of NEST bonus pool allocation ratio function changeDistributionTime(uint256 num) public onlyOwner { _distributionTime = num; } // Modify the decay degree of NEST bonus pool allocation ratio function changeDistributionSpan(uint256 num) public onlyOwner { _distributionSpan = num; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Only bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Leveling contract * @dev ETH transfer in and transfer out */ contract Nest_3_Leveling { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Vote contract mapping (address => uint256) ethMapping; // Corresponded ETH leveling ledger of token /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Modifying voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Transfer out leveling * @param amount Transfer-out amount * @param token Corresponding lock-up token * @param target Transfer-out target */ function tranEth(uint256 amount, address token, address target) public returns (uint256) { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.v3.tokenAbonus")), "No authority"); uint256 tranAmount = amount; if (tranAmount > ethMapping[token]) { tranAmount = ethMapping[token]; } ethMapping[token] = ethMapping[token].sub(tranAmount); address payable addr = target.make_payable(); addr.transfer(tranAmount); return tranAmount; } /** * @dev Transfer in leveling * @param token Corresponded locked token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } // Check the leveled amount corresponding to the token function checkEthMapping(address token) public view returns (uint256) { return ethMapping[token]; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Offering contract * @dev Offering logic and mining logic */ contract Nest_NToken_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; // Offering data structure struct Nest_NToken_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_NToken_OfferPriceData [] _prices; // Array used to save offers Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // nestToken Nest_3_Abonus _abonus; // Bonus pool uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint256 _ownerMining = 5; // Creator ratio uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount uint32 _blockLimit = 25; // Block interval upper limit uint256 _blockAttenuation = 2400000; // Block decay interval mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount uint256[10] _attenuationAmount; // Mining decay list // Log token contract address event OfferTokenContractAddress(address contractAddress); // Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); // Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); // Log current block, current block mined amount, token address event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress); // Log offering block, token address, token offered times event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes); /** * Initialization method * @param voteFactory Voting contract address **/ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); uint256 blockAmount = 4 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * Reset voting contract method * @param voteFactory Voting contract address **/ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); } /** * Offering method * @param ethAmount ETH amount * @param erc20Amount Erc20 token amount * @param erc20Address Erc20 token address **/ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address); require(nTokenAddress != address(0x0)); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); _abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress); // Mining if (_blockOfferAmount[block.number][erc20Address] == 0) { uint256 miningAmount = oreDrawing(nTokenAddress); Nest_NToken nToken = Nest_NToken(nTokenAddress); nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100)); _blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100)); } _blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address **/ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } /** * Withdraw offer assets * @param contractAddress Offer address **/ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner); offerPriceData.serviceCharge = 0; } } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * Offering mining * @param ntoken NToken address **/ function oreDrawing(address ntoken) private returns(uint256) { Nest_NToken miningToken = Nest_NToken(ntoken); (uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo(); uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); miningToken.increaseTotal(miningAmount); emit OreDrawingLog(block.number, miningAmount, ntoken); return miningAmount; } /** * Retrieve mining * @param token Token address **/ function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { // Block mining amount*offer fee/block offer fee uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); // Transfer NToken Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token))); require(nToken.transfer(address(owner), miningAmount), "Transfer failure"); emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]); return miningAmount; } // Compare order prices function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Check contract status function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint256) { return _blockLimit; } // View taker fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View minimum offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View block offering amount function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) { return _blockOfferAmount[blockNum][token]; } // View offering block mining amount function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) { return _blockMining[blockNum][token]; } // View offering mining amount function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); } } // View the owner allocation ratio function checkOwnerMining() public view returns(uint256) { return _ownerMining; } // View the mining decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Modify taker order fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify block interval upper limit function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _leastEth = num; } // Modify offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _offerSpan = num; } // Modify price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } // Modify the owner allocation ratio function changeOwnerMining(uint256 num) public onlyOwner { _ownerMining = num; } // Modify the mining decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_NToken_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form, write the string into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } } /** * @title Auction NToken contract * @dev Auction for listing and generating NToken */ contract Nest_NToken_TokenAuction { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // NestToken Nest_3_OfferPrice _offerPrice; // Price contract address _destructionAddress; // Destruction contract address uint256 _duration = 5 days; // Auction duration uint256 _minimumNest = 100000 ether; // Minimum auction amount uint256 _tokenNum = 1; // Auction token number uint256 _incentiveRatio = 50; // Incentive ratio uint256 _minimumInterval = 10000 ether; // Minimum auction interval mapping(address => AuctionInfo) _auctionList; // Auction list mapping(address => bool) _tokenBlackList; // Auction blacklist struct AuctionInfo { uint256 endTime; // End time uint256 auctionValue; // Auction price address latestAddress; // Highest auctioneer uint256 latestAmount; // Lastest auction amount } address[] _allAuction; // Auction list array /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Initiating auction * @param token Auction token address * @param auctionAmount Initial auction amount */ function startAnAuction(address token, uint256 auctionAmount) public { require(_tokenMapping.checkTokenMapping(token) == address(0x0), "Token already exists"); require(_auctionList[token].endTime == 0, "Token is on sale"); require(auctionAmount >= _minimumNest, "AuctionAmount less than the minimum auction amount"); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(!_tokenBlackList[token]); // Verification ERC20 tokenERC20 = ERC20(token); tokenERC20.safeTransferFrom(address(msg.sender), address(this), 1); require(tokenERC20.balanceOf(address(this)) >= 1); tokenERC20.safeTransfer(address(msg.sender), 1); AuctionInfo memory thisAuction = AuctionInfo(now.add(_duration), auctionAmount, address(msg.sender), auctionAmount); _auctionList[token] = thisAuction; _allAuction.push(token); } /** * @dev Auction * @param token Auction token address * @param auctionAmount Auction amount */ function continueAuction(address token, uint256 auctionAmount) public { require(now <= _auctionList[token].endTime && _auctionList[token].endTime != 0, "Auction closed"); require(auctionAmount > _auctionList[token].auctionValue, "Insufficient auction amount"); uint256 subAuctionAmount = auctionAmount.sub(_auctionList[token].auctionValue); require(subAuctionAmount >= _minimumInterval); uint256 excitation = subAuctionAmount.mul(_incentiveRatio).div(100); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(_nestToken.transfer(_auctionList[token].latestAddress, _auctionList[token].auctionValue.add(excitation)), "Transfer failure"); // Update auction information _auctionList[token].auctionValue = auctionAmount; _auctionList[token].latestAddress = address(msg.sender); _auctionList[token].latestAmount = _auctionList[token].latestAmount.add(subAuctionAmount.sub(excitation)); } /** * @dev Listing * @param token Auction token address */ function auctionSuccess(address token) public { Nest_3_TokenAbonus nestAbonus = Nest_3_TokenAbonus(payable(_voteFactory.checkAddress("nest.v3.tokenAbonus"))); uint256 nowTime = now; uint256 nextTime = nestAbonus.getNextTime(); uint256 timeLimit = nestAbonus.checkTimeLimit(); uint256 getAbonusTimeLimit = nestAbonus.checkGetAbonusTimeLimit(); require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(getAbonusTimeLimit)), "Not time to auctionSuccess"); require(nowTime > _auctionList[token].endTime && _auctionList[token].endTime != 0, "Token is on sale"); // Initialize NToken Nest_NToken nToken = new Nest_NToken(strConcat("NToken", getAddressStr(_tokenNum)), strConcat("N", getAddressStr(_tokenNum)), address(_voteFactory), address(_auctionList[token].latestAddress)); // Auction NEST destruction require(_nestToken.transfer(_destructionAddress, _auctionList[token].latestAmount), "Transfer failure"); // Add NToken mapping _tokenMapping.addTokenMapping(token, address(nToken)); // Initialize charging parameters _offerPrice.addPriceCost(token); _tokenNum = _tokenNum.add(1); } function strConcat(string memory _a, string memory _b) public pure returns (string memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++) { bret[k++] = _ba[i]; } for (uint i = 0; i < _bb.length; i++) { bret[k++] = _bb[i]; } return string(ret); } // Convert to 4-digit string function getAddressStr(uint256 iv) public pure returns (string memory) { bytes memory buf = new bytes(64); uint256 index = 0; do { buf[index++] = byte(uint8(iv % 10 + 48)); iv /= 10; } while (iv > 0 || index < 4); bytes memory str = new bytes(index); for(uint256 i = 0; i < index; ++i) { str[i] = buf[index - i - 1]; } return string(str); } // Check auction duration function checkDuration() public view returns(uint256) { return _duration; } // Check minimum auction amount function checkMinimumNest() public view returns(uint256) { return _minimumNest; } // Check initiated number of auction tokens function checkAllAuctionLength() public view returns(uint256) { return _allAuction.length; } // View auctioned token addresses function checkAuctionTokenAddress(uint256 num) public view returns(address) { return _allAuction[num]; } // View auction blacklist function checkTokenBlackList(address token) public view returns(bool) { return _tokenBlackList[token]; } // View auction token information function checkAuctionInfo(address token) public view returns(uint256 endTime, uint256 auctionValue, address latestAddress) { AuctionInfo memory info = _auctionList[token]; return (info.endTime, info.auctionValue, info.latestAddress); } // View token number function checkTokenNum() public view returns (uint256) { return _tokenNum; } // Modify auction duration function changeDuration(uint256 num) public onlyOwner { _duration = num.mul(1 days); } // Modify minimum auction amount function changeMinimumNest(uint256 num) public onlyOwner { _minimumNest = num; } // Modify auction blacklist function changeTokenBlackList(address token, bool isBlack) public onlyOwner { _tokenBlackList[token] = isBlack; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } contract Nest_NToken is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; // Balance ledger mapping (address => mapping (address => uint256)) private _allowed; // Approval ledger uint256 private _totalSupply = 0 ether; // Total supply string public name; // Token name string public symbol; // Token symbol uint8 public decimals = 18; // Precision uint256 public _createBlock; // Create block number uint256 public _recentlyUsedBlock; // Recently used block number Nest_3_VoteFactory _voteFactory; // Voting factory contract address _bidder; // Owner /** * @dev Initialization method * @param _name Token name * @param _symbol Token symbol * @param voteFactory Voting factory contract address * @param bidder Successful bidder address */ constructor (string memory _name, string memory _symbol, address voteFactory, address bidder) public { name = _name; symbol = _symbol; _createBlock = block.number; _recentlyUsedBlock = block.number; _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _bidder = bidder; } /** * @dev Reset voting contract method * @param voteFactory Voting contract address */ function changeMapping (address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Additional issuance * @param value Additional issuance amount */ function increaseTotal(uint256 value) public { address offerMain = address(_voteFactory.checkAddress("nest.nToken.offerMain")); require(address(msg.sender) == offerMain, "No authority"); _balances[offerMain] = _balances[offerMain].add(value); _totalSupply = _totalSupply.add(value); _recentlyUsedBlock = block.number; } /** * @dev Check the total amount of tokens * @return Total supply */ function totalSupply() override public view returns (uint256) { return _totalSupply; } /** * @dev Check address balance * @param owner Address to be checked * @return Return the balance of the corresponding address */ function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } /** * @dev Check block information * @return createBlock Initial block number * @return recentlyUsedBlock Recently mined and issued block */ function checkBlockInfo() public view returns(uint256 createBlock, uint256 recentlyUsedBlock) { return (_createBlock, _recentlyUsedBlock); } /** * @dev Check owner's approved allowance to the spender * @param owner Approving address * @param spender Approved address * @return Approved amount */ function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount * @return Whether the transfer is successful */ function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approval method * @param spender Approval target * @param value Approval amount * @return Whether the approval is successful */ function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens when approved * @param from Transfer-out account address * @param to Transfer-in account address * @param value Transfer amount * @return Whether approved transfer is successful */ function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the allowance * @param spender Approval target * @param addedValue Amount to increase * @return whether increase is successful */ 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 allowance * @param spender Approval target * @param subtractedValue Amount to decrease * @return Whether decrease is successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount */ function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Check the creator * @return Creator address */ function checkBidder() public view returns(address) { return _bidder; } /** * @dev Transfer creator * @param bidder New creator address */ function changeBidder(address bidder) public { require(address(msg.sender) == _bidder); _bidder = bidder; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender)); _; } } /** * @title NToken mapping contract * @dev Add, modify and check offering token mapping */ contract Nest_NToken_TokenMapping { mapping (address => address) _tokenMapping; // Token mapping - offering token => NToken Nest_3_VoteFactory _voteFactory; // Voting contract event TokenMappingLog(address token, address nToken); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Reset voting contract * @param voteFactory voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Add token mapping * @param token Offering token address * @param nToken Mining NToken address */ function addTokenMapping(address token, address nToken) public { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.nToken.tokenAuction")), "No authority"); require(_tokenMapping[token] == address(0x0), "Token already exists"); _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Change token mapping * @param token Offering token address * @param nToken Mining NToken address */ function changeTokenMapping(address token, address nToken) public onlyOwner { _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Check token mapping * @param token Offering token address * @return Mining NToken address */ function checkTokenMapping(address token) public view returns (address) { return _tokenMapping[token]; } // Only for administrator modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } }
* @dev Check token mapping @param token Offering token address @return Mining NToken address/
function checkTokenMapping(address token) public view returns (address) { return _tokenMapping[token]; }
12,580,520
[ 1, 1564, 1147, 2874, 225, 1147, 25753, 310, 1147, 1758, 327, 5444, 310, 423, 1345, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 1345, 3233, 12, 2867, 1147, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 2316, 3233, 63, 2316, 15533, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0xFc29813Beeb3c7395C7A5f8dfC3352491D5ea0E2/sources/contracts/burnredeem/ERC1155BurnRedeem.sol
* See {IBurnRedeemCore-getBurnRedeemForToken}./
function getBurnRedeemForToken(address creatorContractAddress, uint256 tokenId) external override view returns(uint256 instanceId, BurnRedeem memory burnRedeem) { instanceId = _getRedeemInstanceId(creatorContractAddress, tokenId); burnRedeem = _burnRedeems[creatorContractAddress][instanceId]; }
16,794,515
[ 1, 9704, 288, 13450, 321, 426, 24903, 4670, 17, 588, 38, 321, 426, 24903, 1290, 1345, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2882, 321, 426, 24903, 1290, 1345, 12, 2867, 11784, 8924, 1887, 16, 2254, 5034, 1147, 548, 13, 3903, 3849, 1476, 1135, 12, 11890, 5034, 17608, 16, 605, 321, 426, 24903, 3778, 18305, 426, 24903, 13, 288, 203, 3639, 17608, 273, 389, 588, 426, 24903, 15327, 12, 20394, 8924, 1887, 16, 1147, 548, 1769, 203, 3639, 18305, 426, 24903, 273, 389, 70, 321, 426, 323, 7424, 63, 20394, 8924, 1887, 6362, 1336, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; import "./library/acl.sol"; import "./library/SafeMath.sol"; /** * censensus interface */ interface Consensus { function getValidatorBlockInfo(address validatorAddress) external view returns(uint, uint, uint); } /** * @dev This contract is designed to support Validator Committee on asimov website */ contract ValidatorCommittee is ACL { /// delegate contract address address constant delegateAddr = 0x63000000000000000000000000000000000000006b; /// initialized or not bool private initialized; /// proposal type - for now there is one type which is to add a new asset as transaction fee enum ProposalType {CONFIRM_ASSETS_FOR_FEE} /// proposal status enum ProposalStatus {ONGOING, APPROVED, REJECTED} /// validator structure struct Validator { /// number of blocks plan to produce uint plannedBlocks; /// number of blocks actually produced uint actualBlocks; /// efficiency = actualBlocks / plannedBlocks uint efficiency; /// proposals made by the validator uint[] proposalIds; /// proposals voted /// proposalId => bool mapping(uint => bool) votedProposals; /// existed or not bool existed; } /// proposal structure struct Proposal { address proposer; address[] voters; address[] approvers; address[] rejecters; uint whichRound; uint percent; uint asset; /// height start to take effect uint effectHeight; uint endHeight; mapping(address => bool) voterRight; ProposalType proposalType; ProposalStatus status; bool existed; } /// asset structure struct AssetFee { uint asset; /// height start to take effect uint effectHeight; bool existed; } /// adress => Validator mapping(address => Validator) validators; /// proposal id => Proposal mapping(uint => Proposal) proposals; /// asset => AssetFee mapping(uint => AssetFee) assetFees; /// address => bool mapping(address => bool) signupValidatorsCheck; /// address => bool mapping(address => bool) chosenValidatorsCheck; /// asset => proposal id mapping(uint => uint) ongoingAssetProposalIds; /// signed up validators address[] signupValidators; /// validators chosen by ranking address[] chosenValidators; /// addresses allowed to start new round - for now only contains the censensus system contract address[] authStartNewRoundAddresses; /// assets accepted by validators as transaction fee uint[] assets; /// consensus system contract Consensus consensus; /// proposal index, auto incremental uint private proposalIndex; /// round in committee, note this round means the term length of validator committee instead of "round" in censensus uint private round; /// block height when last update happened uint private lastUpdatedHeight; /// round length calculated in blocks uint private ROUND_LENGTH; /// proposal length calculated in blocks uint private PROPOSAL_LENGTH; /// minimal blocks to produce if a validator wants to signup for committee uint private MINIMAL_SIGNUP_BLOCKS; /// minimal validators required in the committee uint private MINIMAL_VALIDATORS_COUNT; /// maximum validators allowed in the committee uint private MAXIMUM_VALIDATORS_COUNT; /// extra blocks needed for a new asset to take effect uint private MULTI_ASSET_PROPOSAL_EFFECT_HEIGHT; /// maximum assets allowed as transaction fee uint private MAXIMUM_ASSET_PROPOSAL_COUNT; event SignupCommitteeEvent(uint round, address validator); event StartCommitteeProposalEvent(uint round, uint proposalId, address proposer, ProposalType proposalType, ProposalStatus status, uint endTime); event ProposalVotersEvent(uint round, uint proposalId, address[] voters); event VoteForCommitteeEvent(uint round, uint proposalId, address voter, bool decision); event CommitteeProposalStatusChangeEvent(uint round, uint proposalId, ProposalStatus status, uint supportRate, uint rejectRate); event NewRoundEvent(uint round, uint startTime, uint endTime, address[] validators); event MultiAssetProposalEffectHeightEvent(uint round, uint proposalId, uint workHeight); event UpdateRoundBlockInfoEvent(uint round, address[] validators, uint[] plannedBlocks, uint[] actualBlocks); function init(address[] _validators) public { require(!initialized, "it is not allowed to init more than once"); for (uint i = 0; i < _validators.length; i++) { Validator storage validator = validators[_validators[i]]; validator.existed = true; chosenValidatorsCheck[_validators[i]] = true; } chosenValidators = _validators; consensus = Consensus(0x63000000000000000000000000000000000000006a); authStartNewRoundAddresses.push(0x63000000000000000000000000000000000000006a); round = 1; lastUpdatedHeight = block.number; /// round length 30 days ROUND_LENGTH = SafeMath.mul(SafeMath.mul(30, 24), 720); MINIMAL_SIGNUP_BLOCKS = 10; MINIMAL_VALIDATORS_COUNT = 5; MAXIMUM_VALIDATORS_COUNT = 99; /// proposal length 7 days PROPOSAL_LENGTH = SafeMath.div(SafeMath.mul(ROUND_LENGTH, 7), 30); MULTI_ASSET_PROPOSAL_EFFECT_HEIGHT = 500; MAXIMUM_ASSET_PROPOSAL_COUNT = 99; initialized = true; } /** * @dev sign up for validator committee */ function signup() public { require(!signupValidatorsCheck[msg.sender], "already signed up"); uint plannedBlocks; uint actualBlocks; uint efficiency; (plannedBlocks, actualBlocks, efficiency) = consensus.getValidatorBlockInfo(msg.sender); require(actualBlocks >= MINIMAL_SIGNUP_BLOCKS, "not enough blocks produced"); Validator storage validator = validators[msg.sender]; validator.plannedBlocks = plannedBlocks; validator.actualBlocks = actualBlocks; validator.efficiency = efficiency; validator.existed = true; signupValidatorsCheck[msg.sender] = true; signupValidators.push(msg.sender); emit SignupCommitteeEvent(round, msg.sender); } /** * @dev start a new round. * * @param validatorAddresses validator addresses * @param plannedBlocks blocks planned to produce by each validator * @param actualBlocks blocks actually produced by each validator */ function startNewRound(address[] validatorAddresses, uint[] plannedBlocks, uint[] actualBlocks) public authAddresses(authStartNewRoundAddresses) { updateValidatorsBlockInfo(validatorAddresses, plannedBlocks, actualBlocks); /// whether it is time to start a new round if (SafeMath.sub(block.number, lastUpdatedHeight) >= ROUND_LENGTH) { uint length = signupValidators.length; address[] memory tempValidators = signupValidators; if (length >= MINIMAL_VALIDATORS_COUNT) { /// empty validators of last round for (uint i = 0; i < chosenValidators.length; i++) { delete chosenValidatorsCheck[chosenValidators[i]]; } delete chosenValidators; /// if there are more than 99 signups, we need to sort /// sort priority 1. blocks produced 2. efficiency if same number of blocks produced if (length > MAXIMUM_VALIDATORS_COUNT) { quickSortMemoryByActualBlocks(tempValidators, int(0), int(length-1)); } uint forloopLength = length > MAXIMUM_VALIDATORS_COUNT ? MAXIMUM_VALIDATORS_COUNT : length; for (uint j = 0; j < forloopLength; j++) { chosenValidators.push(tempValidators[j]); chosenValidatorsCheck[tempValidators[j]] = true; } } /// empty sign up information for (uint k = 0; k < length; k++) { delete signupValidatorsCheck[signupValidators[k]]; } delete signupValidators; round++; lastUpdatedHeight = block.number; emit NewRoundEvent(round, block.timestamp, SafeMath.add(block.timestamp, ROUND_LENGTH*5), chosenValidators); } } /// update block information function updateValidatorsBlockInfo(address[] validatorAddresses, uint[] plannedBlocks, uint[] actualBlocks) internal { uint validatorLength = validatorAddresses.length; for (uint n = 0; n < validatorLength; n++) { Validator storage validator = validators[validatorAddresses[n]]; validator.plannedBlocks = SafeMath.add(validator.plannedBlocks, plannedBlocks[n]); validator.actualBlocks = SafeMath.add(validator.actualBlocks, actualBlocks[n]); validator.efficiency = SafeMath.div(SafeMath.mul(validator.actualBlocks, 100), validator.plannedBlocks); if (!validator.existed) { validator.existed = true; } } emit UpdateRoundBlockInfoEvent(round, validatorAddresses, plannedBlocks, actualBlocks); } /// quicksort signed up validators function quickSortMemoryByActualBlocks(address[] memory arr, int left, int right) private returns(address[]) { if (arr.length == 0) return; require(left >= 0 && right >= 0 && right >= left, "invalid params of left and right"); int i = left; int j = right; if (i == j) return; address pivot = arr[uint(left + (right - left) / 2)]; uint pivotValue = SafeMath.add(SafeMath.mul(validators[pivot].actualBlocks, 100), validators[pivot].efficiency); while (i <= j) { while (SafeMath.add(SafeMath.mul(validators[arr[uint(i)]].actualBlocks, 100), validators[arr[uint(i)]].efficiency) > pivotValue) i++; while (pivotValue > SafeMath.add(SafeMath.mul(validators[arr[uint(j)]].actualBlocks, 100), validators[arr[uint(j)]].efficiency)) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSortMemoryByActualBlocks(arr, left, j); if (i < right) quickSortMemoryByActualBlocks(arr, i, right); return arr; } /** * @dev make a proposal * * @param proposalType proposal type * @param asset asset * @return proposal id */ function startProposal(uint proposalType, uint asset) public returns(uint) { require(chosenValidatorsCheck[msg.sender], "not authorized"); require(proposalType == uint(ProposalType.CONFIRM_ASSETS_FOR_FEE), "invalid proposal type"); Validator storage validator = validators[msg.sender]; require(validator.existed, "not authorized"); proposalIndex = SafeMath.add(proposalIndex, 1); Proposal storage prop = proposals[proposalIndex]; prop.proposer = msg.sender; prop.voters = chosenValidators; prop.whichRound = round; prop.effectHeight = block.number; prop.endHeight = SafeMath.add(prop.effectHeight, PROPOSAL_LENGTH); prop.status = ProposalStatus.ONGOING; prop.existed = true; if (uint(ProposalType.CONFIRM_ASSETS_FOR_FEE) == proposalType) { require(!assetFees[asset].existed, "asset already existed"); require(asset & 0x10000000000000000 == 0, "only divisible asset can be proposed"); require(assets.length < MAXIMUM_ASSET_PROPOSAL_COUNT, "not allowed anymore"); require(!checkOngoingAssetProposal(asset), "asset is already proposed"); prop.percent = 80; prop.asset = asset; prop.proposalType = ProposalType.CONFIRM_ASSETS_FOR_FEE; ongoingAssetProposalIds[asset] = proposalIndex; } for (uint i = 0; i < prop.voters.length; i++) { prop.voterRight[prop.voters[i]] = true; } validator.proposalIds.push(proposalIndex); /// proposal length, calculated in blocks uint proposalTimeLength = SafeMath.div(SafeMath.mul(SafeMath.mul(ROUND_LENGTH, 5), 7), 30); emit StartCommitteeProposalEvent(round, proposalIndex, msg.sender, prop.proposalType, prop.status, SafeMath.add(block.timestamp, proposalTimeLength)); emit ProposalVotersEvent(round, proposalIndex, prop.voters); return proposalIndex; } /// check ongoing proposals to aviod proposing the same asset multiple times function checkOngoingAssetProposal(uint asset) internal view returns(bool) { uint proposalId = ongoingAssetProposalIds[asset]; Proposal storage prop = proposals[proposalId]; if (prop.existed && block.number < prop.endHeight && prop.status == ProposalStatus.ONGOING) { return true; } return false; } /** * @dev vote on a proposal * * @param proposalId proposal id * @param decision yes or no */ function vote(uint proposalId, bool decision) public { Proposal storage prop = proposals[proposalId]; require(prop.existed, "the proposal does not exist"); require(prop.whichRound == round, "invalid round value"); require(prop.endHeight >= block.number, "invalid vote height"); require(prop.status == ProposalStatus.ONGOING, "invalid proposal status"); require(prop.voterRight[msg.sender], "not authorized"); Validator storage voter = validators[msg.sender]; require(voter.existed, "not authorized"); require(!voter.votedProposals[proposalId], "already voted"); emit VoteForCommitteeEvent(round, proposalId, msg.sender, decision); if (decision) { prop.approvers.push(msg.sender); uint supportRate = SafeMath.div(SafeMath.mul(calVotersBlocks(prop.approvers), 100), calVotersBlocks(prop.voters)); if (supportRate >= prop.percent) { prop.status = ProposalStatus.APPROVED; if (ProposalType.CONFIRM_ASSETS_FOR_FEE == prop.proposalType) { AssetFee storage newAsset = assetFees[prop.asset]; newAsset.asset = prop.asset; newAsset.effectHeight = SafeMath.add(block.number, MULTI_ASSET_PROPOSAL_EFFECT_HEIGHT); newAsset.existed = true; assets.push(prop.asset); } emit CommitteeProposalStatusChangeEvent(round, proposalId, prop.status, supportRate, 0); emit MultiAssetProposalEffectHeightEvent(round, proposalId, newAsset.effectHeight); } } else { prop.rejecters.push(msg.sender); uint rejectPercent = SafeMath.div(SafeMath.mul(calVotersBlocks(prop.rejecters), 100), calVotersBlocks(prop.voters)); if (rejectPercent > SafeMath.sub(100, prop.percent)) { prop.status = ProposalStatus.REJECTED; emit CommitteeProposalStatusChangeEvent(round, proposalId, prop.status, 0, rejectPercent); } } voter.votedProposals[proposalId] = true; } /// calculate actual blocks produced by votors function calVotersBlocks(address[] voters) internal view returns(uint) { uint actualBlocks; uint length = voters.length; for (uint i = 0; i < length; i++) { actualBlocks = SafeMath.add(actualBlocks, validators[voters[i]].actualBlocks); } return actualBlocks; } /** * @dev get the list of assets accepted as transaction fee * * @return array of asset, array of effect height */ function getAssetFeeList() public view returns(uint[], uint[]) { uint length = assets.length; if (length == 0) { return (new uint[](0), new uint[](0)); } uint[] memory tempAssets = new uint[](length); uint[] memory tempHeights = new uint[](length); for (uint i = 0; i < length; i++) { AssetFee storage item = assetFees[assets[i]]; tempAssets[i] = item.asset; tempHeights[i] = item.effectHeight; } return (tempAssets, tempHeights); } /** * @dev get update block height of last round */ function getRoundLastUpdateHeight() public view returns(uint) { return lastUpdatedHeight; } }
delegate contract address initialized or not proposal type - for now there is one type which is to add a new asset as transaction fee
enum ProposalType {CONFIRM_ASSETS_FOR_FEE}
6,473,549
[ 1, 22216, 6835, 1758, 6454, 578, 486, 14708, 618, 300, 364, 2037, 1915, 353, 1245, 618, 1492, 353, 358, 527, 279, 394, 3310, 487, 2492, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 19945, 559, 288, 2248, 31324, 67, 3033, 28092, 67, 7473, 67, 8090, 41, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x352bBd0702A4B6275afA215a18cAeD517B378b0C/sources/contracts/PREZALE.sol
0.02% remaining finalize presale
if(presaleinfo2.totalRaised == presaleinfo.maxCapETH) {
4,533,114
[ 1, 20, 18, 3103, 9, 4463, 12409, 4075, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 13491, 309, 12, 12202, 5349, 1376, 22, 18, 4963, 12649, 5918, 422, 4075, 5349, 1376, 18, 1896, 4664, 1584, 44, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xE9F0a0a787CEEA82f1c8fE7A783826eBD181e707/sources/packages/contracts-core/contracts/XAppConnectionManager.sol
* @notice remove the domain from the two-way mapping @param _domain domain to un-enroll/
function _clearDomain(uint32 _domain) internal { address _currentReplica = domainToReplica[_domain]; if (_currentReplica != address(0)) { domainToReplica[_domain] = address(0); replicaToDomain[_currentReplica] = 0; emit ReplicaUnenrolled(_domain, _currentReplica); } }
15,740,815
[ 1, 4479, 326, 2461, 628, 326, 2795, 17, 1888, 2874, 225, 389, 4308, 2461, 358, 640, 17, 275, 2693, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8507, 3748, 12, 11890, 1578, 389, 4308, 13, 2713, 288, 203, 3639, 1758, 389, 2972, 14222, 273, 2461, 774, 14222, 63, 67, 4308, 15533, 203, 3639, 309, 261, 67, 2972, 14222, 480, 1758, 12, 20, 3719, 288, 203, 5411, 2461, 774, 14222, 63, 67, 4308, 65, 273, 1758, 12, 20, 1769, 203, 5411, 12335, 774, 3748, 63, 67, 2972, 14222, 65, 273, 374, 31, 203, 5411, 3626, 16928, 984, 12401, 1259, 24899, 4308, 16, 389, 2972, 14222, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * Implementation of the basic standard token * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract TokenERC20 { // [ERC20] the name of the token - e.g. "Vehicle Owner’s Benefit" string public name; // [ERC20] the symbol of the token. E.g. "VOB". string public symbol; // [ERC20] the total token supply uint256 public totalSupply; // [ERC20] the number of decimals the token uses - e.g. 18 uint8 public decimals = 18; // [ERC20] the account balance of another account with address _owner mapping (address => uint256) public balanceOf; // [ERC20]the amount which _spender is still allowed to withdraw from _owner. mapping(address => mapping(address => uint256)) allowance; mapping (address => uint256) public freezeOf; // [ERC20] MUST trigger when tokens are transferred, including zero value transfers. event Transfer(address indexed from, address indexed to, uint256 value); // [ERC20] MUST trigger on any successful call to approve event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); // This notifies clients about the amount frozen event Freeze(address indexed from, uint256 value); // This notifies clients about the amount unfrozen event Unfreeze(address indexed from, uint256 value); constructor(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimalUnits) public { totalSupply = _initialSupply; balanceOf[msg.sender] = totalSupply; name = _tokenName; symbol = _tokenSymbol; decimals = _decimalUnits; } /** * Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. */ function _transfer(address _from, address _to, uint256 _value) internal { // the _to account address is not invalid require(_to != 0x0); // the _from account balance has enough tokens to spend require(balanceOf[_from] >= _value); // the _to account balance must not be overflowing after transfer require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; // emit event emit Transfer(_from, _to, _value); } /** * [ERC20] * Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. * The function SHOULD throw if the _from account balance does not have enough tokens to spend. * * Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * [ERC20] * Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event. * The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. * This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. * The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism. * * Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowance[_from][msg.sender] >= _value); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * [ERC20] * Allows _spender to withdraw from your account multiple times, up to the _value amount. * If this function is called again it overwrites the current allowance with _value. * * NOTE: To prevent attack vectors like the one described here and discussed here, * clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. * THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before * */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function freeze(uint256 _value) returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] -= _value; // Subtract from the sender freezeOf[msg.sender] += _value; Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) returns (bool success) { require(freezeOf[msg.sender]>= _value); // Check if the sender has enough require(_value > 0); freezeOf[msg.sender] -= _value; // Subtract from the sender balanceOf[msg.sender] += _value; Unfreeze(msg.sender, _value); return true; } }
Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
1,080,587
[ 1, 1564, 309, 326, 5793, 711, 7304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 2398, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; import "./PermissionCreator.sol"; import "../common/Check.sol"; import "../../interaction/interface/IPermissionManagement.sol"; import "../../interaction/interface/IAuthorization.sol"; /// @title Permission management contract /// @author ["Rivtower Technologies <[email protected]>"] /// @notice The address: 0xffFffFffFFffFFFFFfFfFFfFFFFfffFFff020004 /// The interface the can be called: All /// @dev TODO check address is contract // contract PermissionManagement is ReservedAddress { contract PermissionManagement is IPermissionManagement, Check { PermissionCreator permissionCreator = PermissionCreator( permissionCreatorAddr ); IAuthorization auth = IAuthorization(authorizationAddr); event PermissionDeleted(address _permission); modifier sameLength(address[] _one, bytes4[] _other) { require(_one.length > 0, "The length must large than zero."); require( _one.length == _other.length, "Two arrays'length not the same." ); _; } modifier notBuiltInPermission(address _permission) { for (uint i = 0; i < builtInPermissions.length; i++) require( _permission != builtInPermissions[i], "not buildInPermission." ); _; } /// @notice Create a new permission /// @dev TODO Check the funcs belong the conts /// @param _name The name of permission /// @param _conts The contracts of resource /// @param _funcs The function signature of the resource /// @return New permission's address function newPermission(bytes32 _name, address[] _conts, bytes4[] _funcs) external hasPermission(builtInPermissions[0]) sameLength(_conts, _funcs) returns (address id) { return permissionCreator.createPermission(_name, _conts, _funcs); } /// @notice Delete the permission /// @param _permission The address of permission /// @return true if successed, otherwise false function deletePermission(address _permission) external hasPermission(builtInPermissions[1]) notBuiltInPermission(_permission) returns (bool) { Permission perm = Permission(_permission); perm.close(); // Cancel the auth of the accounts who have the permission require( auth.clearAuthOfPermission(_permission), "deletePermission failed." ); emit PermissionDeleted(_permission); return true; } /// @notice Update the permission name /// @param _permission The address of permission /// @param _name The new name /// @return true if successed, otherwise false function updatePermissionName(address _permission, bytes32 _name) external hasPermission(builtInPermissions[2]) returns (bool) { Permission perm = Permission(_permission); require(perm.updateName(_name), "updatePermissionName failed."); return true; } /// @notice Add the resources of permission /// @param _permission The address of permission /// @param _conts The contracts of resource /// @param _funcs The function signature of resource /// @return true if successed, otherwise false function addResources( address _permission, address[] _conts, bytes4[] _funcs ) external hasPermission(builtInPermissions[2]) returns (bool) { Permission perm = Permission(_permission); require(perm.addResources(_conts, _funcs), "addResources failed."); return true; } /// @notice Delete the resources of permission /// @param _permission The address of permission /// @param _conts The contracts of resource /// @param _funcs The function signature of resource /// @return true if successed, otherwise false function deleteResources( address _permission, address[] _conts, bytes4[] _funcs ) external hasPermission(builtInPermissions[2]) returns (bool) { Permission perm = Permission(_permission); require( perm.deleteResources(_conts, _funcs), "deleteResources failed." ); return true; } /// @notice Set multiple permissions to the account /// @param _account The account to be setted /// @param _permissions The multiple permissions to be setted /// @return true if successed, otherwise false function setAuthorizations(address _account, address[] _permissions) external hasPermission(builtInPermissions[3]) returns (bool) { for (uint i = 0; i < _permissions.length; i++) require( auth.setAuth(_account, _permissions[i]), "setAuthorizations failed." ); return true; } /// @notice Set permission to the account /// @param _account The account to be setted /// @param _permission The permission to be setted /// @return true if successed, otherwise false function setAuthorization(address _account, address _permission) external hasPermission(builtInPermissions[3]) returns (bool) { require( auth.setAuth(_account, _permission), "setAuthorization failed." ); return true; } /// @notice Cancel the account's muliple permissions /// @param _account The account to be canceled /// @param _permissions The multiple permissions to be canceled /// @return true if successed, otherwise false function cancelAuthorizations(address _account, address[] _permissions) external hasPermission(builtInPermissions[4]) returns (bool) { for (uint i = 0; i < _permissions.length; i++) require( auth.cancelAuth(_account, _permissions[i]), "cancelAuthorizations failed." ); return true; } /// @notice Cancel the account's permission /// @param _account The account to be canceled /// @param _permission The permission to be canceled /// @return true if successed, otherwise false function cancelAuthorization(address _account, address _permission) external hasPermission(builtInPermissions[4]) returns (bool) { require( auth.cancelAuth(_account, _permission), "cancelAuthorization failed." ); return true; } /// @notice Clear the account's permissions /// @param _account The account to be cleared /// @return true if successed, otherwise false function clearAuthorization(address _account) external hasPermission(builtInPermissions[4]) returns (bool) { require(auth.clearAuth(_account), "clearAuthorization failed."); return true; } }
@notice Update the permission name @param _permission The address of permission @param _name The new name @return true if successed, otherwise false
function updatePermissionName(address _permission, bytes32 _name) external hasPermission(builtInPermissions[2]) returns (bool) { Permission perm = Permission(_permission); require(perm.updateName(_name), "updatePermissionName failed."); return true; }
6,398,583
[ 1, 1891, 326, 4132, 508, 225, 389, 9827, 1021, 1758, 434, 4132, 225, 389, 529, 1021, 394, 508, 327, 638, 309, 8667, 3692, 16, 3541, 629, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 5041, 461, 12, 2867, 389, 9827, 16, 1731, 1578, 389, 529, 13, 203, 3639, 3903, 203, 3639, 26097, 12, 12406, 382, 6521, 63, 22, 5717, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 8509, 4641, 273, 8509, 24899, 9827, 1769, 203, 3639, 2583, 12, 12160, 18, 2725, 461, 24899, 529, 3631, 315, 2725, 5041, 461, 2535, 1199, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA3D1D966EfA6C99487eF1E0009a4D2F0AE3A4578/sources/new.sol
200 means 2% will send to charity
uint256 public ownerFee = 200;
4,910,702
[ 1, 6976, 4696, 576, 9, 903, 1366, 358, 1149, 560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 3410, 14667, 273, 4044, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x10614e4395AAc006ca0Ef4970d1412e8e921d911/sources/Users/obiedobo/Desktop/Code/apeswap-zap/contracts/extensions/pools/ApeSwapZapPools.sol
@notice Zap token into banana/gnana pool @param inputToken Input token to zap @param inputAmount Amount of input tokens to zap @param lpTokens Tokens of LP to zap to @param path0 Path from input token to LP token0 @param path1 Path from input token to LP token1 @param minAmountsSwap The minimum amount of output tokens that must be received for swap @param minAmountsLP AmountAMin and amountBMin for adding liquidity @param deadline Unix timestamp after which the transaction will revert @param pool Pool address
function zapLPPool( IERC20 inputToken, uint256 inputAmount, address[] calldata path0, address[] calldata path1, uint256 deadline, IBEP20RewardApeV5 pool ) external nonReentrant { IApePair pair = IApePair(address(pool.STAKE_TOKEN())); require( (lpTokens[0] == pair.token0() && lpTokens[1] == pair.token1()) || (lpTokens[1] == pair.token0() && lpTokens[0] == pair.token1()), "ApeSwapZap: Wrong LP pair for Pool" ); _zapInternal( inputToken, inputAmount, lpTokens, path0, path1, minAmountsSwap, minAmountsLP, address(this), deadline ); uint256 balance = pair.balanceOf(address(this)); pair.approve(address(pool), balance); pool.depositTo(balance, msg.sender); pair.approve(address(pool), 0); emit ZapLPPool(inputToken, inputAmount, pool); }
9,554,672
[ 1, 62, 438, 1147, 1368, 25732, 13848, 19, 1600, 13848, 2845, 225, 810, 1345, 2741, 1147, 358, 11419, 225, 810, 6275, 16811, 434, 810, 2430, 358, 11419, 225, 12423, 5157, 13899, 434, 511, 52, 358, 11419, 358, 225, 589, 20, 2666, 628, 810, 1147, 358, 511, 52, 1147, 20, 225, 589, 21, 2666, 628, 810, 1147, 358, 511, 52, 1147, 21, 225, 1131, 6275, 87, 12521, 1021, 5224, 3844, 434, 876, 2430, 716, 1297, 506, 5079, 364, 7720, 225, 1131, 6275, 87, 14461, 16811, 2192, 267, 471, 3844, 38, 2930, 364, 6534, 4501, 372, 24237, 225, 14096, 9480, 2858, 1839, 1492, 326, 2492, 903, 15226, 225, 2845, 8828, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11419, 14461, 2864, 12, 203, 3639, 467, 654, 39, 3462, 810, 1345, 16, 203, 3639, 2254, 5034, 810, 6275, 16, 203, 3639, 1758, 8526, 745, 892, 589, 20, 16, 203, 3639, 1758, 8526, 745, 892, 589, 21, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 467, 5948, 52, 3462, 17631, 1060, 37, 347, 58, 25, 2845, 203, 565, 262, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 467, 37, 347, 4154, 3082, 273, 467, 37, 347, 4154, 12, 2867, 12, 6011, 18, 882, 37, 6859, 67, 8412, 1435, 10019, 203, 3639, 2583, 12, 203, 5411, 261, 9953, 5157, 63, 20, 65, 422, 3082, 18, 2316, 20, 1435, 597, 203, 7734, 12423, 5157, 63, 21, 65, 422, 3082, 18, 2316, 21, 10756, 747, 203, 7734, 261, 9953, 5157, 63, 21, 65, 422, 3082, 18, 2316, 20, 1435, 597, 203, 10792, 12423, 5157, 63, 20, 65, 422, 3082, 18, 2316, 21, 1435, 3631, 203, 5411, 315, 37, 347, 12521, 62, 438, 30, 24668, 511, 52, 3082, 364, 8828, 6, 203, 3639, 11272, 203, 203, 3639, 389, 94, 438, 3061, 12, 203, 5411, 810, 1345, 16, 203, 5411, 810, 6275, 16, 203, 5411, 12423, 5157, 16, 203, 5411, 589, 20, 16, 203, 5411, 589, 21, 16, 203, 5411, 1131, 6275, 87, 12521, 16, 203, 5411, 1131, 6275, 87, 14461, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 14096, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 11013, 273, 3082, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 3082, 18, 12908, 537, 2 ]
./partial_match/3/0xa0e78aa76Da441C4bf73df0eB37e8c5C98282124/sources/POWH.sol
* @dev function to convert all dividend to collateral./ fetch dividends pay out the dividends virtually retrieve ref. bonus dispatch a buy order with the virtualized "withdrawn dividends" fire event
function reinvest(address contractAddress) public nonReentrant { require(contractAddressRecord[contractAddress] == true); require(walletAddressRecord[msg.sender] == true); address _customerAddress = msg.sender; balanceLedger[_customerAddress][contractAddress].payOut += (int256) (_dividends * magnitude); _dividends += balanceLedger[_customerAddress][contractAddress].referralBalance; balanceLedger[_customerAddress][contractAddress].referralBalance = 0; uint256 _collate = purchaseCollate(contractAddress, _dividends, address(0)); emit onReinvest(_customerAddress, contractAddress, _dividends, _collate); }
5,051,446
[ 1, 915, 358, 1765, 777, 31945, 358, 4508, 2045, 287, 18, 19, 2158, 3739, 350, 5839, 8843, 596, 326, 3739, 350, 5839, 331, 2714, 3452, 4614, 1278, 18, 324, 22889, 3435, 279, 30143, 1353, 598, 326, 5024, 1235, 315, 1918, 9446, 82, 3739, 350, 5839, 6, 4452, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 5768, 395, 12, 2867, 6835, 1887, 13, 1071, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 12, 16351, 1887, 2115, 63, 16351, 1887, 65, 422, 638, 1769, 203, 3639, 2583, 12, 19177, 1887, 2115, 63, 3576, 18, 15330, 65, 422, 638, 1769, 203, 540, 203, 540, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 11013, 28731, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 10239, 1182, 1011, 225, 261, 474, 5034, 13, 261, 67, 2892, 350, 5839, 380, 13463, 1769, 203, 540, 203, 3639, 389, 2892, 350, 5839, 1011, 11013, 28731, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 1734, 29084, 13937, 31, 203, 540, 203, 3639, 11013, 28731, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 1734, 29084, 13937, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 389, 12910, 340, 273, 23701, 13535, 340, 12, 16351, 1887, 16, 389, 2892, 350, 5839, 16, 1758, 12, 20, 10019, 203, 540, 203, 3639, 3626, 603, 426, 5768, 395, 24899, 10061, 1887, 16, 6835, 1887, 16, 389, 2892, 350, 5839, 16, 389, 12910, 340, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xa8df33a40fe2e3278e4d94a974f70778043fbd20 //Contract name: I2Presale //Balance: 5.845 Ether //Verification Date: 2/21/2018 //Transacion Count: 30 // CODE STARTS HERE pragma solidity ^0.4.18; interface token { function transfer(address receiver, uint amount) external; } /** * @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; } } contract I2Presale is Ownable { using SafeMath for uint256; address public beneficiary; uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price; uint public usd = 1000; uint public bonus; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Setup the owner */ function I2Presale ( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, // how many token units a buyer gets per dollar uint tokensPerDollar, // $0.1 = 10 // how many token units a buyer gets per wei // uint etherCostOfEachToken, uint bonusInPercent, address addressOfTokenUsedAsReward ) public { beneficiary = ifSuccessfulSendTo; // mean set 100-1000 ETH fundingGoal = fundingGoalInEthers.mul(1 ether); deadline = now.add(durationInMinutes.mul(1 minutes)); price = 10**18; price = price.div(tokensPerDollar).div(usd); // price = etherCostOfEachToken * 1 ether; // price = etherCostOfEachToken.mul(1 ether).div(1000).mul(usd); bonus = bonusInPercent; tokenReward = token(addressOfTokenUsedAsReward); } /** * Change Crowdsale bonus rate */ function changeBonus (uint _bonus) public onlyOwner { bonus = _bonus; } /** * Set USD/ETH rate in USD (1000) */ function setUSDPrice (uint _usd) public onlyOwner { usd = _usd; } /** * Finish Crowdsale in some reason like Goals Reached or etc */ function finshCrowdsale () public onlyOwner { deadline = now; crowdsaleClosed = true; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () public payable { require(beneficiary != address(0)); require(!crowdsaleClosed); require(msg.value != 0); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; // bonus in percent // msg.value.add(msg.value.mul(bonus).div(100)); uint tokensToSend = amount.div(price).mul(10**18); uint tokenToSendWithBonus = tokensToSend.add(tokensToSend.mul(bonus).div(100)); tokenReward.transfer(msg.sender, tokenToSendWithBonus); FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= deadline) _; } /** * Check if goal was reached * * Checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() public afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(beneficiary, amountRaised); } crowdsaleClosed = true; } /** * Withdraw the funds * * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached, * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundTransfer(msg.sender, amount, false); } else { balanceOf[msg.sender] = amount; } } } if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { FundTransfer(beneficiary, amountRaised, false); } else { //If we fail to send the funds to beneficiary, unlock funders balance fundingGoalReached = false; } } } } /** * @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; } }
* Finish Crowdsale in some reason like Goals Reached or etc/
function finshCrowdsale () public onlyOwner { deadline = now; crowdsaleClosed = true; }
1,811,492
[ 1, 11641, 385, 492, 2377, 5349, 316, 2690, 3971, 3007, 4220, 1031, 868, 2004, 578, 5527, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 574, 674, 39, 492, 2377, 5349, 1832, 1071, 1338, 5541, 288, 203, 3639, 14096, 273, 2037, 31, 203, 3639, 276, 492, 2377, 5349, 7395, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8761b55aF5A703d5855F1865dB8fE4DD18E94c53/sources/contracts/SyntheticNouns.sol
The Nouns token URI descriptor ENS reverse records contract The noun seeds Addresses that have claimed a noun Claimer of each noun The internal noun ID tracker
contract SyntheticNouns is ERC721 { using Strings for uint256; using Strings for address; event NounCreated(uint256 indexed tokenId, INounsSeeder.Seed seed); INounsDescriptor public descriptor; IENSReverseRecords public reverseRecords; mapping(uint256 => INounsSeeder.Seed) public seeds; mapping(address => bool) public claimed; mapping(uint256 => address) public claimerOf; uint256 private _currentNounId = 1; pragma solidity ^0.8.0; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { Strings } from "@openzeppelin/contracts/utils/Strings.sol"; import { INounsDescriptor } from "./interfaces/INounsDescriptor.sol"; import { INounsSeeder } from "./interfaces/INounsSeeder.sol"; import { IENSReverseRecords } from "./interfaces/IENSReverseRecords.sol"; constructor(INounsDescriptor _descriptor, IENSReverseRecords _reverseRecords) ERC721("Synthetic Nouns", "sNOUN") { descriptor = _descriptor; reverseRecords = _reverseRecords; } function generateSeed(uint256 _pseudorandomness) private view returns (INounsSeeder.Seed memory) { uint256 backgroundCount = descriptor.backgroundCount(); uint256 bodyCount = descriptor.bodyCount(); uint256 accessoryCount = descriptor.accessoryCount(); uint256 headCount = descriptor.headCount(); uint256 glassesCount = descriptor.glassesCount(); return INounsSeeder.Seed({ background: uint48( uint48(_pseudorandomness) % backgroundCount ), body: uint48( uint48(_pseudorandomness >> 48) % bodyCount ), accessory: uint48( uint48(_pseudorandomness >> 96) % accessoryCount ), head: uint48( uint48(_pseudorandomness >> 144) % headCount ), glasses: uint48( uint48(_pseudorandomness >> 192) % glassesCount ) }); } function generateSeed(uint256 _pseudorandomness) private view returns (INounsSeeder.Seed memory) { uint256 backgroundCount = descriptor.backgroundCount(); uint256 bodyCount = descriptor.bodyCount(); uint256 accessoryCount = descriptor.accessoryCount(); uint256 headCount = descriptor.headCount(); uint256 glassesCount = descriptor.glassesCount(); return INounsSeeder.Seed({ background: uint48( uint48(_pseudorandomness) % backgroundCount ), body: uint48( uint48(_pseudorandomness >> 48) % bodyCount ), accessory: uint48( uint48(_pseudorandomness >> 96) % accessoryCount ), head: uint48( uint48(_pseudorandomness >> 144) % headCount ), glasses: uint48( uint48(_pseudorandomness >> 192) % glassesCount ) }); } function getSeedInput(address _address) public pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_address))); } function claim() public returns (uint256) { require(!claimed[msg.sender], "Noun already claimed"); claimed[msg.sender] = true; uint256 tokenId = _currentNounId++; claimerOf[tokenId] = msg.sender; return _mintTo(msg.sender, tokenId); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "NounsToken: URI query for nonexistent token"); string memory nounId = _tokenId.toString(); string memory name = string(abi.encodePacked("Synthetic Noun ", nounId)); string memory ensName = _reverseName(claimerOf[_tokenId]); string memory addressOrENS = bytes(ensName).length == 0 ? claimerOf[_tokenId].toHexString() : ensName; string memory description = string( abi.encodePacked( "Synthetic Noun ", nounId, " claimed by address, ", addressOrENS, ", is a member of the Synthetic Nouns DAO" ) ); return descriptor.genericDataURI(name, description, seeds[_tokenId]); } function addressPreview(address _address) public view returns (string memory) { return descriptor.generateSVGImage(generateSeed(getSeedInput(_address))); } function _mintTo(address _to, uint256 _nounId) internal returns (uint256) { INounsSeeder.Seed memory seed = seeds[_nounId] = generateSeed(getSeedInput(_to)); _mint(_to, _nounId); emit NounCreated(_nounId, seed); return _nounId; } function _reverseName(address _address) internal view returns (string memory name) { address[] memory t = new address[](1); t[0] = _address; name = reverseRecords.getNames(t)[0]; } }
3,108,248
[ 1, 1986, 423, 465, 87, 1147, 3699, 4950, 512, 3156, 4219, 3853, 6835, 1021, 27771, 19076, 23443, 716, 1240, 7516, 329, 279, 27771, 3905, 69, 4417, 434, 1517, 27771, 1021, 2713, 27771, 1599, 9745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16091, 16466, 50, 465, 87, 353, 4232, 39, 27, 5340, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 8139, 364, 1758, 31, 203, 203, 565, 871, 423, 465, 6119, 12, 11890, 5034, 8808, 1147, 548, 16, 2120, 465, 87, 12702, 264, 18, 12702, 5009, 1769, 203, 203, 565, 2120, 465, 87, 3187, 1071, 4950, 31, 203, 203, 565, 467, 21951, 12650, 6499, 1071, 4219, 6499, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2120, 465, 87, 12702, 264, 18, 12702, 13, 1071, 19076, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 7516, 329, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 927, 69, 4417, 951, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 50, 465, 548, 273, 404, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 288, 4232, 39, 27, 5340, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 18, 18281, 14432, 203, 5666, 288, 8139, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 7957, 18, 18281, 14432, 203, 5666, 288, 2120, 465, 87, 3187, 289, 628, 25165, 15898, 19, 706, 465, 87, 3187, 18, 18281, 14432, 203, 5666, 288, 2120, 465, 87, 12702, 264, 289, 628, 25165, 15898, 19, 706, 465, 87, 12702, 264, 18, 18281, 14432, 203, 5666, 288, 467, 21951, 12650, 6499, 289, 628, 25165, 15898, 2 ]
./partial_match/1/0x4D4c8F2f30e0224889ab578283A844e10B57e0F8/sources/contracts/PancakeV3Pool.sol
@dev Get the pool's balance of token1 @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize check
function balance1() private view returns (uint256) { (bool success, bytes memory data) = token1.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)) ); require(success && data.length >= 32); return abi.decode(data, (uint256)); }
3,596,922
[ 1, 967, 326, 2845, 1807, 11013, 434, 1147, 21, 225, 1220, 445, 353, 16189, 15411, 358, 4543, 279, 19530, 1110, 7000, 554, 866, 316, 2719, 358, 326, 327, 13178, 554, 866, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 21, 1435, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 21, 18, 3845, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 45, 654, 39, 3462, 2930, 2840, 18, 12296, 951, 18, 9663, 16, 1758, 12, 2211, 3719, 203, 3639, 11272, 203, 3639, 2583, 12, 4768, 597, 501, 18, 2469, 1545, 3847, 1769, 203, 3639, 327, 24126, 18, 3922, 12, 892, 16, 261, 11890, 5034, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xc54f81ed1116c53d13776C419764F75cEfDe18F5/sources/SIPilotToken.sol
converts ETH to DAI refund leftover ETH to user
function convertEthToDai(uint daiAmount) public payable { uint deadline = block.timestamp + 15; address[] memory path = new address[](2); path[0] = _uniswapRouter.WETH(); path[1] = _daiToken; require(amts[0] > 0, "Exchange failed."); require(success, "refund failed"); }
5,089,191
[ 1, 6283, 87, 512, 2455, 358, 463, 18194, 16255, 29709, 512, 2455, 358, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1765, 41, 451, 774, 40, 10658, 12, 11890, 5248, 77, 6275, 13, 1071, 8843, 429, 288, 203, 3639, 2254, 14096, 273, 1203, 18, 5508, 397, 4711, 31, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 389, 318, 291, 91, 438, 8259, 18, 59, 1584, 44, 5621, 203, 3639, 589, 63, 21, 65, 273, 389, 2414, 77, 1345, 31, 203, 203, 3639, 2583, 12, 301, 3428, 63, 20, 65, 405, 374, 16, 315, 11688, 2535, 1199, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 1734, 1074, 2535, 8863, 203, 565, 289, 203, 21281, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
@dev Reads the int112 at `rdPtr` in returndata.
function readInt112( ReturndataPointer rdPtr ) internal pure returns (int112 value) { assembly { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
3,218,541
[ 1, 7483, 326, 509, 17666, 622, 1375, 13623, 5263, 68, 316, 327, 892, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 13731, 17666, 12, 203, 565, 2000, 892, 4926, 9437, 5263, 203, 225, 262, 2713, 16618, 1135, 261, 474, 17666, 460, 13, 288, 203, 565, 19931, 288, 203, 1377, 327, 892, 3530, 12, 20, 16, 9437, 5263, 16, 389, 3335, 3944, 13, 203, 1377, 460, 519, 312, 945, 12, 20, 13, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/288/0xBf977E734C24474f28282028C36F0863F4B1b49A/sources/contracts/BaseJumpRateModelV2.sol
* @title Logic for Compound's JumpRateModel Contract V2. @author Compound (modified by Dharma Labs, refactored by Arr00) @notice Version 2 modifies Version 1 by enabling updateable parameters./
contract BaseJumpRateModelV2 { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); address public owner; uint public multiplierPerBlock; uint public baseRatePerBlock; uint public jumpMultiplierPerBlock; uint public kink; constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) internal { owner = owner_; updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) external { require(msg.sender == owner, "only the owner may call this function."); updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } function updateBlocksPerYear(uint blocksPerYear_) external { require(msg.sender == owner, "only the owner may call this function."); blocksPerYear = blocksPerYear_; } function transferOwnership(address owner_) external { require(owner_ != address(0), "new owner is the zero address."); require(msg.sender == owner, "only the owner may call this function."); owner = owner_; } function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } function getBorrowRateInternal(uint cash, uint borrows, uint reserves) internal view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } function getBorrowRateInternal(uint cash, uint borrows, uint reserves) internal view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } } else { function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRateInternal(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) internal { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_)); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } }
16,905,481
[ 1, 20556, 364, 21327, 1807, 804, 2801, 4727, 1488, 13456, 776, 22, 18, 225, 21327, 261, 7342, 635, 463, 30250, 2540, 511, 5113, 16, 283, 3493, 7653, 635, 10371, 713, 13, 225, 4049, 576, 23934, 4049, 404, 635, 570, 17912, 1089, 429, 1472, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3360, 26743, 4727, 1488, 58, 22, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 871, 1166, 29281, 1370, 12, 11890, 1026, 4727, 2173, 1768, 16, 2254, 15027, 2173, 1768, 16, 2254, 11833, 23365, 2173, 1768, 16, 2254, 417, 754, 1769, 203, 203, 565, 1758, 1071, 3410, 31, 203, 203, 203, 565, 2254, 1071, 15027, 2173, 1768, 31, 203, 203, 565, 2254, 1071, 1026, 4727, 2173, 1768, 31, 203, 203, 565, 2254, 1071, 11833, 23365, 2173, 1768, 31, 203, 203, 565, 2254, 1071, 417, 754, 31, 203, 203, 565, 3885, 12, 11890, 1026, 4727, 2173, 5593, 16, 2254, 15027, 2173, 5593, 16, 2254, 11833, 23365, 2173, 5593, 16, 2254, 417, 754, 67, 16, 1758, 3410, 67, 13, 2713, 288, 203, 3639, 3410, 273, 3410, 67, 31, 203, 203, 3639, 1089, 26743, 4727, 1488, 3061, 12, 1969, 4727, 2173, 5593, 16, 225, 15027, 2173, 5593, 16, 11833, 23365, 2173, 5593, 16, 417, 754, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 1089, 26743, 4727, 1488, 12, 11890, 1026, 4727, 2173, 5593, 16, 2254, 15027, 2173, 5593, 16, 2254, 11833, 23365, 2173, 5593, 16, 2254, 417, 754, 67, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3700, 326, 3410, 2026, 745, 333, 445, 1199, 1769, 203, 203, 3639, 1089, 26743, 4727, 1488, 3061, 12, 1969, 4727, 2173, 5593, 16, 15027, 2173, 5593, 16, 11833, 23365, 2173, 5593, 16, 417, 754, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 1089, 6450, 2173, 5593, 12, 11890, 2 ]
./full_match/80001/0x93606Db8e1340eBa115633Cc8a031D379D7638C6/sources/contracts/dev/functions/FunctionsBillingRegistry.sol
@notice Oracle withdraw LINK earned through fulfilling requests @notice If amount is 0 the full balance will be withdrawn @param recipient where to send the funds @param amount amount to withdraw/
function oracleWithdraw(address recipient, uint96 amount) external nonReentrant whenNotPaused { if (amount == 0) { amount = s_withdrawableTokens[msg.sender]; } if (s_withdrawableTokens[msg.sender] < amount) { revert InsufficientBalance(); } s_withdrawableTokens[msg.sender] -= amount; s_totalBalance -= amount; if (!LINK.transfer(recipient, amount)) { revert InsufficientBalance(); } }
5,640,171
[ 1, 23601, 598, 9446, 22926, 425, 1303, 329, 3059, 16136, 74, 5789, 3285, 225, 971, 3844, 353, 374, 326, 1983, 11013, 903, 506, 598, 9446, 82, 225, 8027, 1625, 358, 1366, 326, 284, 19156, 225, 3844, 3844, 358, 598, 9446, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 20865, 1190, 9446, 12, 2867, 8027, 16, 2254, 10525, 3844, 13, 3903, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 565, 309, 261, 8949, 422, 374, 13, 288, 203, 1377, 3844, 273, 272, 67, 1918, 9446, 429, 5157, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 565, 309, 261, 87, 67, 1918, 9446, 429, 5157, 63, 3576, 18, 15330, 65, 411, 3844, 13, 288, 203, 1377, 15226, 22085, 11339, 13937, 5621, 203, 565, 289, 203, 565, 272, 67, 1918, 9446, 429, 5157, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 565, 272, 67, 4963, 13937, 3947, 3844, 31, 203, 565, 309, 16051, 10554, 18, 13866, 12, 20367, 16, 3844, 3719, 288, 203, 1377, 15226, 22085, 11339, 13937, 5621, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x2B72ED11123cD87D42060Be24C83af43b28FCF55/sources/ThievesList1.sol
Value Changing Functions */
function setNumberOfPublicMints(uint256 _mints) public onlyOwner { MAX_PUBLIC_MINTS = _mints; }
781,179
[ 1, 620, 1680, 18183, 15486, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 9226, 4782, 49, 28142, 12, 11890, 5034, 389, 81, 28142, 13, 1071, 1338, 5541, 288, 203, 3639, 4552, 67, 14939, 67, 49, 3217, 55, 273, 389, 81, 28142, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; abstract contract Context { function _MSGSENDER157() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA592() 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; } } interface IERC20 { function TOTALSUPPLY223() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF306(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER463(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE561(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM21(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER851(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL370(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD799(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB732(a, b, "SafeMath: subtraction overflow"); } function SUB732(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 MUL950(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 DIV680(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV680(a, b, "SafeMath: division by zero"); } function DIV680(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD792(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD792(a, b, "SafeMath: modulo by zero"); } function MOD792(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT333(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 SENDVALUE497(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL661(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL661(target, data, "Address: low-level call failed"); } function FUNCTIONCALL661(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE995(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE621(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE995(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE995(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT333(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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER597(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFER463.selector, to, value)); } function SAFETRANSFERFROM780(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFERFROM21.selector, from, to, value)); } function SAFEAPPROVE352(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.ALLOWANCE696(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, value)); } function SAFEINCREASEALLOWANCE57(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD799(value); _CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE5(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB732(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN182(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. 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).FUNCTIONCALL661(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED950(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER157(); _owner = msgSender; emit OWNERSHIPTRANSFERRED950(address(0), msgSender); } function OWNER835() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER465() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER157(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP697() public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED950(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP738(address newOwner) public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED950(_owner, newOwner); _owner = newOwner; } } 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME734() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL830() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS862() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY223() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF306(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER463(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER846(_MSGSENDER157(), recipient, amount); return true; } function ALLOWANCE696(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE561(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE805(_MSGSENDER157(), spender, amount); return true; } function TRANSFERFROM21(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER846(sender, recipient, amount); _APPROVE805(sender, _MSGSENDER157(), _allowances[sender][_MSGSENDER157()].SUB732(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE200(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].ADD799(addedValue)); return true; } function DECREASEALLOWANCE585(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].SUB732(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER846(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER151(sender, recipient, amount); _balances[sender] = _balances[sender].SUB732(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD799(amount); emit TRANSFER851(sender, recipient, amount); } function _MINT127(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER151(address(0), account, amount); _totalSupply = _totalSupply.ADD799(amount); _balances[account] = _balances[account].ADD799(amount); emit TRANSFER851(address(0), account, amount); } function _BURN291(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER151(account, address(0), amount); _balances[account] = _balances[account].SUB732(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB732(amount); emit TRANSFER851(account, address(0), amount); } function _APPROVE805(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL370(owner, spender, amount); } function _SETUPDECIMALS256(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER151(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } //nGASToken contract nGASToken is ERC20("pumpgasplatform.com", "nGAS"), Ownable { function MINT597(address _to, uint256 _amount) public ONLYOWNER465 { //inject NONSTANDARD NAMING _MINT127(_to, _amount); } function TRANSFER463(address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER463(to, _PARTIALBURN883(msg.sender, amount)); } function TRANSFERFROM21(address from, address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM21(from, to, _PARTIALBURN883(from, amount)); } function _PARTIALBURN883(address sender, uint256 amount) internal returns (uint256) { //inject NONSTANDARD NAMING uint256 burnAmount = (amount.MUL950(30)).DIV680(1000); //3% will be burned every tx if (burnAmount > 0) { _BURN291(sender, burnAmount); } return amount.SUB732(burnAmount); } }
inject NONSTANDARD NAMING
function SAFEAPPROVE352(IERC20 token, address spender, uint256 value) internal {
1,839,177
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 348, 6799, 41, 2203, 3373, 3412, 4763, 22, 12, 45, 654, 39, 3462, 1147, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 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; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/LinkedListLib.sol /** * @title LinkedListLib * @author Darryl Morris (o0ragman0o) and Modular.network * * This utility library was forked from https://github.com/o0ragman0o/LibCLL * into the Modular-Network ethereum-libraries repo at https://github.com/Modular-Network/ethereum-libraries * It has been updated to add additional functionality and be more compatible with solidity 0.4.18 * coding patterns. * * version 1.1.1 * Copyright (c) 2017 Modular Inc. * The MIT License (MIT) * https://github.com/Modular-network/ethereum-libraries/blob/master/LICENSE * * The LinkedListLib provides functionality for implementing data indexing using * a circlular linked list * * Modular provides smart contract services and security reviews for contract * deployments in addition to working on open source projects in the Ethereum * community. Our purpose is to test, document, and deploy reusable code onto the * blockchain and improve both security and usability. We also educate non-profits, * schools, and other community members about the application of blockchain * technology. For further information: modular.network * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList{ mapping (uint256 => mapping (bool => uint256)) list; } /// @dev returns true if the list exists /// @param self stored linked list from contract function listExists(LinkedList storage self) public view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } /// @dev returns true if the node exists /// @param self stored linked list from contract /// @param _node a node to search for function nodeExists(LinkedList storage self, uint256 _node) public view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /// @dev Returns the number of elements in the list /// @param self stored linked list from contract function sizeOf(LinkedList storage self) public view returns (uint256 numElements) { bool exists; uint256 i; (exists,i) = getAdjacent(self, HEAD, NEXT); while (i != HEAD) { (exists,i) = getAdjacent(self, i, NEXT); numElements++; } return; } /// @dev Returns the links of a node as a tuple /// @param self stored linked list from contract /// @param _node id of the node to get function getNode(LinkedList storage self, uint256 _node) public view returns (bool,uint256,uint256) { if (!nodeExists(self,_node)) { return (false,0,0); } else { return (true,self.list[_node][PREV], self.list[_node][NEXT]); } } /// @dev Returns the link of a node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node id of the node to step from /// @param _direction direction to step in function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool,uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /// @dev Can be used before `insert` to build an ordered list /// @param self stored linked list from contract /// @param _node an existing node to search from, e.g. HEAD. /// @param _value value to seek /// @param _direction direction to seek in // @return next first node beyond '_node' in direction `_direction` function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /// @dev Creates a bidirectional link between two nodes on direction `_direction` /// @param self stored linked list from contract /// @param _node first node for linking /// @param _link node to link to in the _direction function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /// @dev Insert node `_new` beside existing node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node existing node /// @param _new new node to insert /// @param _direction direction to insert node in function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; } else { return false; } } /// @dev removes an entry from the linked list /// @param self stored linked list from contract /// @param _node node to remove from the list function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } /// @dev pushes an enrty to the head of the linked list /// @param self stored linked list from contract /// @param _node new entry to push to the head /// @param _direction push to the head (NEXT) or tail (PREV) function push(LinkedList storage self, uint256 _node, bool _direction) internal { insert(self, HEAD, _node, _direction); } /// @dev pops the first entry from the linked list /// @param self stored linked list from contract /// @param _direction pop from the head (NEXT) or the tail (PREV) function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/ownership/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: openzeppelin-solidity/contracts/ownership/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { checkRole(msg.sender, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public { addRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressAdded(addr); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address addr) public view returns (bool) { return hasRole(addr, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param addrs 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[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public { removeRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressRemoved(addr); } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { removeAddressFromWhitelist(addrs[i]); } } } // File: contracts/QuantstampAuditData.sol contract QuantstampAuditData is Whitelist { // the audit data has a whitelist of addresses of audit contracts that may interact with this contract using LinkedListLib for LinkedListLib.LinkedList; // constants used by LinkedListLib uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; // state of audit requests submitted to the contract enum AuditState { None, Queued, Assigned, Refunded, Completed, // automated audit finished successfully and the report is available Error, // automated audit failed to finish; the report contains detailed information about the error Expired, Resolved } // structure representing an audit struct Audit { address requestor; string contractUri; uint256 price; uint256 requestBlockNumber; // block number that audit was requested QuantstampAuditData.AuditState state; address auditor; // the address of the node assigned to the audit uint256 assignBlockNumber; // block number that audit was assigned string reportHash; // stores the hash of audit report uint256 reportBlockNumber; // block number that the payment and the audit report were submitted address registrar; // address of the contract which registers this request } // map audits (requestId, Audit) mapping(uint256 => Audit) public audits; // token used to pay for audits. This contract assumes that the owner of the contract trusts token's code and // that transfer function (such as transferFrom, transfer) do the right thing StandardToken public token; // Once an audit node gets an audit request, the audit price is locked for this many blocks. // After that, the requestor can asks for a refund. uint256 public auditTimeoutInBlocks = 25; // maximum number of assigned audits per each auditor uint256 public maxAssignedRequests = 10; // map audit nodes to their minimum prices. Defaults to zero: the node accepts all requests. mapping(address => uint256) public minAuditPrice; // whitelist audit nodes LinkedListLib.LinkedList internal whitelistedNodesList; uint256 private requestCounter; event WhitelistedNodeAdded(address addr); event WhitelistedNodeRemoved(address addr); /** * @dev The constructor creates an audit contract. * @param tokenAddress The address of a StandardToken that will be used to pay auditor nodes. */ constructor (address tokenAddress) public { require(tokenAddress != address(0)); token = StandardToken(tokenAddress); } function addAuditRequest (address requestor, string contractUri, uint256 price) public onlyWhitelisted returns(uint256) { // assign the next request ID uint256 requestId = ++requestCounter; // store the audit audits[requestId] = Audit(requestor, contractUri, price, block.number, AuditState.Queued, address(0), 0, "", 0, msg.sender); // solhint-disable-line not-rely-on-time return requestId; } function getAuditContractUri(uint256 requestId) public view returns(string) { return audits[requestId].contractUri; } function getAuditRequestor(uint256 requestId) public view returns(address) { return audits[requestId].requestor; } function getAuditPrice (uint256 requestId) public view returns(uint256) { return audits[requestId].price; } function getAuditState (uint256 requestId) public view returns(AuditState) { return audits[requestId].state; } function getAuditRequestBlockNumber (uint256 requestId) public view returns(uint) { return audits[requestId].requestBlockNumber; } function setAuditState (uint256 requestId, AuditState state) public onlyWhitelisted { audits[requestId].state = state; } function getAuditAuditor (uint256 requestId) public view returns(address) { return audits[requestId].auditor; } function getAuditRegistrar (uint256 requestId) public view returns(address) { return audits[requestId].registrar; } function setAuditAuditor (uint256 requestId, address auditor) public onlyWhitelisted { audits[requestId].auditor = auditor; } function getAuditAssignBlockNumber (uint256 requestId) public view returns(uint) { return audits[requestId].assignBlockNumber; } function setAuditAssignBlockNumber (uint256 requestId, uint256 assignBlockNumber) public onlyWhitelisted { audits[requestId].assignBlockNumber = assignBlockNumber; } function setAuditReportHash (uint256 requestId, string reportHash) public onlyWhitelisted { audits[requestId].reportHash = reportHash; } function setAuditReportBlockNumber (uint256 requestId, uint256 reportBlockNumber) public onlyWhitelisted { audits[requestId].reportBlockNumber = reportBlockNumber; } function setAuditRegistrar (uint256 requestId, address registrar) public onlyWhitelisted { audits[requestId].registrar = registrar; } function setAuditTimeout (uint256 timeoutInBlocks) public onlyOwner { auditTimeoutInBlocks = timeoutInBlocks; } /** * @dev set the maximum number of audits any audit node can handle at any time. * @param maxAssignments maximum number of audit requests for each auditor */ function setMaxAssignedRequests (uint256 maxAssignments) public onlyOwner { maxAssignedRequests = maxAssignments; } function getMinAuditPrice (address auditor) public view returns(uint256) { return minAuditPrice[auditor]; } /** * @dev Allows the audit node to set its minimum price per audit in wei-QSP * @param price The minimum price. */ function setMinAuditPrice(address auditor, uint256 price) public onlyWhitelisted { minAuditPrice[auditor] = price; } /** * @dev Returns true if a node is whitelisted * param node Node to check. */ function isWhitelisted(address node) public view returns(bool) { return whitelistedNodesList.nodeExists(uint256(node)); } /** * @dev Adds an address to the whitelist * @param addr address * @return true if the address was added to the whitelist */ function addNodeToWhitelist(address addr) public onlyOwner returns(bool success) { if (whitelistedNodesList.insert(HEAD, uint256(addr), PREV)) { emit WhitelistedNodeAdded(addr); success = true; } } /** * @dev Removes an address from the whitelist linked-list * @param addr address * @return true if the address was removed from the whitelist, */ function removeNodeFromWhitelist(address addr) public onlyOwner returns(bool success) { if (whitelistedNodesList.remove(uint256(addr)) != 0) { emit WhitelistedNodeRemoved(addr); success = true; } } /** * @dev Given a whitelisted address, returns the next address from the whitelist * @param addr address * @return next address of the given param */ function getNextWhitelistedNode(address addr) public view returns(address) { bool direction; uint256 next; (direction, next) = whitelistedNodesList.getAdjacent(uint256(addr), NEXT); return address(next); } } // File: contracts/QuantstampAudit.sol contract QuantstampAudit is Ownable, Pausable { using SafeMath for uint256; using LinkedListLib for LinkedListLib.LinkedList; // constants used by LinkedListLib uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; // mapping from an auditor address to the number of requests that it currently processes mapping(address => uint256) public assignedRequestCount; // increasingly sorted linked list of prices LinkedListLib.LinkedList internal priceList; // map from price to a list of request IDs mapping(uint256 => LinkedListLib.LinkedList) internal auditsByPrice; // list of request IDs of assigned audits (the list preserves temporal order of assignments) LinkedListLib.LinkedList internal assignedAudits; // contract that stores audit data (separate from the auditing logic) QuantstampAuditData public auditData; event LogAuditFinished( uint256 requestId, address auditor, QuantstampAuditData.AuditState auditResult, string reportHash ); event LogAuditRequested(uint256 requestId, address requestor, string uri, uint256 price ); event LogAuditAssigned(uint256 requestId, address auditor, address requestor, string uri, uint256 price, uint256 requestBlockNumber); /* solhint-disable event-name-camelcase */ event LogReportSubmissionError_InvalidAuditor(uint256 requestId, address auditor); event LogReportSubmissionError_InvalidState(uint256 requestId, address auditor, QuantstampAuditData.AuditState state); event LogReportSubmissionError_InvalidResult(uint256 requestId, address auditor, QuantstampAuditData.AuditState state); event LogReportSubmissionError_ExpiredAudit(uint256 requestId, address auditor, uint256 allowanceBlockNumber); event LogAuditAssignmentError_ExceededMaxAssignedRequests(address auditor); event LogAuditAssignmentUpdate_Expired(uint256 requestId, uint256 allowanceBlockNumber); /* solhint-enable event-name-camelcase */ event LogAuditQueueIsEmpty(); event LogPayAuditor(uint256 requestId, address auditor, uint256 amount); event LogAuditNodePriceChanged(address auditor, uint256 amount); event LogRefund(uint256 requestId, address requestor, uint256 amount); event LogRefundInvalidRequestor(uint256 requestId, address requestor); event LogRefundInvalidState(uint256 requestId, QuantstampAuditData.AuditState state); event LogRefundInvalidFundsLocked(uint256 requestId, uint256 currentBlock, uint256 fundLockEndBlock); // the audit queue has elements, but none satisfy the minPrice of the audit node // amount corresponds to the current minPrice of the auditor event LogAuditNodePriceHigherThanRequests(address auditor, uint256 amount); event LogInvalidResolutionCall(uint256 requestId); event LogErrorReportResolved(uint256 requestId, address receiver, uint256 auditPrice); enum AuditAvailabilityState { Error, Ready, // an audit is available to be picked up Empty, // there is no audit request in the queue Exceeded, // number of incomplete audit requests is reached the cap Underprice // all queued audit requests are less than the expected price } /** * @dev The constructor creates an audit contract. * @param auditDataAddress The address of a AuditData that stores data used for performing audits. */ constructor (address auditDataAddress) public { require(auditDataAddress != address(0)); auditData = QuantstampAuditData(auditDataAddress); } /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(auditData.isWhitelisted(msg.sender)); _; } /** * @dev Returns funds to the requestor. * @param requestId Unique ID of the audit request. */ function refund(uint256 requestId) external returns(bool) { QuantstampAuditData.AuditState state = auditData.getAuditState(requestId); // check that the audit exists and is in a valid state if (state != QuantstampAuditData.AuditState.Queued && state != QuantstampAuditData.AuditState.Assigned && state != QuantstampAuditData.AuditState.Expired) { emit LogRefundInvalidState(requestId, state); return false; } address requestor = auditData.getAuditRequestor(requestId); if (requestor != msg.sender) { emit LogRefundInvalidRequestor(requestId, msg.sender); return; } uint256 refundBlockNumber = auditData.getAuditAssignBlockNumber(requestId) + auditData.auditTimeoutInBlocks(); // check that the auditor has not recently started the audit (locking the funds) if (state == QuantstampAuditData.AuditState.Assigned) { if (block.number <= refundBlockNumber) { emit LogRefundInvalidFundsLocked(requestId, block.number, refundBlockNumber); return false; } // the request is expired but not detected by getNextAuditRequest updateAssignedAudits(requestId); } else if (state == QuantstampAuditData.AuditState.Queued) { // remove the request from the queue // note that if an audit node is currently assigned the request, it is already removed from the queue removeQueueElement(requestId); } // set the audit state to refunded auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Refunded); // return the funds to the user uint256 price = auditData.getAuditPrice(requestId); emit LogRefund(requestId, requestor, price); return auditData.token().transfer(requestor, price); } /** * @dev Submits audit request. * @param contractUri Identifier of the resource to audit. * @param price The total amount of tokens that will be paid for the audit. */ function requestAudit(string contractUri, uint256 price) external whenNotPaused returns(uint256) { require(price > 0); // transfer tokens to this contract auditData.token().transferFrom(msg.sender, address(this), price); // store the audit uint256 requestId = auditData.addAuditRequest(msg.sender, contractUri, price); // TODO: use existing price instead of HEAD (optimization) queueAuditRequest(requestId, HEAD); emit LogAuditRequested(requestId, msg.sender, contractUri, price); // solhint-disable-line not-rely-on-time return requestId; } /** * @dev Submits the report and pays the auditor node for their work if the audit is completed. * @param requestId Unique identifier of the audit request. * @param auditResult Result of an audit. * @param reportHash Hash of the generated report. */ function submitReport(uint256 requestId, QuantstampAuditData.AuditState auditResult, string reportHash) public onlyWhitelisted { if (QuantstampAuditData.AuditState.Completed != auditResult && QuantstampAuditData.AuditState.Error != auditResult) { emit LogReportSubmissionError_InvalidResult(requestId, msg.sender, auditResult); return; } QuantstampAuditData.AuditState auditState = auditData.getAuditState(requestId); if (auditState != QuantstampAuditData.AuditState.Assigned) { emit LogReportSubmissionError_InvalidState(requestId, msg.sender, auditState); return; } // the sender must be the auditor if (msg.sender != auditData.getAuditAuditor(requestId)) { emit LogReportSubmissionError_InvalidAuditor(requestId, msg.sender); return; } // remove the requestId from assigned queue updateAssignedAudits(requestId); // auditor should not send a report after its allowed period uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(requestId) + auditData.auditTimeoutInBlocks(); if (allowanceBlockNumber < block.number) { // update assigned to expired state auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Expired); emit LogReportSubmissionError_ExpiredAudit(requestId, msg.sender, allowanceBlockNumber); return; } // update the audit information held in this contract auditData.setAuditState(requestId, auditResult); auditData.setAuditReportHash(requestId, reportHash); auditData.setAuditReportBlockNumber(requestId, block.number); // solhint-disable-line not-rely-on-time // validate the audit state require(isAuditFinished(requestId)); emit LogAuditFinished(requestId, msg.sender, auditResult, reportHash); // solhint-disable-line not-rely-on-time if (auditResult == QuantstampAuditData.AuditState.Completed) { uint256 auditPrice = auditData.getAuditPrice(requestId); auditData.token().transfer(msg.sender, auditPrice); emit LogPayAuditor(requestId, msg.sender, auditPrice); } } /** * @dev Determines who has to be paid for a given requestId recorded with an error status * @param requestId Unique identifier of the audit request. * @param toRequester The audit price goes to the requester or the audit node. */ function resolveErrorReport(uint256 requestId, bool toRequester) public onlyOwner { QuantstampAuditData.AuditState auditState = auditData.getAuditState(requestId); if (auditState != QuantstampAuditData.AuditState.Error) { emit LogInvalidResolutionCall(requestId); return; } uint256 auditPrice = auditData.getAuditPrice(requestId); address receiver = toRequester ? auditData.getAuditRequestor(requestId) : auditData.getAuditAuditor(requestId); auditData.token().transfer(receiver, auditPrice); auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Resolved); emit LogErrorReportResolved(requestId, receiver, auditPrice); } /** * @dev Determines if there is an audit request available to be picked up by the caller */ function anyRequestAvailable() public view returns(AuditAvailabilityState) { // there are no audits in the queue if (!auditQueueExists()) { return AuditAvailabilityState.Empty; } // check if the auditor's assignment is not exceeded. if (assignedRequestCount[msg.sender] >= auditData.maxAssignedRequests()) { return AuditAvailabilityState.Exceeded; } if (anyAuditRequestMatchesPrice(auditData.getMinAuditPrice(msg.sender)) == 0) { return AuditAvailabilityState.Underprice; } return AuditAvailabilityState.Ready; } /** * @dev Finds a list of most expensive audits and assigns the oldest one to the auditor node. */ function getNextAuditRequest() public onlyWhitelisted { // remove an expired audit request if (assignedAudits.listExists()) { bool exists; uint256 potentialExpiredRequestId; (exists, potentialExpiredRequestId) = assignedAudits.getAdjacent(HEAD, NEXT); uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(potentialExpiredRequestId) + auditData.auditTimeoutInBlocks(); if (allowanceBlockNumber < block.number) { updateAssignedAudits(potentialExpiredRequestId); auditData.setAuditState(potentialExpiredRequestId, QuantstampAuditData.AuditState.Expired); emit LogAuditAssignmentUpdate_Expired(potentialExpiredRequestId, allowanceBlockNumber); } } AuditAvailabilityState isRequestAvailable = anyRequestAvailable(); // there are no audits in the queue if (isRequestAvailable == AuditAvailabilityState.Empty) { emit LogAuditQueueIsEmpty(); return; } // check if the auditor's assignment is not exceeded. if (isRequestAvailable == AuditAvailabilityState.Exceeded) { emit LogAuditAssignmentError_ExceededMaxAssignedRequests(msg.sender); return; } // there are no audits in the queue with a price high enough for the audit node uint256 minPrice = auditData.getMinAuditPrice(msg.sender); uint256 requestId = dequeueAuditRequest(minPrice); if (requestId == 0) { emit LogAuditNodePriceHigherThanRequests(msg.sender, minPrice); return; } auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Assigned); auditData.setAuditAuditor(requestId, msg.sender); auditData.setAuditAssignBlockNumber(requestId, block.number); assignedRequestCount[msg.sender]++; // push to the tail assignedAudits.push(requestId, PREV); emit LogAuditAssigned( requestId, auditData.getAuditAuditor(requestId), auditData.getAuditRequestor(requestId), auditData.getAuditContractUri(requestId), auditData.getAuditPrice(requestId), auditData.getAuditRequestBlockNumber(requestId)); } /** * @dev Allows the audit node to set its minimum price per audit in wei-QSP * @param price The minimum price. */ function setAuditNodePrice(uint256 price) public onlyWhitelisted { auditData.setMinAuditPrice(msg.sender, price); emit LogAuditNodePriceChanged(msg.sender, price); } /** * @dev Checks if an audit is finished. It is considered finished when the audit is either completed or failed. * @param requestId Unique ID of the audit request. */ function isAuditFinished(uint256 requestId) public view returns(bool) { QuantstampAuditData.AuditState state = auditData.getAuditState(requestId); return state == QuantstampAuditData.AuditState.Completed || state == QuantstampAuditData.AuditState.Error; } /** * @dev Given a price, returns the next price from the priceList * @param price of the current node * @return next price in the linked list */ function getNextPrice(uint256 price) public view returns(uint256) { bool exists; uint256 next; (exists, next) = priceList.getAdjacent(price, NEXT); return next; } /** * @dev Given a requestId, returns the next one from assignedAudits * @param requestId of the current node * @return next requestId in the linked list */ function getNextAssignedRequest(uint256 requestId) public view returns(uint256) { bool exists; uint256 next; (exists, next) = assignedAudits.getAdjacent(requestId, NEXT); return next; } /** * @dev Given a price and a requestId, then function returns the next requestId with the same price * return 0, provided the given price does not exist in auditsByPrice * @param price of the current bucket * @param requestId unique Id of an requested audit * @return next requestId with the same price */ function getNextAuditByPrice(uint256 price, uint256 requestId) public view returns(uint256) { bool exists; uint256 next; (exists, next) = auditsByPrice[price].getAdjacent(requestId, NEXT); return next; } /** * @dev Given a requestId, the function removes it from the list of audits and decreases the number of assigned * audits of the associated auditor * @param requestId unique Id of an requested audit */ function updateAssignedAudits(uint256 requestId) internal { assignedAudits.remove(requestId); assignedRequestCount[auditData.getAuditAuditor(requestId)] = assignedRequestCount[auditData.getAuditAuditor(requestId)].sub(1); } /** * @dev Checks if the list of audits has any elements */ function auditQueueExists() internal view returns(bool) { return priceList.listExists(); } /** * @dev Adds an audit request to the queue * @param requestId Request ID. * @param existingPrice price of an existing audit in the queue (makes insertion O(1)) */ function queueAuditRequest(uint256 requestId, uint256 existingPrice) internal { uint256 price = auditData.getAuditPrice(requestId); if (!priceList.nodeExists(price)) { // if a price bucket doesn't exist, create it next to an existing one priceList.insert(priceList.getSortedSpot(existingPrice, price, NEXT), price, PREV); } // push to the tail auditsByPrice[price].push(requestId, PREV); } /** * @dev Evaluates if there is an audit price >= minPrice. Returns 0 if there no audit with the desired price. * Note that there should not be any audit with price as 0. * @param minPrice The minimum audit price. */ function anyAuditRequestMatchesPrice(uint256 minPrice) internal view returns(uint256) { bool exists; uint256 price; // picks the tail of price buckets (exists, price) = priceList.getAdjacent(HEAD, PREV); if (price < minPrice) { return 0; } return price; } /** * @dev Finds a list of most expensive audits and returns the oldest one that has a price >= minPrice * @param minPrice The minimum audit price. */ function dequeueAuditRequest(uint256 minPrice) internal returns(uint256) { uint256 price; // picks the tail of price buckets // TODO seems the following statement is redundantly called from getNextAuditRequest. If this is the only place // to call dequeueAuditRequest, then removing the following line saves gas, but leaves dequeueAuditRequest // unsafe for further extension by noobies. price = anyAuditRequestMatchesPrice(minPrice); if (price > 0) { // picks the oldest audit request uint256 result = auditsByPrice[price].pop(NEXT); // removes the price bucket if it contains no requests if (!auditsByPrice[price].listExists()) { priceList.remove(price); } return result; } return 0; } /** * @dev Removes an element from the list * @param requestId The Id of the request to be removed */ function removeQueueElement(uint256 requestId) internal { uint256 price = auditData.getAuditPrice(requestId); // the node must exist in the list require(priceList.nodeExists(price)); require(auditsByPrice[price].nodeExists(requestId)); auditsByPrice[price].remove(requestId); if (!auditsByPrice[price].listExists()) { priceList.remove(price); } } }
* @dev Returns true if a node is whitelisted param node Node to check./
function isWhitelisted(address node) public view returns(bool) { return whitelistedNodesList.nodeExists(uint256(node)); }
5,489,212
[ 1, 1356, 638, 309, 279, 756, 353, 26944, 579, 756, 2029, 358, 866, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 18927, 329, 12, 2867, 756, 13, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 565, 327, 26944, 3205, 682, 18, 2159, 4002, 12, 11890, 5034, 12, 2159, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/// @author Jianwei Liu [email protected] pragma solidity 0.5.12; import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** @notice The VaultNotary contract is the contract for reading/writing the * vault uri and hash, and controlling the permissions to those operations by vault * owner. */ contract VaultNotary is Ownable { struct Data { /* Struct Slot 0 */ // The access control mapping to record whether an address can update the Hash of a Vault mapping(address => bool) hashAcl; /* Struct Slot 1 */ // The access control mapping to record whether an address can update the Uri of a Vault mapping(address => bool) uriAcl; /* Struct Slot 2 */ // The address of the Vault owner, 20 bytes address vaultOwner; /* Struct Slot 3 */ string vaultHash; /* Struct Slot 4 */ string vaultUri; } /* Slot 0, data part at keccak256(key . uint256(0)), where . is concatenation*/ // Each Vault has its own Data mapping(bytes16 => VaultNotary.Data) internal notaryMapping; /* Slot 1 */ // Boolean that controls whether this contract is deprecated or not, 1 byte bool internal isDeprecated; // Notary Events event VaultUri(address indexed msgSender, bytes16 indexed vaultId, string vaultUri); event VaultHash(address indexed msgSender, bytes16 indexed vaultId, string vaultHash); event VaultRegistered(address indexed msgSender, bytes16 indexed vaultId); event UpdateHashPermissionGranted(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToGrant); event UpdateHashPermissionRevoked(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToRevoke); event UpdateUriPermissionGranted(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToGrant); event UpdateUriPermissionRevoked(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToRevoke); // Contract Events event ContractDeprecatedSet(address indexed msgSender, bool isDeprecated); /** @dev Modifier for limiting the access to vaultUri update * only whitelisted user can do the decorated operation */ modifier canUpdateUri(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner || notaryMapping[vaultId].uriAcl[msg.sender], "Only the vault owner or whitelisted users can update vault URI"); _; } /** @dev Modifier for limiting the access to vaultHash update * only whitelisted user can do the decorated operation */ modifier canUpdateHash(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner || notaryMapping[vaultId].hashAcl[msg.sender], "Only the vault owner or whitelisted users can update vault hash"); _; } /** @dev Modifier for limiting the access to grant and revoke permissions * Will check the message sender, only the owner of a vault can do the operation decorated * @param vaultId bytes16 ID of the vault to check */ modifier vaultOwnerOnly(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner, "Method only accessible to vault owner"); _; } /** @notice This modifier is for testing whether a Vault has been registered yet * @param vaultId bytes16 The ID of the vault to check */ modifier isNotRegistered(bytes16 vaultId) { require(notaryMapping[vaultId].vaultOwner == address(0x0), "Vault ID already exists"); _; } /** @notice This modifier is for testing whether a Vault has been registered yet * @param vaultId bytes16 The ID of the vault to check */ modifier isRegistered(bytes16 vaultId) { require(notaryMapping[vaultId].vaultOwner != address(0x0), "Vault ID does not exist"); _; } /** @notice If we upgrade the version of the contract, the old contract * will not be allowed to register new Vault anymore. However, the existing * Vaults registered in that contract should still be able to be updated */ modifier notDeprecated() { require(!isDeprecated, "This version of the VaultNotary contract has been deprecated"); _; } /** @notice This is function to register a vault, will only do the registration if a vaultId has not been registered before * @dev It sets the msg.sender to the vault owner, and calls the setVaultUri and setVaultHash to * initialize the uri and hash of a vault. It emits VaultRegistered on success. * @param vaultId bytes16 VaultID to create, is the same as shipment ID in our system * @param vaultUri string Vault URI to set * @param vaultHash string Vault hash to set */ function registerVault(bytes16 vaultId, string calldata vaultUri, string calldata vaultHash) external notDeprecated isNotRegistered(vaultId) { notaryMapping[vaultId].vaultOwner = msg.sender; //work around for if (vaultUri != "") if (bytes(vaultUri).length != 0) setVaultUri(vaultId, vaultUri); if (bytes(vaultHash).length != 0) setVaultHash(vaultId, vaultHash); emit VaultRegistered(msg.sender, vaultId); } /** @notice Sets the contract isDeprecated flag. Vault registration will be disabled if isDeprecated == True * Only contract owner can set this * @dev It emits ContractDeprecatedSet on success * @param _isDeprecated bool Boolean control variable */ function setDeprecated(bool _isDeprecated) external onlyOwner { isDeprecated = _isDeprecated; emit ContractDeprecatedSet(msg.sender, isDeprecated); } /** @notice Function to grant update permission to the hash field in a vault * @dev It emits UpdateHashPermissionGranted on success * @param vaultId bytes16 The ID of Vault to grant permission * @param addressToGrant address The address to grant permission */ function grantUpdateHashPermission(bytes16 vaultId, address addressToGrant) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].hashAcl[addressToGrant] = true; emit UpdateHashPermissionGranted(msg.sender, vaultId, addressToGrant); } /** @notice Function to revoke update permission to the hash field in a vault * @dev It emits UpdateHashPermissionRevoked on success * @param vaultId The ID of Vault to revoke permission * @param addressToRevoke address The address to revoke permission */ function revokeUpdateHashPermission(bytes16 vaultId, address addressToRevoke) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].hashAcl[addressToRevoke] = false; emit UpdateHashPermissionRevoked(msg.sender, vaultId, addressToRevoke); } /** @notice Function to grant update permission to the Uri field in a vault * @dev It emits UpdateUriPermissionGranted on success * @param vaultId bytes16 The ID of Vault to grant permission * @param addressToGrant address The address to grant permission */ function grantUpdateUriPermission(bytes16 vaultId, address addressToGrant) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].uriAcl[addressToGrant] = true; emit UpdateUriPermissionGranted(msg.sender, vaultId, addressToGrant); } /** @notice Function to revoke update permission to the Uri field in a vault * @dev It emits UpdateUriPermissionRevoked on success * @param vaultId The ID of Vault to revoke permission * @param addressToRevoke address The address to revoke permission */ function revokeUpdateUriPermission(bytes16 vaultId, address addressToRevoke) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].uriAcl[addressToRevoke] = false; emit UpdateUriPermissionRevoked(msg.sender, vaultId, addressToRevoke); } /** @notice This function can read the vaultUri, vaultHash and vaultOwner given a * vaultId. It can be used in unit tests to verify the values are correct * after calling registerVault or using the setters. It can also be used * by outside users to read the details of a vault. If vaultID is not * registered, the vaultOwner returned will be 0x0. Otherwise, vaultOwner will * not be 0x0. Therefore, the returned vaultOwner can be used to test whether * the queried vault is registered. When vault not registered, the returned * vaultUri and vaultHash will both be empty strings * @param vaultId bytes16 The ID of the Vault to query * @return vaultUri string The uri of the vault * @return vaultHash string The hash of the vault * @return vaultOwner address The address of the vault owner */ function getVaultNotaryDetails(bytes16 vaultId) external view returns(string memory vaultUri, string memory vaultHash, address vaultOwner) { vaultUri = notaryMapping[vaultId].vaultUri; vaultHash = notaryMapping[vaultId].vaultHash; vaultOwner = notaryMapping[vaultId].vaultOwner; } /** @notice Function to set the vault URI * @dev It emits VaultUri on success * @param vaultId bytes16 ID of the vault to set * @param vaultUri string The vault URI to set */ function setVaultUri(bytes16 vaultId, string memory vaultUri) public isRegistered(vaultId) canUpdateUri(vaultId) { notaryMapping[vaultId].vaultUri = vaultUri; emit VaultUri(msg.sender, vaultId, vaultUri); } /** @notice Function to set the vault hash * @dev It emits VaultHash on success * @param vaultId bytes16 ID of the vault to set * @param vaultHash string The vault hash to set */ function setVaultHash(bytes16 vaultId, string memory vaultHash) public isRegistered(vaultId) canUpdateHash(vaultId) { notaryMapping[vaultId].vaultHash = vaultHash; emit VaultHash(msg.sender, vaultId, vaultHash); } }
* @notice This modifier is for testing whether a Vault has been registered yet @param vaultId bytes16 The ID of the vault to check/
modifier isRegistered(bytes16 vaultId) { require(notaryMapping[vaultId].vaultOwner != address(0x0), "Vault ID does not exist"); _; }
2,520,323
[ 1, 2503, 9606, 353, 364, 7769, 2856, 279, 17329, 711, 2118, 4104, 4671, 225, 9229, 548, 1731, 2313, 1021, 1599, 434, 326, 9229, 358, 866, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 353, 10868, 12, 3890, 2313, 9229, 548, 13, 288, 203, 3639, 2583, 12, 902, 814, 3233, 63, 26983, 548, 8009, 26983, 5541, 480, 1758, 12, 20, 92, 20, 3631, 315, 12003, 1599, 1552, 486, 1005, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x43520395f42256100b47881CA53Ef613371d1506/sources/ECOProxy.sol
* @dev Collection of functions related to the address type/
library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != accountHash && codehash != 0x0); } assembly { codehash := extcodehash(account) } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{ value: amount }(""); }
16,184,916
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 203, 203, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 3639, 19931, 288, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 289, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 460, 30, 3844, 289, 2932, 8863, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1331e537Df2b3ae5B75E2655552B0AD7502cA4f8/sources/UniswapV2_ZapIn_General_V3.sol
*/ check output via tokenA -> tokenB
@notice This function is used to swap ERC20 <> ERC20 @param _FromTokenContractAddress The token address to swap from. @param _ToTokenContractAddress The token address to swap to. @param tokens2Trade The amount of tokens to swap @return tokenBought The quantity of tokens bought function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 tokenBought) { if (_FromTokenContractAddress == _ToTokenContractAddress) { return tokens2Trade; } IERC20(_FromTokenContractAddress).safeApprove( address(uniswapRouter), 0 ); IERC20(_FromTokenContractAddress).safeApprove( address(uniswapRouter), tokens2Trade ); if (_FromTokenContractAddress != wethTokenAddress) { if (_ToTokenContractAddress != wethTokenAddress) { address pairA = UniSwapV2FactoryAddress.getPair( _FromTokenContractAddress, _ToTokenContractAddress ); address[] memory pathA = new address[](2); pathA[0] = _FromTokenContractAddress; pathA[1] = _ToTokenContractAddress; uint256 amtA; if (pairA != address(0)) { amtA = uniswapRouter.getAmountsOut(tokens2Trade, pathA)[1]; } pathB[0] = _FromTokenContractAddress; pathB[1] = wethTokenAddress; pathB[2] = _ToTokenContractAddress; uint256 amtB = uniswapRouter.getAmountsOut( tokens2Trade, pathB )[2]; if (amtA >= amtB) { tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathA, address(this), deadline )[pathA.length - 1]; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathB, address(this), deadline )[pathB.length - 1]; } address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } require(tokenBought > 0, "Error Swapping Tokens 2"); }
4,402,553
[ 1, 19, 866, 876, 3970, 1147, 37, 317, 1147, 38, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 632, 20392, 1220, 445, 353, 1399, 358, 7720, 4232, 39, 3462, 2813, 4232, 39, 3462, 203, 565, 632, 891, 389, 1265, 1345, 8924, 1887, 1021, 1147, 1758, 358, 7720, 628, 18, 203, 565, 632, 891, 389, 774, 1345, 8924, 1887, 1021, 1147, 1758, 358, 7720, 358, 18, 7010, 565, 632, 891, 2430, 22, 22583, 1021, 3844, 434, 2430, 358, 7720, 203, 565, 632, 2463, 1147, 13809, 9540, 1021, 10457, 434, 2430, 800, 9540, 203, 565, 445, 389, 2316, 22, 1345, 12, 203, 3639, 1758, 389, 1265, 1345, 8924, 1887, 16, 203, 3639, 1758, 389, 774, 1345, 8924, 1887, 16, 203, 3639, 2254, 5034, 2430, 22, 22583, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 1147, 13809, 9540, 13, 288, 203, 3639, 309, 261, 67, 1265, 1345, 8924, 1887, 422, 389, 774, 1345, 8924, 1887, 13, 288, 203, 5411, 327, 2430, 22, 22583, 31, 203, 3639, 289, 203, 3639, 467, 654, 39, 3462, 24899, 1265, 1345, 8924, 1887, 2934, 4626, 12053, 537, 12, 203, 5411, 1758, 12, 318, 291, 91, 438, 8259, 3631, 203, 5411, 374, 203, 3639, 11272, 203, 3639, 467, 654, 39, 3462, 24899, 1265, 1345, 8924, 1887, 2934, 4626, 12053, 537, 12, 203, 5411, 1758, 12, 318, 291, 91, 438, 8259, 3631, 203, 5411, 2430, 22, 22583, 203, 3639, 11272, 203, 203, 3639, 309, 261, 67, 1265, 1345, 8924, 1887, 480, 341, 546, 1345, 1887, 13, 288, 203, 5411, 309, 261, 67, 774, 1345, 8924, 1887, 480, 341, 546, 1345, 1887, 13, 288, 203, 7734, 1758, 3082, 37, 273, 1351, 77, 2 ]
./partial_match/1/0xbf826778E20274a33CC896275F3F01c97BCa7b71/sources/Asset.sol
@dev Read royalty fee set./
function getRoyaltyFee() public view returns (uint256) { return royalty; }
4,423,248
[ 1, 1994, 721, 93, 15006, 14036, 444, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 13372, 15006, 14667, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 721, 93, 15006, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-04 */ // SPDX-License-Identifier: MIT //FORKED OFF BORINGBANANAS.CO, GREAT COMMUNITY, GO CHECK THEM OUT! //VEE IS THE MAN. // GO TO LINE 1885 TO SEE WHERE THE MARTIAN CONTRACT STARTS //LETS HAVE SOME FUN! HOPE YOU LIKE EM. // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; contract UrbanMartians is ERC721, Ownable { using SafeMath for uint256; string public MARTIAN_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN MARTIANS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE uint256 public constant martianPrice = 25000000000000000; // 0.025 ETH uint public constant maxMartianPurchase = 5; uint256 public constant MAX_MARTIANS = 3000 ; bool public saleIsActive = false; mapping(uint => string) public martianNames; event martianNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("UrbanMartians", "UMART") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { MARTIAN_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A MARTIAN WITHIN RANGE"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintUrbanMartian(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Martian"); require(numberOfTokens > 0 && numberOfTokens <= maxMartianPurchase, "Can only mint 5 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_MARTIANS, "Purchase would exceed max supply of Martians"); require(msg.value >= martianPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MARTIANS) { _safeMint(msg.sender, mintIndex); } } } function changeMartianName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this martian!"); require(sha256(bytes(_name)) != sha256(bytes(martianNames[_tokenId])), "New name is same as the current one"); martianNames[_tokenId] = _name; emit martianNameChange(msg.sender, _tokenId, _name); } function viewMartianName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a martian within range" ); return martianNames[_tokenId]; } // GET ALL MARTIANS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function martianNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = martianNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
IPFS URL WILL BE ADDED WHEN MARTIANS ARE ALL SOLD OUT
string public MARTIAN_PROVENANCE = "";
15,443,918
[ 1, 2579, 4931, 1976, 678, 15125, 9722, 11738, 7660, 29707, 490, 4928, 45, 11607, 432, 862, 8061, 348, 11846, 8210, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 1071, 490, 4928, 21634, 67, 3373, 58, 1157, 4722, 273, 1408, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private communityAddr = 0xf38ce89f0e7c0057fce8dc1e8dcbb36a2366e8c5; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players 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 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0xde38b17d669a1ca474f9adb4ca3c816e79275567; plyr_[1].name = "plyr1"; plyr_[1].names = 1; pIDxAddr_[0xde38b17d669a1ca474f9adb4ca3c816e79275567] = 1; pIDxName_["plyr1"] = 1; plyrNames_[1]["plyr1"] = true; plyrNameList_[1][1] = "plyr1"; plyr_[2].addr = 0x0fa923b59b06b757f37ddd36d6862ebb37733faa; plyr_[2].name = "plyr2"; plyr_[2].names = 1; pIDxAddr_[0x0fa923b59b06b757f37ddd36d6862ebb37733faa] = 2; pIDxName_["plyr2"] = 2; plyrNames_[2]["plyr2"] = true; plyrNameList_[2][1] = "plyr2"; pID_ = 2; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @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"); _; } modifier onlyCommunity() { require(msg.sender == communityAddr, "msg sender is not the community"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // 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 ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. 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 refered 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 { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 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; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // 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; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards communityAddr.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 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; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // 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; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyCommunity() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) onlyCommunity() public { registrationFee_ = _fee; } } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ dddos │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ 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 dddos * - 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); } } }
============================================================================== _| _ _|_ _ _ _ _|_ _ . (_|(_| | (_| _\(/_ | |_||_) .=============================|================================================
contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private communityAddr = 0xf38ce89f0e7c0057fce8dc1e8dcbb36a2366e8c5; struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } public constructor() { plyr_[1].addr = 0xde38b17d669a1ca474f9adb4ca3c816e79275567; plyr_[1].name = "plyr1"; plyr_[1].names = 1; pIDxAddr_[0xde38b17d669a1ca474f9adb4ca3c816e79275567] = 1; pIDxName_["plyr1"] = 1; plyrNames_[1]["plyr1"] = true; plyrNameList_[1][1] = "plyr1"; plyr_[2].addr = 0x0fa923b59b06b757f37ddd36d6862ebb37733faa; plyr_[2].name = "plyr2"; plyr_[2].names = 1; pIDxAddr_[0x0fa923b59b06b757f37ddd36d6862ebb37733faa] = 2; pIDxName_["plyr2"] = 2; plyrNames_[2]["plyr2"] = true; plyrNameList_[2][1] = "plyr2"; pID_ = 2; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require(_codeLength == 0, "sorry humans only"); _; } modifier onlyCommunity() assembly {_codeLength := extcodesize(_addr)} { require(msg.sender == communityAddr, "msg sender is not the community"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onNewName function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } } else if (_affCode == _pID) { registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function useMyOldName(string _nameString) isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); plyr_[_pID].name = _name; } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } communityAddr.transfer(address(this).balance); if (_all == true) emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } } else { function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } } else if (_affID == _pID) { registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function addGame(address _gameAddress, string _gameNameStr) onlyCommunity() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) onlyCommunity() public { registrationFee_ = _fee; } }
467,100
[ 1, 9917, 26678, 377, 389, 96, 389, 389, 96, 67, 389, 565, 389, 389, 389, 96, 67, 565, 389, 282, 263, 565, 261, 67, 96, 24899, 96, 571, 261, 67, 96, 225, 389, 30351, 18510, 571, 571, 67, 20081, 67, 13, 225, 263, 2429, 14468, 33, 96, 20775, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19185, 9084, 288, 203, 565, 1450, 1770, 1586, 364, 533, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1758, 3238, 19833, 3178, 273, 374, 5841, 7414, 311, 6675, 74, 20, 73, 27, 71, 713, 10321, 74, 311, 28, 7201, 21, 73, 28, 7201, 9897, 5718, 69, 4366, 6028, 73, 28, 71, 25, 31, 203, 565, 1958, 19185, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 1731, 1578, 508, 31, 203, 3639, 2254, 5034, 7125, 1403, 31, 203, 3639, 2254, 5034, 1257, 31, 203, 565, 289, 203, 565, 1071, 203, 565, 3885, 1435, 203, 565, 288, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 4793, 273, 374, 92, 323, 7414, 70, 4033, 72, 6028, 29, 69, 21, 5353, 24, 5608, 74, 29, 361, 70, 24, 5353, 23, 71, 28, 2313, 73, 7235, 5324, 2539, 9599, 31, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 529, 273, 315, 1283, 86, 21, 14432, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 1973, 273, 404, 31, 203, 3639, 293, 734, 92, 3178, 67, 63, 20, 92, 323, 7414, 70, 4033, 72, 6028, 29, 69, 21, 5353, 24, 5608, 74, 29, 361, 70, 24, 5353, 23, 71, 28, 2313, 73, 7235, 5324, 2539, 9599, 65, 273, 404, 31, 203, 3639, 293, 734, 92, 461, 67, 9614, 1283, 86, 21, 11929, 273, 404, 31, 203, 3639, 293, 715, 86, 1557, 67, 63, 21, 6362, 6, 1283, 86, 21, 11929, 273, 638, 31, 203, 3639, 293, 715, 86, 461, 682, 67, 63, 21, 2 ]
pragma solidity ^0.6.2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract FlightSuretyData is AccessControl { using SafeMath for uint256; // Roles definition bytes32 public constant AIRLINER_ROLE = keccak256("AIRLINER"); // Airlines registration fee and flight insurance cap uint256 private constant _AIRLINE_REG_FEE = 10 ether; uint256 private constant _FLIGHT_INSURANCE_CAP = 1 ether; bool public operational = true; // Blocks all state changes throughout the contract if false address private _contractOwner; // Account used to deploy contract mapping (address => uint256) private _authorizedContracts; // Keeps track of authorized app contract(s) // Tuple to store registration info on airlines struct Airline { bool isFunded; string name; } uint256 public airlinesCount; mapping (address => Airline) private _airlines; mapping (bytes32 => address[]) private _insurances; // Flight number to insuree addresses mapping (bytes32 => uint256) private _insurees; // Insuree to insured amount mapping (address => uint256) private _pendingWithdrawals; // Insuree to withdrawal amount event Received(address _address, address indexed _iAddress, uint256 _amount); event Funded(address _address, address indexed _iAddress, uint256 _amount); constructor (address _address) public { _contractOwner = _msgSender(); super._setupRole(AIRLINER_ROLE, _msgSender()); super._setRoleAdmin(AIRLINER_ROLE, AIRLINER_ROLE); super.grantRole(AIRLINER_ROLE, _address); _airlines[_address] = Airline({ isFunded: false, name: "First National" }); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller * */ modifier requireContractOwner() { require(_msgSender() == _contractOwner, "Caller is not contract owner"); _; } modifier requireIsAuthorized() { require( _authorizedContracts[_msgSender()] == 1, "Caller is not an authorized app contract" ); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool _mode) public requireContractOwner { operational = _mode; } /** * @dev Authorizes `_address` for remote calls * */ function authorizeContract(address _address) public requireIsOperational requireContractOwner { if (_authorizedContracts[_address] == 0) { _authorizedContracts[_address] = 1; super.grantRole(AIRLINER_ROLE, _address); } } /** * @dev Deauthorizes `_address` for remote calls * */ function deauthorizeContract(address _address) public requireIsOperational requireContractOwner { if (_authorizedContracts[_address] == 1) { _authorizedContracts[_address] = 0; super.revokeRole(AIRLINER_ROLE, _address); } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Returns `true` if `_address` has Airliner Role * */ function hasAirlinerRole(address _address) external view returns (bool) { return super.hasRole(AIRLINER_ROLE, _address); } /** * @dev Gets `isFunded` for an airliner `_address` * */ function getFundedStatus(address _address) external view returns (bool) { return _airlines[_address].isFunded; } /** * @dev Add an airline to the registration queue * * Can only be called from FlightSuretyApp contract * */ function registerAirline(address _address, string calldata _name) external requireIsOperational requireIsAuthorized returns (bool) { if (_airlines[_address].isFunded == true) { return false; } _airlines[_address] = Airline({ isFunded: false, name: _name }); super.grantRole(AIRLINER_ROLE, _address); return true; } /** * @dev Buy insurance for a flight * */ function buy ( address _airline, string calldata _flight, uint256 _timestamp ) external payable requireIsOperational { require( msg.value > 0 && msg.value <= _FLIGHT_INSURANCE_CAP, "Flight insurance out of range" ); bytes32 _flightKey = keccak256( abi.encodePacked(_airline, _flight, _timestamp) ); require( _insurees[keccak256(abi.encodePacked(_flightKey, _msgSender()))] == 0, "Passenger already insured for given flight" ); _insurances[_flightKey].push(_msgSender()); _insurees[keccak256(abi.encodePacked(_flightKey, _msgSender()))] = msg.value; } /** * @dev Credits payouts to insurees * * Can only be called from FlightSuretyApp contract * */ function creditInsurees(bytes32 _flightKey) external requireIsOperational requireIsAuthorized { for (uint256 i = 0; i < _insurances[_flightKey].length; i++) { address _insuree = _insurances[_flightKey][i]; uint256 _insuredAmount = _insurees[ keccak256(abi.encodePacked(_flightKey, _insuree)) ]; if (_insuredAmount > 0) { uint256 _amount = _insuredAmount.add(_insuredAmount.div(2)); _insurees[keccak256(abi.encodePacked(_flightKey, _insuree))] = 0; _pendingWithdrawals[_insuree] = _pendingWithdrawals[_insuree].add(_amount); } } } /** * @dev Transfers eligible payout funds to insuree * */ function withdraw() external requireIsOperational { uint256 _amount = _pendingWithdrawals[_msgSender()]; require( _amount > 0, "Passenger has no pending withdrawal" ); _pendingWithdrawals[_msgSender()] = 0; (bool success,) = _msgSender().call{value: _amount}(""); require(success); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund() public payable requireIsOperational { require( super.hasRole(AIRLINER_ROLE, _msgSender()), "Sender does not have Airliner Role" ); require(!_airlines[_msgSender()].isFunded, "Airline is funded already"); require( msg.value >= _AIRLINE_REG_FEE, "Sent funding fee for a new airline is too low" ); _airlines[_msgSender()].isFunded = true; airlinesCount = airlinesCount.add(1); emit Funded(_msgSender(), _msgSender(), msg.value); } /** * @dev Receive ether function for funding smart contract. * */ receive() external payable requireIsOperational { emit Received(_msgSender(), _msgSender(), msg.value); } /** * @dev Fallback function for funding smart contract. * */ fallback() external payable requireIsOperational { emit Received(_msgSender(), _msgSender(), msg.value); } }
* @dev Transfers eligible payout funds to insuree/
function withdraw() external requireIsOperational { uint256 _amount = _pendingWithdrawals[_msgSender()]; require( _amount > 0, "Passenger has no pending withdrawal" ); _pendingWithdrawals[_msgSender()] = 0; require(success); }
2,571,094
[ 1, 1429, 18881, 21351, 293, 2012, 284, 19156, 358, 316, 2055, 73, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 3903, 2583, 2520, 2988, 287, 288, 203, 3639, 2254, 5034, 389, 8949, 273, 389, 9561, 1190, 9446, 1031, 63, 67, 3576, 12021, 1435, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 389, 8949, 405, 374, 16, 203, 5411, 315, 6433, 14348, 711, 1158, 4634, 598, 9446, 287, 6, 203, 3639, 11272, 203, 203, 3639, 389, 9561, 1190, 9446, 1031, 63, 67, 3576, 12021, 1435, 65, 273, 374, 31, 203, 203, 203, 3639, 2583, 12, 4768, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xE788E055568df59E8c832fC21d9A1dA12ae0bfC1/sources/contracts/Contract.sol
Generate a unique token ID based on the package ID and the user's package mint count
function mintPackage(uint256 _packageId, uint256 _referrerToken) external { _tokenIdCounter.increment(); require(_packageId > 0 && _packageId <= MAX_PACKAGES, "Invalid package ID"); require(referralCounts[referrers[_referrerToken]] < MAX_REFERRALS, "Referral limit reached"); require(userPackageMintCount[msg.sender][_packageId] < getMaxMintCount(_packageId), "Package mint limit reached"); require(getTotalPurchasedPackages(msg.sender) < MAX_PURCHASES_PER_USER, "Max packages per user reached"); uint256 tokenId = _tokenIdCounter.current(); address referrer = referrers[_referrerToken]; if (users[referrer].packageId == 0) { referrer = owner(); } if (referrer != address(0) && referrer != msg.sender) { users[referrer].referrals.push(msg.sender); referralCounts[referrer]++; } uint256 packagePrice = packages[_packageId].price.mul(10 ** DECIMALS); require(usdtToken.transferFrom(msg.sender, address(this), packagePrice), "USDT transfer failed"); users[msg.sender] = User({ packageId: _packageId, sponsor: referrer, referrals: new address[](0), referralRewards: 0, unilevelRewards: 0, stakedAmount: packagePrice, stakedTime: block.timestamp }); if (referrer != address(0) && referrer != msg.sender) { referrerTokens[msg.sender] = _referrerToken; } _mint(msg.sender, tokenId); _setTokenURI(tokenId, packages[_packageId]._tokenURIs); emit Purchase(msg.sender, _packageId); userPackageMintCount[msg.sender][_packageId]++; }
3,813,534
[ 1, 4625, 279, 3089, 1147, 1599, 2511, 603, 326, 2181, 1599, 471, 326, 729, 1807, 2181, 312, 474, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 2261, 12, 11890, 5034, 389, 5610, 548, 16, 2254, 5034, 389, 1734, 11110, 1345, 13, 3903, 288, 203, 3639, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 3639, 2583, 24899, 5610, 548, 405, 374, 597, 389, 5610, 548, 1648, 4552, 67, 19077, 55, 16, 315, 1941, 2181, 1599, 8863, 203, 3639, 2583, 12, 1734, 29084, 9211, 63, 1734, 370, 414, 63, 67, 1734, 11110, 1345, 13563, 411, 4552, 67, 30269, 54, 1013, 55, 16, 315, 1957, 29084, 1800, 8675, 8863, 203, 3639, 2583, 12, 1355, 2261, 49, 474, 1380, 63, 3576, 18, 15330, 6362, 67, 5610, 548, 65, 411, 7288, 49, 474, 1380, 24899, 5610, 548, 3631, 315, 2261, 312, 474, 1800, 8675, 8863, 203, 3639, 2583, 12, 588, 5269, 10262, 343, 8905, 11425, 12, 3576, 18, 15330, 13, 411, 4552, 67, 52, 1099, 1792, 4429, 55, 67, 3194, 67, 4714, 16, 315, 2747, 5907, 1534, 729, 8675, 8863, 203, 540, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 203, 3639, 1758, 14502, 273, 1278, 370, 414, 63, 67, 1734, 11110, 1345, 15533, 203, 3639, 309, 261, 5577, 63, 1734, 11110, 8009, 5610, 548, 422, 374, 13, 288, 203, 5411, 14502, 273, 3410, 5621, 203, 3639, 289, 203, 203, 3639, 309, 261, 1734, 11110, 480, 1758, 12, 20, 13, 597, 14502, 480, 1234, 18, 15330, 13, 288, 203, 5411, 3677, 63, 1734, 11110, 8009, 1734, 370, 1031, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 5411, 1278, 29084, 9211, 63, 1734, 11110, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-03 */ /** *Submitted for verification at Etherscan.io on 2021-11-03 */ /** *Submitted for verification at BscScan.com on 2021-10-30 */ // File: contracts/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ // constructor () internal { // _owner = msg.sender; // emit OwnershipTransferred(address(0), _owner); // } function ownerInit() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/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); function mint(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); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function blindBox(address seller, string calldata tokenURI, bool flag, address to, string calldata ownerId) external returns (uint256); function mintAliaForNonCrypto(uint256 price, address from) external returns (bool); function nonCryptoNFTVault() external returns(address); function mainPerecentage() external returns(uint256); function authorPercentage() external returns(uint256); function platformPerecentage() external returns(uint256); function updateAliaBalance(string calldata stringId, uint256 amount) external returns(bool); function getSellDetail(uint256 tokenId) external view returns (address, uint256, uint256, address, uint256, uint256, uint256); function getNonCryptoWallet(string calldata ownerId) external view returns(uint256); function getNonCryptoOwner(uint256 tokenId) external view returns(string memory); function adminOwner(address _address) external view returns(bool); function getAuthor(uint256 tokenIdFunction) external view returns (address); function _royality(uint256 tokenId) external view returns (uint256); function getrevenueAddressBlindBox(string calldata info) external view returns(address); function getboxNameByToken(uint256 token) external view returns(string memory); //Revenue share function addNonCryptoAuthor(string calldata artistId, uint256 tokenId, bool _isArtist) external returns(bool); function transferAliaArtist(address buyer, uint256 price, address nftVaultAddress, uint256 tokenId ) external returns(bool); function checkArtistOwner(string calldata artistId, uint256 tokenId) external returns(bool); function checkTokenAuthorIsArtist(uint256 tokenId) external returns(bool); function withdraw(uint) external; function deposit() payable external; // function approve(address spender, uint256 rawAmount) external; // BlindBox ref:https://noborderz.slack.com/archives/C0236PBG601/p1633942033011800?thread_ts=1633941154.010300&cid=C0236PBG601 function isSellable (string calldata name) external view returns(bool); function tokenURI(uint256 tokenId) external view returns (string memory); function ownerOf(uint256 tokenId) external view returns (address); function burn (uint256 tokenId) external; } // File: contracts/INFT.sol pragma solidity ^0.5.0; // import "../openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol"; interface INFT { function transferFromAdmin(address owner, address to, uint256 tokenId) external; function mintWithTokenURI(address to, string calldata tokenURI) external returns (uint256); function getAuthor(uint256 tokenIdFunction) external view returns (address); function updateTokenURI(uint256 tokenIdT, string calldata uriT) external; // function mint(address to, string calldata tokenURI) external returns (uint256); function transferOwnership(address newOwner) external; function ownerOf(uint256 tokenId) external view returns(address); function transferFrom(address owner, address to, uint256 tokenId) external; } // File: contracts/IFactory.sol pragma solidity ^0.5.0; contract IFactory { function create(string calldata name_, string calldata symbol_, address owner_) external returns(address); function getCollections(address owner_) external view returns(address [] memory); } // File: contracts/LPInterface.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 LPInterface { /** * @dev Returns the amount of tokens in existence. */ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // File: openzeppelin-solidity/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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/Proxy/DexStorage.sol pragma solidity ^0.5.0; /////////////////////////////////////////////////////////////////////////////////////////////////// /** * @title DexStorage * @dev Defining dex storage for the proxy contract. */ /////////////////////////////////////////////////////////////////////////////////////////////////// contract DexStorage { using SafeMath for uint256; address x; // dummy variable, never set or use its value in any logic contracts. It keeps garbage value & append it with any value set on it. IERC20 ALIA; INFT XNFT; IFactory factory; IERC20 OldNFTDex; IERC20 BUSD; IERC20 BNB; struct RDetails { address _address; uint256 percentage; } struct AuthorDetails { address _address; uint256 royalty; string ownerId; bool isSecondry; } // uint256[] public sellList; // this violates generlization as not tracking tokenIds agains nftContracts/collections but ignoring as not using it in logic anywhere (uncommented) mapping (uint256 => mapping(address => AuthorDetails)) internal _tokenAuthors; mapping (address => bool) public adminOwner; address payable public platform; address payable public authorVault; uint256 internal platformPerecentage; struct fixedSell { // address nftContract; // adding to support multiple NFT contracts buy/sell address seller; uint256 price; uint256 timestamp; bool isDollar; uint256 currencyType; } // stuct for auction struct auctionSell { address seller; address nftContract; address bidder; uint256 minPrice; uint256 startTime; uint256 endTime; uint256 bidAmount; bool isDollar; uint256 currencyType; // address nftAddress; } // tokenId => nftContract => fixedSell mapping (uint256 => mapping (address => fixedSell)) internal _saleTokens; mapping(address => bool) public _supportNft; // tokenId => nftContract => auctionSell mapping(uint256 => mapping ( address => auctionSell)) internal _auctionTokens; address payable public nonCryptoNFTVault; // tokenId => nftContract => ownerId mapping (uint256=> mapping (address => string)) internal _nonCryptoOwners; struct balances{ uint256 bnb; uint256 Alia; uint256 BUSD; } mapping (string => balances) internal _nonCryptoWallet; LPInterface LPAlia; LPInterface LPBNB; uint256 public adminDiscount; address admin; mapping (string => address) internal revenueAddressBlindBox; mapping (uint256=>string) internal boxNameByToken; bool public collectionConfig; uint256 public countCopy; mapping (uint256=> mapping( address => mapping(uint256 => bool))) _allowedCurrencies; IERC20 token; // struct offer { // address _address; // string ownerId; // uint256 currencyType; // uint256 price; // } // struct offers { // uint256 count; // mapping (uint256 => offer) _offer; // } // mapping(uint256 => mapping(address => offers)) _offers; uint256[] allowedArray; } // File: contracts/AuctionDex.sol pragma solidity ^0.5.0; contract AuctionDex is Ownable, DexStorage { event CancelSell(address indexed from, address nftContract, uint256 tokenId); event UpdatePrice(address indexed from, uint256 tokenId, uint256 newPrice, bool isDollar, address nftContract, uint256 baseCurrency, uint256[] allowedCurrencies); event OnAuction(address indexed seller, address nftContract, uint256 indexed tokenId, uint256 startPrice, uint256 endTime, uint256 baseCurrency); event Bid(address indexed bidder, address nftContract, uint256 tokenId, uint256 amount); event Claim(address indexed bidder, address nftContract, uint256 tokenId, uint256 amount, address seller, uint256 baseCurrency); event MintWithTokenURI(address indexed collection, uint256 indexed tokenId, address minter, string tokenURI); event BuyNFT(address indexed from, address nft_a, uint256 tokenId, address buyer, uint256 price, uint256 baseCurrency, uint256 calculated, uint256 currencyType); function() external payable {} // modifier to check if given collection is supported by DEX modifier isValid( address collection_) { require(_supportNft[collection_],"unsupported collection"); _; } function setOnAuction(address _contract,uint256 _tokenId, uint256 _minPrice, uint256 baseCurrency, uint256 _endTime) isValid(_contract) public { require(INFT(_contract).ownerOf(_tokenId) == msg.sender, "102"); // string storage boxName = boxNameByToken[_tokenId]; // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); require(baseCurrency <= 1, "121"); // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); _auctionTokens[_tokenId][_contract].seller = msg.sender; _auctionTokens[_tokenId][_contract].nftContract = _contract; _auctionTokens[_tokenId][_contract].minPrice = _minPrice; _auctionTokens[_tokenId][_contract].startTime = now; _auctionTokens[_tokenId][_contract].endTime = _endTime; _auctionTokens[_tokenId][_contract].currencyType = baseCurrency; INFT(_contract).transferFrom(msg.sender, address(this), _tokenId); emit OnAuction(msg.sender, _contract, _tokenId, _minPrice, _endTime, baseCurrency); } //mint & sell own/xanalia collection only function MintAndAuctionNFT(address to, string memory tokenURI, address _contract, uint256 _minPrice, string memory ownerId, uint256 _endTime, uint256 royality, uint256 baseCurrency) public { require(_contract == address(XNFT), "MintAndAuctionNFT function only supports non-user defined collection"); uint256 _tokenId; _tokenId = XNFT.mintWithTokenURI(to, string(abi.encodePacked("https://ipfs.infura.io:5001/api/v0/cat?arg=", tokenURI))); emit MintWithTokenURI(address(XNFT), _tokenId, msg.sender, tokenURI); _tokenAuthors[_tokenId][address(XNFT)].ownerId = ownerId; setOnAuction(_contract, _tokenId, _minPrice, baseCurrency, _endTime); if(royality > 0) { _tokenAuthors[_tokenId][address(XNFT)].royalty = royality; }else { _tokenAuthors[_tokenId][address(XNFT)].royalty = 25; } } function onAuctionOrNot(uint256 tokenId, address _contract) public view returns (bool){ if(_auctionTokens[tokenId][_contract].seller!=address(0)) return true; else return false; } function bnbTransferAuction(address _address, uint256 percentage, uint256 price) internal { address payable newAddress = address(uint160(_address)); uint256 initialBalance; uint256 newBalance; initialBalance = address(this).balance; BNB.withdraw((price / 1000) * percentage); newBalance = address(this).balance.sub(initialBalance); newAddress.transfer(newBalance); } // added _contract param in function to support generalization function placeBid(address _contract, uint256 _tokenId, uint256 _amount, bool awardType, address from) isValid(_contract) public{ auctionSell storage temp = _auctionTokens[_tokenId][_contract]; require(temp.currencyType == 0, "123"); require(temp.endTime >= now,"103"); require(temp.minPrice <= _amount, "105"); require(temp.bidAmount < _amount,"106"); token = BUSD; //IERC20(address(ALIA)); token.transferFrom(msg.sender, address(this), SafeMath.div(_amount,1000000000000)); temp.bidAmount > 0 && token.transfer(temp.bidder, SafeMath.div(temp.bidAmount,1000000000000)); temp.bidder = from; temp.bidAmount = _amount; emit Bid(from, temp.nftContract, _tokenId, _amount); } function placeBidBNB(address _contract, uint256 _tokenId, bool awardType, address from) isValid(_contract) payable public{ auctionSell storage temp = _auctionTokens[_tokenId][_contract]; require(temp.currencyType == 1, "123"); require(temp.endTime >= now,"103"); uint256 before_bal = BNB.balanceOf(address(this)); BNB.deposit.value(msg.value)(); uint256 after_bal = BNB.balanceOf(address(this)); uint256 _amount = after_bal - before_bal; require(temp.minPrice <= _amount, "105"); require(temp.bidAmount < _amount,"106"); if(temp.bidAmount > 0) bnbTransferAuction(temp.bidder, 1000, temp.bidAmount); temp.bidder = from; temp.bidAmount = _amount; emit Bid(from, temp.nftContract, _tokenId, _amount); } // added _contract param in function to support generalization function claimAuction(address _contract, uint256 _tokenId, bool awardType, string memory ownerId, address from) isValid(_contract) public { auctionSell storage temp = _auctionTokens[_tokenId][_contract]; require(temp.endTime < now,"103"); require(temp.minPrice > 0,"104"); require(msg.sender==temp.bidder,"107"); INFT(temp.nftContract).transferFrom(address(this), temp.bidder, _tokenId); (uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) = getPercentages(_tokenId, _contract); if(temp.currencyType < 1){ uint256 price = SafeMath.div(temp.bidAmount,1000000000000); token = BUSD; //IERC20(address(ALIA)); if(blindRAddress == address(0x0)){ token.transfer( platform, SafeMath.div(SafeMath.mul(price ,platformPerecentage ) , 1000)); } if(_contract == address(XNFT)){ // currently only supporting royality for non-user defined collection token.transfer( blindRAddress, SafeMath.div(SafeMath.mul(price ,authorPercentage ) , 1000)); } token.transfer( temp.seller, SafeMath.div(SafeMath.mul(price ,mainPerecentage ) , 1000)); }else { if(blindRAddress == address(0x0)){ bnbTransferAuction( platform, platformPerecentage, temp.bidAmount); } if(_contract == address(XNFT)){ // currently only supporting royality for non-user defined collection bnbTransferAuction( platform, authorPercentage, temp.bidAmount); } bnbTransferAuction( platform, mainPerecentage, temp.bidAmount); } // in case of user-defined collection, sell will receive amount = bidAmount - platformPerecentage amount // author will get nothing as royality not tracking for user-defined collections emit Claim(temp.bidder, temp.nftContract, _tokenId, temp.bidAmount, temp.seller, temp.currencyType); delete _auctionTokens[_tokenId][_contract]; } function calculatePrice(uint256 _price, uint256 base, uint256 currencyType, uint256 tokenId, address seller, address nft_a) public view returns(uint256 price) { price = _price; (uint112 _reserve0, uint112 _reserve1,) =LPBNB.getReserves(); if(nft_a == address(XNFT) && _tokenAuthors[tokenId][address(XNFT)]._address == admin && adminOwner[seller] && adminDiscount > 0){ // getAuthor() can break generalization if isn't supported in Collection.sol. SOLUTION: royality isn't paying for user-defined collections price = _price- ((_price * adminDiscount) / 1000); } if(currencyType == 0 && base == 1){ price = SafeMath.div(SafeMath.mul(price,SafeMath.mul(_reserve1,1000000000000)),_reserve0); } else if(currencyType == 1 && base == 0){ price = SafeMath.div(SafeMath.mul(price,_reserve0),SafeMath.mul(_reserve1,1000000000000)); } } function getPercentages(uint256 tokenId, address nft_a) public view returns(uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) { if(_tokenAuthors[tokenId][nft_a].royalty > 0 && nft_a == address(XNFT)) { // royality for XNFT only (non-user defined collection) mainPerecentage = SafeMath.sub(SafeMath.sub(1000,_tokenAuthors[tokenId][nft_a].royalty),platformPerecentage); //50 authorPercentage = _tokenAuthors[tokenId][nft_a].royalty; } else { mainPerecentage = SafeMath.sub(1000, platformPerecentage); } blindRAddress = revenueAddressBlindBox[boxNameByToken[tokenId]]; if(blindRAddress != address(0x0)){ mainPerecentage = 865; authorPercentage =135; } } function buyNFT(address nft_a,uint256 tokenId, string memory ownerId, uint256 currencyType) isValid(nft_a) public{ fixedSell storage temp = _saleTokens[tokenId][nft_a]; require(temp.price > 0, "108"); require(_allowedCurrencies[tokenId][nft_a][currencyType] && currencyType != 1, "123"); uint256 price = calculatePrice(temp.price, temp.currencyType, currencyType, tokenId, temp.seller, nft_a); (uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) = getPercentages(tokenId, nft_a); price = SafeMath.div(price,1000000000000); BUSD.transferFrom(msg.sender, platform, SafeMath.div(SafeMath.mul(price ,platformPerecentage), 1000)); if( nft_a == address(XNFT)) { BUSD.transferFrom(msg.sender,blindRAddress, SafeMath.div(SafeMath.mul(price ,authorPercentage), 1000) ); } BUSD.transferFrom(msg.sender, temp.seller,SafeMath.div(SafeMath.mul(price ,mainPerecentage), 1000) ); clearMapping(tokenId, nft_a, temp.price, temp.currencyType, price, currencyType); } function clearMapping(uint256 tokenId, address nft_a, uint256 price, uint256 baseCurrency, uint256 calcultated, uint256 currencyType ) internal { INFT(nft_a).transferFrom(address(this), msg.sender, tokenId); delete _saleTokens[tokenId][nft_a]; for(uint256 i = 0; i <=1 ; i++) { _allowedCurrencies[tokenId][nft_a][i] = false; } // _allowedCurrencies[tokenId][1] = false; // _allowedCurrencies[tokenId][2] = false; emit BuyNFT(msg.sender, nft_a, tokenId, msg.sender, price, baseCurrency, calcultated, currencyType); } }
added _contract param in function to support generalization
function claimAuction(address _contract, uint256 _tokenId, bool awardType, string memory ownerId, address from) isValid(_contract) public { auctionSell storage temp = _auctionTokens[_tokenId][_contract]; require(temp.endTime < now,"103"); require(temp.minPrice > 0,"104"); require(msg.sender==temp.bidder,"107"); INFT(temp.nftContract).transferFrom(address(this), temp.bidder, _tokenId); (uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) = getPercentages(_tokenId, _contract); if(temp.currencyType < 1){ uint256 price = SafeMath.div(temp.bidAmount,1000000000000); if(blindRAddress == address(0x0)){ token.transfer( platform, SafeMath.div(SafeMath.mul(price ,platformPerecentage ) , 1000)); } token.transfer( blindRAddress, SafeMath.div(SafeMath.mul(price ,authorPercentage ) , 1000)); } token.transfer( temp.seller, SafeMath.div(SafeMath.mul(price ,mainPerecentage ) , 1000)); if(blindRAddress == address(0x0)){ bnbTransferAuction( platform, platformPerecentage, temp.bidAmount); } bnbTransferAuction( platform, authorPercentage, temp.bidAmount); } bnbTransferAuction( platform, mainPerecentage, temp.bidAmount);
36,251
[ 1, 9665, 389, 16351, 579, 316, 445, 358, 2865, 7470, 1588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7516, 37, 4062, 12, 2867, 389, 16351, 16, 2254, 5034, 389, 2316, 548, 16, 1426, 279, 2913, 559, 16, 533, 3778, 29456, 16, 1758, 628, 13, 4908, 24899, 16351, 13, 1071, 288, 203, 565, 279, 4062, 55, 1165, 2502, 1906, 273, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 15533, 203, 565, 2583, 12, 5814, 18, 409, 950, 411, 2037, 10837, 23494, 8863, 203, 565, 2583, 12, 5814, 18, 1154, 5147, 405, 374, 10837, 21869, 8863, 203, 565, 2583, 12, 3576, 18, 15330, 631, 5814, 18, 19773, 765, 10837, 23054, 8863, 203, 565, 2120, 4464, 12, 5814, 18, 82, 1222, 8924, 2934, 13866, 1265, 12, 2867, 12, 2211, 3631, 1906, 18, 19773, 765, 16, 389, 2316, 548, 1769, 203, 377, 261, 11890, 5034, 2774, 2173, 557, 319, 410, 16, 2254, 5034, 2869, 16397, 16, 1758, 29696, 54, 1887, 13, 273, 22612, 2998, 1023, 24899, 2316, 548, 16, 389, 16351, 1769, 203, 377, 203, 565, 309, 12, 5814, 18, 7095, 559, 411, 404, 15329, 203, 3639, 2254, 5034, 6205, 273, 14060, 10477, 18, 2892, 12, 5814, 18, 19773, 6275, 16, 21, 12648, 2787, 1769, 203, 377, 309, 12, 3083, 728, 54, 1887, 422, 1758, 12, 20, 92, 20, 3719, 95, 203, 1377, 1147, 18, 13866, 12, 4072, 16, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 12, 8694, 225, 269, 9898, 2173, 557, 319, 410, 262, 269, 4336, 10019, 203, 377, 289, 203, 377, 1147, 18, 13866, 12, 29696, 54, 1887, 16, 14060, 10477, 18, 2892, 12, 9890, 10477, 2 ]
pragma solidity ^0.4.24; contract Enum { enum Operation { Call, DelegateCall, Create } } contract EtherPaymentFallback { /// @dev Fallback function accepts Ether transactions. function () external payable { } } contract Executor is EtherPaymentFallback { event ContractCreation(address newContract); function execute(address to, uint256 value, bytes data, Enum.Operation operation, uint256 txGas) internal returns (bool success) { if (operation == Enum.Operation.Call) success = executeCall(to, value, data, txGas); else if (operation == Enum.Operation.DelegateCall) success = executeDelegateCall(to, data, txGas); else { address newContract = executeCreate(data); success = newContract != 0; emit ContractCreation(newContract); } } function executeCall(address to, uint256 value, bytes data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } function executeDelegateCall(address to, bytes data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } function executeCreate(bytes data) internal returns (address newContract) { // solium-disable-next-line security/no-inline-assembly assembly { newContract := create(0, add(data, 0x20), mload(data)) } } } contract SelfAuthorized { modifier authorized() { require(msg.sender == address(this), "Method can only be called from this contract"); _; } } contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(Module module); event DisabledModule(Module module); address public constant SENTINEL_MODULES = address(0x1); mapping (address => address) internal modules; function setupModules(address to, bytes data) internal { require(modules[SENTINEL_MODULES] == 0, "Modules have already been initialized"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != 0) // Setup has to complete successfully or transaction fails. require(executeDelegateCall(to, data, gasleft()), "Could not finish initialization"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @param module Module to be whitelisted. function enableModule(Module module) public authorized { // Module address cannot be null or sentinel. require(address(module) != 0 && address(module) != SENTINEL_MODULES, "Invalid module address provided"); // Module cannot be added twice. require(modules[module] == 0, "Module has already been added"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(Module prevModule, Module module) public authorized { // Validate module address and check that it corresponds to module index. require(address(module) != 0 && address(module) != SENTINEL_MODULES, "Invalid module address provided"); require(modules[prevModule] == address(module), "Invalid prevModule, module pair provided"); modules[prevModule] = modules[module]; modules[module] = 0; emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule(address to, uint256 value, bytes data, Enum.Operation operation) public returns (bool success) { // Only whitelisted modules are allowed. require(modules[msg.sender] != 0, "Method can only be called from an enabled module"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); } /// @dev Returns array of modules. /// @return Array of modules. function getModules() public view returns (address[]) { // Calculate module count uint256 moduleCount = 0; address currentModule = modules[SENTINEL_MODULES]; while(currentModule != SENTINEL_MODULES) { currentModule = modules[currentModule]; moduleCount ++; } address[] memory array = new address[](moduleCount); // populate return array moduleCount = 0; currentModule = modules[SENTINEL_MODULES]; while(currentModule != SENTINEL_MODULES) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount ++; } return array; } } contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address public constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "Owners have already been setup"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != 0 && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == 0, "Duplicate owner address provided"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null. require(owner != 0 && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == 0, "Address is already an owner"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner(address prevOwner, address owner, uint256 _threshold) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold"); // Validate owner address and check that it corresponds to owner index. require(owner != 0 && owner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == owner, "Invalid prevOwner, owner pair provided"); owners[prevOwner] = owners[owner]; owners[owner] = 0; ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner(address prevOwner, address oldOwner, address newOwner) public authorized { // Owner address cannot be null. require(newOwner != 0 && newOwner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[newOwner] == 0, "Address is already an owner"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != 0 && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = 0; emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owners[owner] != 0; } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[]) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while(currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index ++; } return array; } } contract MasterCopy is SelfAuthorized { // masterCopy always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address masterCopy; /// @dev Allows to upgrade the contract. This can only be done via a Safe transaction. /// @param _masterCopy New contract address. function changeMasterCopy(address _masterCopy) public authorized { // Master copy address cannot be null. require(_masterCopy != 0, "Invalid master copy address provided"); masterCopy = _masterCopy; } } contract Module is MasterCopy { ModuleManager public manager; modifier authorized() { require(msg.sender == address(manager), "Method can only be called from manager"); _; } function setManager() internal { // manager can only be 0 at initalization of contract. // Check ensures that setup function can only be called once. require(address(manager) == 0, "Manager has already been set"); manager = ModuleManager(msg.sender); } } contract SignatureDecoder { /// @dev Recovers address who signed the message /// @param messageHash operation ethereum signed message hash /// @param messageSignature message `txHash` signature /// @param pos which signature to read function recoverKey ( bytes32 messageHash, bytes messageSignature, uint256 pos ) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = signatureSplit(messageSignature, pos); return ecrecover(messageHash, v, r, s); } /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` /// @param pos which signature to read /// @param signatures concatenated rsv signatures function signatureSplit(bytes signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solium-disable-next-line security/no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } contract StateChannelModule is Module, SignatureDecoder { string public constant NAME = "State Channel Module"; string public constant VERSION = "0.0.2"; // isExecuted mapping allows to check if a transaction (by hash) was already executed. mapping (bytes32 => uint256) public isExecuted; /// @dev Setup function sets manager function setup() public { setManager(); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param nonce Nonce used for this Safe transaction. /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes data, Enum.Operation operation, uint256 nonce, bytes signatures ) public { bytes32 transactionHash = getTransactionHash(to, value, data, operation, nonce); require(isExecuted[transactionHash] == 0, "Transaction already executed"); checkHash(transactionHash, signatures); // Mark as executed and execute transaction. isExecuted[transactionHash] = 1; require(manager.execTransactionFromModule(to, value, data, operation), "Could not execute transaction"); } function checkHash(bytes32 transactionHash, bytes signatures) internal view { // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint256 i; uint256 threshold = OwnerManager(manager).getThreshold(); // Validate threshold is reached. for (i = 0; i < threshold; i++) { currentOwner = recoverKey(transactionHash, signatures, i); require(OwnerManager(manager).isOwner(currentOwner), "Signature not provided by owner"); require(currentOwner > lastOwner, "Signatures are not ordered by owner address"); lastOwner = currentOwner; } } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes data, Enum.Operation operation, uint256 nonce ) public view returns (bytes32) { return keccak256(abi.encodePacked(byte(0x19), byte(0), this, to, value, data, operation, nonce)); } }
manager can only be 0 at initalization of contract. Check ensures that setup function can only be called once.
function setManager() internal { require(address(manager) == 0, "Manager has already been set"); manager = ModuleManager(msg.sender); }
7,301,233
[ 1, 4181, 848, 1338, 506, 374, 622, 1208, 287, 1588, 434, 6835, 18, 2073, 11932, 716, 3875, 445, 848, 1338, 506, 2566, 3647, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1318, 1435, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 12, 2867, 12, 4181, 13, 422, 374, 16, 315, 1318, 711, 1818, 2118, 444, 8863, 203, 3639, 3301, 273, 5924, 1318, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x02173cf42495ab5f4C13680a0214Df1bEB847a09/sources/MasterChef.sol
Accumulated RMTs per share, times 1e12. See below.
uint256 accRmtPerShare;
9,378,157
[ 1, 8973, 5283, 690, 534, 6152, 87, 1534, 7433, 16, 4124, 404, 73, 2138, 18, 2164, 5712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4078, 54, 1010, 2173, 9535, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x0f256550f8311d063c55424D080F948afea26319/sources/LendingPool_flat.sol
Claim back your poolToken. Unlocks the amount deposited + gained and burns the eToken. Check to see if user has enough funds, and amount > 0 Updates User balance burn eToken
function withdraw(uint256 _amount) external { require(_balances[msg.sender].balance >= _amount && _amount > 0); uint256 totalAmount = _amount * 10**18; _balances[msg.sender].balance = _balances[msg.sender].balance.sub(totalAmount); _poolTokenSupply = _poolTokenSupply.sub(totalAmount); _burn(msg.sender, totalAmount); poolToken.transfer(msg.sender, totalAmount); emit Withdraw(msg.sender, totalAmount); }
7,113,539
[ 1, 9762, 1473, 3433, 2845, 1345, 18, 3967, 87, 326, 3844, 443, 1724, 329, 397, 314, 8707, 471, 18305, 87, 326, 425, 1345, 18, 2073, 358, 2621, 309, 729, 711, 7304, 284, 19156, 16, 471, 3844, 405, 374, 15419, 2177, 11013, 18305, 425, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 3903, 288, 7010, 3639, 2583, 24899, 70, 26488, 63, 3576, 18, 15330, 8009, 12296, 1545, 389, 8949, 597, 389, 8949, 405, 374, 1769, 7010, 540, 203, 3639, 2254, 5034, 2078, 6275, 273, 389, 8949, 380, 1728, 636, 2643, 31, 203, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 12296, 273, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 12296, 18, 1717, 12, 4963, 6275, 1769, 27699, 3639, 389, 6011, 1345, 3088, 1283, 273, 389, 6011, 1345, 3088, 1283, 18, 1717, 12, 4963, 6275, 1769, 203, 540, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 2078, 6275, 1769, 203, 3639, 2845, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 2078, 6275, 1769, 203, 540, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 2078, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9b2Dc6e830320C48044a555263cBA4CdeB0FB201/sources/contracts/DeHiveTokensale.sol
* @notice For purchase with NUX token only. Available only for tokensale @param nuxAmount Amount of the NUX token/
function purchaseDHVwithNUX(uint256 nuxAmount) external onlyPreSale whenNotPaused correctGas { require(nuxAmount > 0, "Zero amount"); uint256 purchaseAmount = _calcPurchaseAmount(NUXToken, nuxAmount); require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); require(purchasedWithNUX.add(purchaseAmount) <= PRE_SALE_DHV_NUX_POOL, "Not enough DHV in NUX pool"); purchasedWithNUX = purchasedWithNUX.add(purchaseAmount); purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount); IERC20Upgradeable(NUXToken).safeTransferFrom(_msgSender(), _treasury, nuxAmount); emit DHVPurchased(_msgSender(), NUXToken, purchaseAmount); }
3,125,520
[ 1, 1290, 23701, 598, 423, 57, 60, 1147, 1338, 18, 15633, 1338, 364, 2430, 5349, 225, 290, 2616, 6275, 16811, 434, 326, 423, 57, 60, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 16501, 58, 1918, 50, 57, 60, 12, 11890, 5034, 290, 2616, 6275, 13, 3903, 1338, 1386, 30746, 1347, 1248, 28590, 3434, 27998, 288, 203, 3639, 2583, 12, 82, 2616, 6275, 405, 374, 16, 315, 7170, 3844, 8863, 203, 3639, 2254, 5034, 23701, 6275, 273, 389, 12448, 23164, 6275, 12, 50, 57, 60, 1345, 16, 290, 2616, 6275, 1769, 203, 3639, 2583, 12, 12688, 12104, 6275, 18, 1289, 12, 12688, 343, 8905, 63, 3576, 18, 15330, 5717, 1648, 943, 5157, 6275, 16, 315, 13528, 2935, 12428, 8863, 203, 203, 203, 3639, 2583, 12, 12688, 343, 8905, 1190, 50, 57, 60, 18, 1289, 12, 12688, 12104, 6275, 13, 1648, 7071, 67, 5233, 900, 67, 16501, 58, 67, 50, 57, 60, 67, 20339, 16, 315, 1248, 7304, 24141, 58, 316, 423, 57, 60, 2845, 8863, 203, 3639, 5405, 343, 8905, 1190, 50, 57, 60, 273, 5405, 343, 8905, 1190, 50, 57, 60, 18, 1289, 12, 12688, 12104, 6275, 1769, 203, 203, 3639, 5405, 343, 8905, 63, 67, 3576, 12021, 1435, 65, 273, 5405, 343, 8905, 63, 67, 3576, 12021, 1435, 8009, 1289, 12, 12688, 12104, 6275, 1769, 203, 3639, 467, 654, 39, 3462, 10784, 429, 12, 50, 57, 60, 1345, 2934, 4626, 5912, 1265, 24899, 3576, 12021, 9334, 389, 27427, 345, 22498, 16, 290, 2616, 6275, 1769, 203, 203, 3639, 3626, 24141, 58, 10262, 343, 8905, 24899, 3576, 12021, 9334, 423, 57, 60, 1345, 16, 23701, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0xb20ED2192a949388173630fD03FC1e98D0036847/sources/MasterChef.sol
* @title SafeBEP20 @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./
library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IBEP20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IBEP20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } function _callOptionalReturn(IBEP20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } }
11,362,418
[ 1, 9890, 5948, 52, 3462, 225, 4266, 10422, 6740, 9722, 52, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 5948, 52, 3462, 364, 467, 5948, 52, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 5948, 52, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 445, 4183, 5912, 12, 203, 3639, 467, 5948, 52, 3462, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 467, 5948, 52, 3462, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 1265, 18, 9663, 16, 628, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 12053, 537, 12, 203, 3639, 467, 5948, 52, 3462, 1147, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 261, 1132, 422, 374, 13, 747, 261, 2316, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 13, 422, 374, 3631, 203, 5411, 296, 9890, 5948, 52, 3462, 30, 6617, 537, 628, 1661, 17, 7124, 358, 1661, 17, 7124, 1699, 1359, 11, 203, 3639, 11272, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 2 ]
./full_match/1/0x17B354dD2595411ff79041f930e491A4Df39A278/sources/src/data/VerifierLookupTable.sol
@notice Updates the verifier for the provided `batchSize`. @param batchSize The batch size to add the verifier for. @param verifier The verifier for a batch of size `batchSize`. @return oldVerifier The old verifier instance associated with this batch size. @custom:reverts string If the caller is not the owner.
function updateVerifier(uint256 batchSize, ITreeVerifier verifier) public onlyOwner returns (ITreeVerifier oldVerifier) { oldVerifier = verifier_lut[batchSize]; verifier_lut[batchSize] = verifier; emit VerifierUpdated(batchSize, address(oldVerifier), address(verifier)); }
3,853,631
[ 1, 5121, 326, 20130, 364, 326, 2112, 1375, 5303, 1225, 8338, 225, 16494, 1021, 2581, 963, 358, 527, 326, 20130, 364, 18, 225, 20130, 1021, 20130, 364, 279, 2581, 434, 963, 1375, 5303, 1225, 8338, 327, 1592, 17758, 1021, 1592, 20130, 791, 3627, 598, 333, 2581, 963, 18, 632, 3662, 30, 266, 31537, 533, 971, 326, 4894, 353, 486, 326, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 17758, 12, 11890, 5034, 16494, 16, 467, 2471, 17758, 20130, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 1135, 261, 1285, 992, 17758, 1592, 17758, 13, 203, 565, 288, 203, 3639, 1592, 17758, 273, 20130, 67, 80, 322, 63, 5303, 1225, 15533, 203, 3639, 20130, 67, 80, 322, 63, 5303, 1225, 65, 273, 20130, 31, 203, 3639, 3626, 6160, 1251, 7381, 12, 5303, 1225, 16, 1758, 12, 1673, 17758, 3631, 1758, 12, 31797, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "../util/Ownable.sol"; import "../util/SafeMath.sol"; import "../util/RLP.sol"; import "../storage/KeyValueStorage.sol"; import "../ip-organisations/IPR.sol"; import "../ip-organisations/IPOrganisations.sol"; import "../util/ECRecovery.sol"; import "./Marketplaces.sol"; /** * @title Exchange * @author Civic Ledger */ contract ExchangeSubmitOrder is Ownable { using SafeMath for uint256; using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; uint256 constant STATUS_PENDING = 1; KeyValueStorage internal storageContract; struct Order { uint256 ipOrganisationIndex; uint256 ipTypeIndex; uint256 ipIndex; address orderTakerAddress; address marketplaceAddress; uint256 orderType; uint256 paymentCurrency; address paymentTokenAddress; uint256 paymentAmountInWei; uint256 nonce; uint256 timestamp; address feeRecipientAddress; uint256 feeAmountInWei; uint8 v; bytes32 r; bytes32 s; } /** * @dev constructor * @param _storageAddress Address of central storage contract */ constructor(address _storageAddress) public { storageContract = KeyValueStorage(_storageAddress); } /** * @dev Checks to make sure the Exchange contract is calling */ modifier onlyOwnerOrExchangeContract() { address exchangeAddress = storageContract.getAddress(keccak256("contract.name", "Exchange")); require(msg.sender == exchangeAddress); _; } /// @dev submit an order /// @param _order RLP list of arguments (TODO) function submitOrder(bytes _order) external onlyOwnerOrExchangeContract() { // create order from the RLP encoded arguments Order memory order = getOrder(_order); checkIsRegisteredMarketplace(order.marketplaceAddress); // order taker address cannot be empty require(order.orderTakerAddress != address(0)); // marketplace address cannot be empty require(order.marketplaceAddress != address(0)); // if a fee is provided then fee recipient cannot be empty if (order.feeAmountInWei > 0) { require(order.feeRecipientAddress != address(0)); } // check marketplace order nonce to stop replays require(storageContract.getBool(keccak256("orders.marketplace.nonce", order.marketplaceAddress, order.nonce)) == false); // get ip type token address address ipTypeAddress = getIPTypeTokenAddress(order.ipOrganisationIndex, order.ipTypeIndex); require(ipTypeAddress != address(0)); IPR ipRightToken = IPR(ipTypeAddress); // validate IP right exists require(ipRightToken.exists(order.ipIndex)); // validate IP right is transferrable/licensable require(ipRightToken.isValidOrderType(order.ipIndex, order.orderType) == true); // check signature belongs to order taker bytes32 orderHash = hashOrder(order); address signerAddress = ECRecovery.recover(orderHash, order.v, order.r, order.s); require (signerAddress == order.orderTakerAddress); // get new order index for marketplace uint256 nextIndex = storageContract.getUint(keccak256("orders.nextIndex", order.marketplaceAddress)); // record order storeOrder(nextIndex, order, signerAddress, STATUS_PENDING); // mark nonce as used storageContract.setBool(keccak256("orders.marketplace.nonce", order.marketplaceAddress, order.nonce), true); // increment the marketplace index for next registration storageContract.setUint(keccak256("orders.nextIndex", order.marketplaceAddress), nextIndex.add(1)); } function getOrder(bytes _order) internal pure returns(Order) { // must be a list of parameters RLPReader.RLPItem[] memory itemList = _order.toRlpItem().toList(); return Order( itemList[0].toUint(), // ipOrganisationIndex itemList[1].toUint(), // ipTypeIndex itemList[2].toUint(), // ipIndex itemList[3].toAddress(), // orderTakerAddress itemList[4].toAddress(), // marketplaceAddress itemList[5].toUint(), // orderType itemList[6].toUint(), // paymentCurrency itemList[7].toAddress(), // paymentTokenAddress itemList[8].toUint(), // paymentAmountInWei itemList[9].toUint(), // nonce itemList[10].toUint(), // timestamp itemList[11].toAddress(), // feeRecipientAddress itemList[12].toUint(), // feeAmountInWei uint8(itemList[13].toUint()), // signature v itemList[14].toBytes32(), // signature r itemList[15].toBytes32() // signature s ); } function getIPTypeTokenAddress(uint256 _ipOrganisationIndex, uint256 _ipTypeIndex) internal view returns(address) { IPOrganisations ipOrganisations = IPOrganisations(storageContract.getAddress(keccak256("contract.name", "IPOrganisations"))); return ipOrganisations.ipTypeAddressAtIndex(_ipOrganisationIndex, _ipTypeIndex); } function hashOrder(Order _order) internal pure returns(bytes32) { return keccak256( _order.ipOrganisationIndex, _order.ipTypeIndex, _order.ipIndex, _order.orderTakerAddress, _order.marketplaceAddress, _order.orderType, _order.paymentCurrency, _order.paymentTokenAddress, _order.paymentAmountInWei, _order.nonce, _order.timestamp, _order.feeRecipientAddress, _order.feeAmountInWei ); } function storeOrder(uint256 _orderIndex, Order _order, address _signerAddress, uint256 _status) internal { // store details storageContract.setUint(keccak256("order.status", _order.marketplaceAddress, _orderIndex), _status); storageContract.setUint(keccak256("order.ipo", _order.marketplaceAddress, _orderIndex), _order.ipOrganisationIndex); storageContract.setUint(keccak256("order.ipType", _order.marketplaceAddress, _orderIndex), _order.ipTypeIndex); storageContract.setUint(keccak256("order.ip", _order.marketplaceAddress, _orderIndex), _order.ipIndex); storageContract.setAddress(keccak256("order.taker.address", _order.marketplaceAddress, _orderIndex), _order.orderTakerAddress); storageContract.setAddress(keccak256("order.marketplace.address", _order.marketplaceAddress, _orderIndex), _order.marketplaceAddress); storageContract.setUint(keccak256("order.type", _order.marketplaceAddress, _orderIndex), _order.orderType); storageContract.setUint(keccak256("order.payment.currency", _order.marketplaceAddress, _orderIndex), _order.paymentCurrency); storageContract.setAddress(keccak256("order.payment.token", _order.marketplaceAddress, _orderIndex), _order.paymentTokenAddress); storageContract.setUint(keccak256("order.payment.amount", _order.marketplaceAddress, _orderIndex), _order.paymentAmountInWei); storageContract.setUint(keccak256("order.nonce", _order.marketplaceAddress, _orderIndex), _order.nonce); storageContract.setUint(keccak256("order.timestamp", _order.marketplaceAddress, _orderIndex), _order.timestamp); storageContract.setAddress(keccak256("order.fee.recipient", _order.marketplaceAddress, _orderIndex), _order.feeRecipientAddress); storageContract.setUint(keccak256("order.fee.amount", _order.marketplaceAddress, _orderIndex), _order.feeAmountInWei); storageContract.setUint8(keccak256("order.signature.v", _order.marketplaceAddress, _orderIndex), _order.v); storageContract.setBytes32(keccak256("order.signature.r", _order.marketplaceAddress, _orderIndex), _order.r); storageContract.setBytes32(keccak256("order.signature.s", _order.marketplaceAddress, _orderIndex), _order.s); storageContract.setAddress(keccak256("order.signature.address", _order.marketplaceAddress, _orderIndex), _signerAddress); storageContract.setBool(keccak256("order.exists", _order.marketplaceAddress, _orderIndex), true); } /// @dev Checks that sender is a registered marketplace /// @param _marketplaceAddress Address of the marketpalce to check function checkIsRegisteredMarketplace(address _marketplaceAddress) internal view { Marketplaces marketplaces = Marketplaces(storageContract.getAddress(keccak256("contract.name", "Marketplaces"))); require(marketplaces.isRegistered(_marketplaceAddress)); } }
check signature belongs to order taker
bytes32 orderHash = hashOrder(order);
1,021,140
[ 1, 1893, 3372, 11081, 358, 1353, 268, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1731, 1578, 1353, 2310, 273, 1651, 2448, 12, 1019, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]